diff options
Diffstat (limited to 'src/ooxml/testcases')
273 files changed, 0 insertions, 59719 deletions
diff --git a/src/ooxml/testcases/org/apache/poi/benchmark/AddImageBench.java b/src/ooxml/testcases/org/apache/poi/benchmark/AddImageBench.java deleted file mode 100644 index c1cf799c25..0000000000 --- a/src/ooxml/testcases/org/apache/poi/benchmark/AddImageBench.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.benchmark; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openjdk.jmh.annotations.*; -import org.openjdk.jmh.profile.GCProfiler; -import org.openjdk.jmh.profile.StackProfiler; -import org.openjdk.jmh.runner.Runner; -import org.openjdk.jmh.runner.RunnerException; -import org.openjdk.jmh.runner.options.Options; -import org.openjdk.jmh.runner.options.OptionsBuilder; - -import java.util.concurrent.TimeUnit; - - -@BenchmarkMode(Mode.AverageTime) -@OutputTimeUnit(TimeUnit.MICROSECONDS) -@Warmup(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS ) -@Measurement(iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS) -@State(Scope.Benchmark) -public class AddImageBench { - - private Workbook wb; - private CreationHelper helper; - private byte[] bytes; - private Sheet sheet; - - @Setup(Level.Iteration) - public void doit() { - wb = new XSSFWorkbook(); - helper = wb.getCreationHelper(); - //add a picture in this workbook. - - bytes = HSSFTestDataSamples.getTestDataFileContent("45829.png"); - sheet = wb.createSheet(); - } - - @Benchmark - public void benchCreatePicture() throws Exception { - Drawing drawing = sheet.createDrawingPatriarch(); - - ClientAnchor anchor = helper.createClientAnchor(); - anchor.setCol1(1); - anchor.setRow1(1); - drawing.createPicture(anchor, wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG)); - - } - - public static void main(String[] args) throws RunnerException { - Options opt = new OptionsBuilder() - .include(".*" + AddImageBench.class.getSimpleName() + ".*") - .addProfiler(StackProfiler.class) - .addProfiler(GCProfiler.class) - .forks(1) - .build(); - - new Runner(opt).run(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/extractor/ooxml/TestExtractorFactory.java b/src/ooxml/testcases/org/apache/poi/extractor/ooxml/TestExtractorFactory.java deleted file mode 100644 index b94a3454de..0000000000 --- a/src/ooxml/testcases/org/apache/poi/extractor/ooxml/TestExtractorFactory.java +++ /dev/null @@ -1,462 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.extractor.ooxml; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.extractor.ExtractorFactory.createExtractor; -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.assertNull; -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.IOException; -import java.util.Locale; -import java.util.stream.Stream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.extractor.POIOLE2TextExtractor; -import org.apache.poi.extractor.POITextExtractor; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.extractor.EventBasedExcelExtractor; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.ooxml.extractor.POIXMLExtractorFactory; -import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.poifs.filesystem.FileMagic; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor; -import org.apache.poi.xssf.extractor.XSSFExcelExtractor; -import org.apache.xmlbeans.XmlException; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; - -/** - * Test that the extractor factory plays nicely - */ -class TestExtractorFactory { - - private static final POIDataSamples ssTests = POIDataSamples.getSpreadSheetInstance(); - private static final File xls = getFileAndCheck(ssTests, "SampleSS.xls"); - private static final File xlsx = getFileAndCheck(ssTests, "SampleSS.xlsx"); - @SuppressWarnings("unused") - private static final File xlsxStrict = getFileAndCheck(ssTests, "SampleSS.strict.xlsx"); - private static final File xltx = getFileAndCheck(ssTests, "test.xltx"); - private static final File xlsEmb = getFileAndCheck(ssTests, "excel_with_embeded.xls"); - private static final File xlsb = getFileAndCheck(ssTests, "testVarious.xlsb"); - - private static final POIDataSamples wpTests = POIDataSamples.getDocumentInstance(); - private static final File doc = getFileAndCheck(wpTests, "SampleDoc.doc"); - private static final File doc6 = getFileAndCheck(wpTests, "Word6.doc"); - private static final File doc95 = getFileAndCheck(wpTests, "Word95.doc"); - private static final File docx = getFileAndCheck(wpTests, "SampleDoc.docx"); - private static final File dotx = getFileAndCheck(wpTests, "test.dotx"); - private static final File docEmb = getFileAndCheck(wpTests, "word_with_embeded.doc"); - private static final File docEmbOOXML = getFileAndCheck(wpTests, "word_with_embeded_ooxml.doc"); - - private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - private static final File ppt = getFileAndCheck(slTests, "SampleShow.ppt"); - private static final File pptx = getFileAndCheck(slTests, "SampleShow.pptx"); - private static final File ppt97 = getFileAndCheck(slTests, "bug56240.ppt"); - private static final File txt = getFileAndCheck(slTests, "SampleShow.txt"); - - private static final POIDataSamples olTests = POIDataSamples.getHSMFInstance(); - private static final File msg = getFileAndCheck(olTests, "quick.msg"); - private static final File msgEmb = getFileAndCheck(olTests, "attachment_test_msg.msg"); - private static final File msgEmbMsg = getFileAndCheck(olTests, "attachment_msg_pdf.msg"); - - private static final POIDataSamples dgTests = POIDataSamples.getDiagramInstance(); - private static final File vsd = getFileAndCheck(dgTests, "Test_Visio-Some_Random_Text.vsd"); - private static final File vsdx = getFileAndCheck(dgTests, "test.vsdx"); - - private static final POIDataSamples pubTests = POIDataSamples.getPublisherInstance(); - private static final File pub = getFileAndCheck(pubTests, "Simple.pub"); - - private static final POIXMLExtractorFactory xmlFactory = new POIXMLExtractorFactory(); - - private static File getFileAndCheck(POIDataSamples samples, String name) { - File file = samples.getFile(name); - - assertNotNull(file, "Did not get a file for " + name); - assertTrue(file.isFile(), "Did not get a type file for " + name); - assertTrue(file.exists(), "File did not exist: " + name); - - return file; - } - - public static Stream<Arguments> testOOXMLData() { - return Stream.of( - Arguments.of("Excel - xlsx", xlsx, "XSSFExcelExtractor", 200), - Arguments.of("Excel - xltx", xltx, "XSSFExcelExtractor", -1), - Arguments.of("Excel - xlsb", xlsb, "XSSFBEventBasedExcelExtractor", -1), - Arguments.of("Word - docx", docx, "XWPFWordExtractor", 120), - Arguments.of("Word - dotx", dotx, "XWPFWordExtractor", -1), - Arguments.of("PowerPoint - pptx", pptx, "XSLFExtractor", 120), - Arguments.of("Visio - vsdx", vsdx, "XDGFVisioExtractor", 20) - ); - }; - - public static Stream<Arguments> testScratchData() { - return Stream.of( - Arguments.of("Excel", xls, "ExcelExtractor", 200), - Arguments.of("Word", doc, "WordExtractor", 120), - Arguments.of("Word 6", doc6, "Word6Extractor", 20), - Arguments.of("Word 95", doc95, "Word6Extractor", 120), - Arguments.of("PowerPoint", ppt, "SlideShowExtractor", 120), - Arguments.of("PowerPoint 97 Dual", ppt97, "SlideShowExtractor", 120), - Arguments.of("Visio", vsd, "VisioTextExtractor", 50), - Arguments.of("Publisher", pub, "PublisherTextExtractor", 50), - Arguments.of("Outlook msg", msg, "OutlookTextExtractor", 50) - ); - }; - - public static Stream<Arguments> testFileData() { - return Stream.concat(testOOXMLData(), testScratchData()); - // TODO Support OOXML-Strict / xlsxStrict, see bug #57699 - }; - - - @ParameterizedTest - @MethodSource("testFileData") - void testFile(String testcase, File file, String extractor, int count) throws Exception { - try (POITextExtractor ext = createExtractor(file)) { - assertNotNull(ext); - testExtractor(ext, testcase, extractor, count); - } - } - - @ParameterizedTest - @MethodSource("testScratchData") - void testPOIFS(String testcase, File testFile, String extractor, int count) throws Exception { - // test processing of InputStream - try (FileInputStream fis = new FileInputStream(testFile); - POIFSFileSystem poifs = new POIFSFileSystem(fis); - POITextExtractor ext = createExtractor(poifs)) { - assertNotNull(ext); - testExtractor(ext, testcase, extractor, count); - } - } - - @ParameterizedTest - @MethodSource("testFileData") - void testOOXML(String testcase, File testFile, String extractor, int count) throws Exception { - // test processing of InputStream - try (FileInputStream fis = new FileInputStream(testFile); - POITextExtractor ext = createExtractor(fis)) { - assertNotNull(ext); - testExtractor(ext, testcase, extractor, count); - } - } - - @ParameterizedTest - @MethodSource("testOOXMLData") - void testPackage(String testcase, File testFile, String extractor, int count) throws Exception { - try (final OPCPackage pkg = OPCPackage.open(testFile, PackageAccess.READ); - final POITextExtractor ext = xmlFactory.create(pkg)) { - assertNotNull(ext); - testExtractor(ext, testcase, extractor, count); - pkg.revert(); - } - } - - @Test - void testFileInvalid() { - IOException ex = assertThrows(IOException.class, () -> createExtractor(txt)); - assertEquals("Can't create extractor - unsupported file type: UNKNOWN", ex.getMessage()); - } - - @Test - void testInputStreamInvalid() throws IOException { - try (FileInputStream fis = new FileInputStream(txt)) { - IOException ex = assertThrows(IOException.class, () -> createExtractor(fis)); - assertTrue(ex.getMessage().contains(FileMagic.UNKNOWN.name())); - } - } - - @Test - void testPOIFSInvalid() { - // Not really an Extractor test, but we'll leave it to test POIFS reaction anyway ... - IOException ex = assertThrows(IOException.class, () -> new POIFSFileSystem(txt)); - assertTrue(ex.getMessage().contains("Invalid header signature; read 0x3D20726F68747541, expected 0xE11AB1A1E011CFD0")); - } - - private void testExtractor(final POITextExtractor ext, final String testcase, final String extrClass, final Integer minLength) { - assertEquals(extrClass, ext.getClass().getSimpleName(), "invalid extractor for " + testcase); - final String actual = ext.getText(); - if (minLength == -1) { - assertContains(actual.toLowerCase(Locale.ROOT), "test"); - } else { - assertTrue(actual.length() > minLength, "extracted content too short for " + testcase); - } - } - @Test - void testPackageInvalid() { - // Text - assertThrows(NotOfficeXmlFileException.class, () -> OPCPackage.open(txt, PackageAccess.READ)); - } - - @Test - void testPreferEventBased() throws Exception { - assertFalse(ExtractorFactory.getPreferEventExtractor()); - assertFalse(ExtractorFactory.getThreadPrefersEventExtractors()); - assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors()); - - ExtractorFactory.setThreadPrefersEventExtractors(true); - - assertTrue(ExtractorFactory.getPreferEventExtractor()); - assertTrue(ExtractorFactory.getThreadPrefersEventExtractors()); - assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors()); - - ExtractorFactory.setAllThreadsPreferEventExtractors(false); - - assertFalse(ExtractorFactory.getPreferEventExtractor()); - assertTrue(ExtractorFactory.getThreadPrefersEventExtractors()); - assertEquals(Boolean.FALSE, ExtractorFactory.getAllThreadsPreferEventExtractors()); - - ExtractorFactory.setAllThreadsPreferEventExtractors(null); - - assertTrue(ExtractorFactory.getPreferEventExtractor()); - assertTrue(ExtractorFactory.getThreadPrefersEventExtractors()); - assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors()); - - try { - // Check we get the right extractors now - try (POITextExtractor extractor = createExtractor(new POIFSFileSystem(new FileInputStream(xls)))) { - assertTrue(extractor instanceof EventBasedExcelExtractor); - assertTrue(extractor.getText().length() > 200); - } - try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString(), PackageAccess.READ))) { - assertNotNull(extractor); - assertTrue(extractor instanceof XSSFEventBasedExcelExtractor); - assertTrue(extractor.getText().length() > 200); - } - } finally { - // Put back to normal - ExtractorFactory.setThreadPrefersEventExtractors(false); - } - - assertFalse(ExtractorFactory.getPreferEventExtractor()); - assertFalse(ExtractorFactory.getThreadPrefersEventExtractors()); - assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors()); - - // And back - try (POITextExtractor extractor = createExtractor(new POIFSFileSystem(new FileInputStream(xls)))) { - assertTrue(extractor instanceof ExcelExtractor); - assertTrue(extractor.getText().length() > 200); - } - - try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString(), PackageAccess.READ))) { - assertTrue(extractor instanceof XSSFExcelExtractor); - } - - try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString()))) { - assertNotNull(extractor); - assertTrue(extractor.getText().length() > 200); - } - } - - public static Stream<Arguments> testEmbeddedData() { - return Stream.of( - Arguments.of("No embeddings", xls, "0-0-0-0-0-0"), - Arguments.of("Excel", xlsEmb, "6-2-2-2-0-0"), - Arguments.of("Word", docEmb, "4-1-2-1-0-0"), - Arguments.of("Word which contains an OOXML file", docEmbOOXML, "3-0-1-1-0-1"), - Arguments.of("Outlook", msgEmb, "1-1-0-0-0-0"), - Arguments.of("Outlook with another outlook file in it", msgEmbMsg, "1-0-0-0-1-0") - // TODO - PowerPoint - // TODO - Publisher - // TODO - Visio - ); - } - - /** - * Test embedded docs text extraction. For now, only - * does poifs embedded, but will do ooxml ones - * at some point. - */ - @ParameterizedTest - @MethodSource("testEmbeddedData") - void testEmbedded(String format, File file, String expected) throws Exception { - int numWord = 0, numXls = 0, numPpt = 0, numMsg = 0, numWordX = 0; - - try (final POIOLE2TextExtractor ext = (POIOLE2TextExtractor) createExtractor(file)) { - final POITextExtractor[] embeds = ExtractorFactory.getEmbeddedDocsTextExtractors(ext); - - for (POITextExtractor embed : embeds) { - assertTrue(embed.getText().length() > 20); - switch (embed.getClass().getSimpleName()) { - case "SlideShowExtractor": - numPpt++; - break; - case "ExcelExtractor": - numXls++; - break; - case "WordExtractor": - numWord++; - break; - case "OutlookTextExtractor": - numMsg++; - break; - case "XWPFWordExtractor": - numWordX++; - break; - } - } - - final String actual = embeds.length+"-"+numWord+"-"+numXls+"-"+numPpt+"-"+numMsg+"-"+numWordX; - assertEquals(expected, actual, "invalid number of embeddings - "+format); - } - - - } - - @ParameterizedTest - @ValueSource(strings = { - // password protected files - "spreadsheet/password.xls", - "spreadsheet/protected_passtika.xlsx", - "spreadsheet/51832.xls", - "document/PasswordProtected.doc", - "slideshow/Password_Protected-hello.ppt", - "slideshow/Password_Protected-56-hello.ppt", - "slideshow/Password_Protected-np-hello.ppt", - "slideshow/cryptoapi-proc2356.ppt", - //"document/bug53475-password-is-pass.docx", - //"document/bug53475-password-is-solrcell.docx", - "spreadsheet/xor-encryption-abc.xls", - "spreadsheet/35897-type4.xls", - //"poifs/protect.xlsx", - //"poifs/protected_sha512.xlsx", - //"poifs/extenxls_pwd123.xlsx", - //"poifs/protected_agile.docx", - "spreadsheet/58616.xlsx", - - // TODO: fails XMLExportTest, is this ok? - "spreadsheet/CustomXMLMapping-singleattributenamespace.xlsx", - "spreadsheet/55864.xlsx", - "spreadsheet/57890.xlsx", - - // TODO: these fail now with some NPE/file read error because we now try to compute every value via Cell.toString()! - "spreadsheet/44958.xls", - "spreadsheet/44958_1.xls", - "spreadsheet/testArraysAndTables.xls", - - // TODO: good to ignore? - "spreadsheet/sample-beta.xlsx", - - // This is actually a spreadsheet! - "hpsf/TestRobert_Flaherty.doc", - - // some files that are broken, eg Word 95, ... - "spreadsheet/43493.xls", - "spreadsheet/46904.xls", - "document/Bug50955.doc", - "slideshow/PPT95.ppt", - "openxml4j/OPCCompliance_CoreProperties_DCTermsNamespaceLimitedUseFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_DoNotUseCompatibilityMarkupFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_NotPresentFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_UnauthorizedXMLLangAttributeFAIL.docx", - "openxml4j/OPCCompliance_DerivedPartNameFAIL.docx", - "openxml4j/invalid.xlsx", - "spreadsheet/54764-2.xlsx", // see TestXSSFBugs.bug54764() - "spreadsheet/54764.xlsx", // see TestXSSFBugs.bug54764() - "spreadsheet/Simple.xlsb", - "poifs/unknown_properties.msg", // POIFS properties corrupted - "poifs/only-zero-byte-streams.ole2", // No actual contents - "spreadsheet/poc-xmlbomb.xlsx", // contains xml-entity-expansion - "spreadsheet/poc-xmlbomb-empty.xlsx", // contains xml-entity-expansion - "spreadsheet/poc-shared-strings.xlsx", // contains shared-string-entity-expansion - - // old Excel files, which we only support simple text extraction of - "spreadsheet/testEXCEL_2.xls", - "spreadsheet/testEXCEL_3.xls", - "spreadsheet/testEXCEL_4.xls", - "spreadsheet/testEXCEL_5.xls", - "spreadsheet/testEXCEL_95.xls", - - // OOXML Strict is not yet supported, see bug #57699 - "spreadsheet/SampleSS.strict.xlsx", - "spreadsheet/SimpleStrict.xlsx", - "spreadsheet/sample.strict.xlsx", - - // non-TNEF files - "ddf/Container.dat", - "ddf/47143.dat", - - // sheet cloning errors - "spreadsheet/47813.xlsx", - "spreadsheet/56450.xls", - "spreadsheet/57231_MixedGasReport.xls", - "spreadsheet/OddStyleRecord.xls", - "spreadsheet/WithChartSheet.xlsx", - "spreadsheet/chart_sheet.xlsx" - }) - void testFileLeak(String file) { - // run a number of files that might fail in order to catch - // leaked file resources when using file-leak-detector while - // running the test - assertThrows(Exception.class, () -> ex(file)); - } - - /** - * #59074 - Excel 95 files should give a helpful message, not just - * "No supported documents found in the OLE2 stream" - */ - @Test - void bug59074() throws Exception { - try (POITextExtractor extractor = ex("59074.xls")) { - String text = extractor.getText(); - assertContains(text, "Exotic warrant"); - } - } - - @Test - void testGetEmbeddedFromXMLExtractor() { - // currently not implemented - assertThrows(IllegalStateException.class, () -> ExtractorFactory.getEmbeddedDocsTextExtractors(null)); - } - - // This bug is currently open. This test will fail with "expected error not thrown" when the bug has been fixed. - // When this happens, change this from @Test(expected=...) to @Test - // bug 45565: text within TextBoxes is extracted by ExcelExtractor and WordExtractor - @Test - void test45565() throws Exception { - try (POITextExtractor extractor = ex("45565.xls")) { - String text = extractor.getText(); - assertThrows(AssertionError.class, () -> { - assertContains(text, "testdoc"); - assertContains(text, "test phrase"); - }); - } - } - - private static POITextExtractor ex(String filename) throws IOException { - return createExtractor(ssTests.getFile(filename)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestDetectAsOOXML.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestDetectAsOOXML.java deleted file mode 100644 index 13e46c5222..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestDetectAsOOXML.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ooxml; - -import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleFileStream; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -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 java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.filesystem.DocumentFactoryHelper; -import org.apache.poi.poifs.filesystem.FileMagic; -import org.apache.poi.util.IOUtils; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; - -/** - * Class to test that HXF correctly detects OOXML - * documents - */ -@SuppressWarnings("deprecation") -class TestDetectAsOOXML { - @Test - void testOpensProperly() throws IOException, InvalidFormatException { - try (InputStream is = openSampleFileStream("sample.xlsx"); - OPCPackage pkg = OPCPackage.open(is)) { - assertNotNull(pkg); - } - } - - @ParameterizedTest - @CsvSource({"SampleSS.xlsx, OOXML", "SampleSS.xls, OLE2", "SampleSS.txt, UNKNOWN"}) - void testDetectAsPOIFS(String file, FileMagic fm) throws IOException { - try (InputStream is = FileMagic.prepareToCheckMagic(openSampleFileStream(file))) { - FileMagic act = FileMagic.valueOf(is); - - assertEquals(act == FileMagic.OOXML, DocumentFactoryHelper.hasOOXMLHeader(is), - "OOXML files should be detected, others not"); - - assertEquals(fm, act, "file magic failed for " + file); - } - } - - @Test - void testFileCorruption() throws Exception { - // create test InputStream - byte[] testData = { 1, 2, 3 }; - ByteArrayInputStream testInput = new ByteArrayInputStream(testData); - InputStream is = FileMagic.prepareToCheckMagic(testInput); - - // detect header - assertFalse(DocumentFactoryHelper.hasOOXMLHeader(is)); - - // check if InputStream is still intact - byte[] act = IOUtils.toByteArray(is); - assertArrayEquals(testData, act); - assertEquals(-1, is.read()); - is.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestEmbedded.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestEmbedded.java deleted file mode 100644 index e41193a3c8..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestEmbedded.java +++ /dev/null @@ -1,77 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.ooxml; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xslf.usermodel.XSLFSlideShow; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.jupiter.api.Test; - -/** - * Class to test that we handle embeded bits in OOXML files properly - */ -class TestEmbedded { - @Test - void testExcel() throws Exception { - POIXMLDocument doc = new XSSFWorkbook( - POIDataSamples.getSpreadSheetInstance().openResourceAsStream("ExcelWithAttachments.xlsm") - ); - test(doc, 4); - } - - @Test - void testWord() throws Exception { - POIXMLDocument doc = new XWPFDocument( - POIDataSamples.getDocumentInstance().openResourceAsStream("WordWithAttachments.docx") - ); - test(doc, 5); - } - - @Test - void testPowerPoint() throws Exception { - POIXMLDocument doc = new XSLFSlideShow(OPCPackage.open( - POIDataSamples.getSlideShowInstance().openResourceAsStream("PPTWithAttachments.pptm")) - ); - test(doc, 4); - } - - private void test(POIXMLDocument doc, int expectedCount) throws Exception { - assertNotNull(doc.getAllEmbeddedParts()); - assertEquals(expectedCount, doc.getAllEmbeddedParts().size()); - - for(int i=0; i<doc.getAllEmbeddedParts().size(); i++) { - PackagePart pp = doc.getAllEmbeddedParts().get(i); - assertNotNull(pp); - - byte[] b = IOUtils.toByteArray(pp.getInputStream()); - assertTrue(b.length > 0); - } - - doc.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestNecessaryOOXMLClasses.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestNecessaryOOXMLClasses.java deleted file mode 100644 index 86179eeaae..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestNecessaryOOXMLClasses.java +++ /dev/null @@ -1,34 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ooxml; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import com.microsoft.schemas.compatibility.AlternateContentDocument; -import org.apache.xmlbeans.impl.schema.DocumentFactory; -import org.junit.jupiter.api.Test; - -// aim is to get these classes loaded and included in poi-ooxml-lite.jar -class TestNecessaryOOXMLClasses { - - @Test - void testProblemClasses() { - DocumentFactory<AlternateContentDocument> factory = AlternateContentDocument.Factory; - assertNotNull(factory); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java deleted file mode 100644 index 2104a418a8..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java +++ /dev/null @@ -1,346 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ooxml; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -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.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 static org.junit.jupiter.api.Assertions.fail; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.Thread.UncaughtExceptionHandler; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ooxml.POIXMLDocumentPart.RelationPart; -import org.apache.poi.ooxml.util.PackageHelper; -import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NullOutputStream; -import org.apache.poi.util.TempFile; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; - -/** - * Test recursive read and write of OPC packages - */ -public final class TestPOIXMLDocument { - - private static class OPCParser extends POIXMLDocument { - - public OPCParser(OPCPackage pkg) { - super(pkg); - } - - public OPCParser(OPCPackage pkg, String coreDocumentRel) { - super(pkg, coreDocumentRel); - } - - @Override - public List<PackagePart> getAllEmbeddedParts() { - throw new RuntimeException("not supported"); - } - - void parse(POIXMLFactory factory) throws IOException{ - load(factory); - } - } - - private static final class TestFactory extends POIXMLFactory { - - public TestFactory() { - // - } - - @Override - protected POIXMLRelation getDescriptor(String relationshipType) { - return null; - } - } - - private static void traverse(POIXMLDocument doc) { - HashMap<String,POIXMLDocumentPart> context = new HashMap<>(); - for (RelationPart p : doc.getRelationParts()){ - traverse(p, context); - } - } - - /** - * Recursively traverse a OOXML document and assert that same logical parts have the same physical instances - */ - private static void traverse(RelationPart rp, HashMap<String,POIXMLDocumentPart> context) { - POIXMLDocumentPart dp = rp.getDocumentPart(); - assertEquals(rp.getRelationship().getTargetURI().toString(), dp.getPackagePart().getPartName().getName()); - - context.put(dp.getPackagePart().getPartName().getName(), dp); - for(RelationPart p : dp.getRelationParts()){ - assertNotNull(p.getRelationship().toString()); - - String uri = p.getDocumentPart().getPackagePart().getPartName().getURI().toString(); - assertEquals(uri, p.getRelationship().getTargetURI().toString()); - if (!context.containsKey(uri)) { - traverse(p, context); - } else { - POIXMLDocumentPart prev = context.get(uri); - assertSame(prev, p.getDocumentPart(), "Duplicate POIXMLDocumentPart instance for targetURI=" + uri); - } - } - } - - private void assertReadWrite(POIDataSamples samples, String filename) throws Exception { - try (InputStream is = samples.openResourceAsStream(filename); - OPCPackage pkg1 = PackageHelper.open(is)){ - File tmp = TempFile.createTempFile("poi-ooxml", ".tmp"); - try (FileOutputStream out = new FileOutputStream(tmp); - OPCParser doc = new OPCParser(pkg1)) { - doc.parse(new TestFactory()); - traverse(doc); - doc.write(out); - out.close(); - - // Should not be able to write to an output stream that has been closed - // FIXME: A better exception class (IOException?) and message should be raised - // indicating that the document could not be written because the output stream is closed. - // see {@link org.apache.poi.openxml4j.opc.ZipPackage#saveImpl(java.io.OutputStream)} - OpenXML4JRuntimeException e = assertThrows(OpenXML4JRuntimeException.class, () -> doc.write(out), - "Should not be able to write to an output stream that has been closed."); - assertTrue(e.getMessage().matches("Fail to save: an error occurs while saving the package : " + - "The part .+ failed to be saved in the stream with marshaller .+")); - - // Should not be able to write a document that has been closed - doc.close(); - IOException e2 = assertThrows(IOException.class, () -> doc.write(new NullOutputStream()), - "Should not be able to write a document that has been closed."); - assertEquals("Cannot write data, document seems to have been closed already", e2.getMessage()); - - // Should be able to close a document multiple times, though subsequent closes will have no effect. - } - - - try (OPCPackage pkg2 = OPCPackage.open(tmp.getAbsolutePath()); - OPCParser doc = new OPCParser(pkg1)) { - doc.parse(new TestFactory()); - traverse(doc); - - assertEquals(pkg1.getRelationships().size(), pkg2.getRelationships().size()); - - ArrayList<PackagePart> l1 = pkg1.getParts(); - ArrayList<PackagePart> l2 = pkg2.getParts(); - - assertEquals(l1.size(), l2.size()); - for (int i = 0; i < l1.size(); i++) { - PackagePart p1 = l1.get(i); - PackagePart p2 = l2.get(i); - - assertEquals(p1.getContentType(), p2.getContentType()); - assertEquals(p1.hasRelationships(), p2.hasRelationships()); - if (p1.hasRelationships()) { - assertEquals(p1.getRelationships().size(), p2.getRelationships().size()); - } - assertEquals(p1.getPartName(), p2.getPartName()); - } - } - } - } - - @Test - void testPPTX() throws Exception { - assertReadWrite(POIDataSamples.getSlideShowInstance(), "PPTWithAttachments.pptm"); - } - - @Test - void testXLSX() throws Exception { - assertReadWrite(POIDataSamples.getSpreadSheetInstance(), "ExcelWithAttachments.xlsm"); - } - - @Test - void testDOCX() throws Exception { - assertReadWrite(POIDataSamples.getDocumentInstance(), "WordWithAttachments.docx"); - } - - @Test - void testRelationOrder() throws Exception { - POIDataSamples pds = POIDataSamples.getDocumentInstance(); - try (InputStream is = pds.openResourceAsStream("WordWithAttachments.docx"); - OPCPackage pkg = PackageHelper.open(is); - OPCParser doc = new OPCParser(pkg)) { - doc.parse(new TestFactory()); - - for (POIXMLDocumentPart rel : doc.getRelations()) { - //TODO finish me - assertNotNull(rel); - } - } - } - - @Test - void testGetNextPartNumber() throws Exception { - POIDataSamples pds = POIDataSamples.getDocumentInstance(); - try (InputStream is = pds.openResourceAsStream("WordWithAttachments.docx"); - OPCPackage pkg = PackageHelper.open(is); - OPCParser doc = new OPCParser(pkg)) { - doc.parse(new TestFactory()); - - // Non-indexed parts: Word is taken, Excel is not - assertEquals(-1, doc.getNextPartNumber(XWPFRelation.DOCUMENT, 0)); - assertEquals(-1, doc.getNextPartNumber(XWPFRelation.DOCUMENT, -1)); - assertEquals(-1, doc.getNextPartNumber(XWPFRelation.DOCUMENT, 99)); - assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, 0)); - assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, -1)); - assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, 99)); - - // Indexed parts: - // Has 2 headers - assertEquals(0, doc.getNextPartNumber(XWPFRelation.HEADER, 0)); - assertEquals(3, doc.getNextPartNumber(XWPFRelation.HEADER, -1)); - assertEquals(3, doc.getNextPartNumber(XWPFRelation.HEADER, 1)); - assertEquals(8, doc.getNextPartNumber(XWPFRelation.HEADER, 8)); - - // Has no Excel Sheets - assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKSHEET, 0)); - assertEquals(1, doc.getNextPartNumber(XSSFRelation.WORKSHEET, -1)); - assertEquals(1, doc.getNextPartNumber(XSSFRelation.WORKSHEET, 1)); - } - } - - @Test - void testCommitNullPart() throws IOException { - POIXMLDocumentPart part = new POIXMLDocumentPart(); - part.prepareForCommit(); - part.commit(); - part.onSave(new HashSet<>()); - - assertNull(part.getRelationById(null)); - assertNull(part.getRelationId(null)); - assertFalse(part.removeRelation(null, true)); - part.removeRelation((POIXMLDocumentPart)null); - assertEquals("",part.toString()); - part.onDocumentCreate(); - //part.getTargetPart(null); - } - - @Test - void testVSDX() throws Exception { - POIDataSamples pds = POIDataSamples.getDiagramInstance(); - try (InputStream is = pds.openResourceAsStream("test.vsdx"); - OPCPackage open = PackageHelper.open(is); - POIXMLDocument part = new OPCParser(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT)) { - assertNotNull(part); - assertEquals(0, part.getRelationCounter()); - } - } - - @Test - void testVSDXPart() throws IOException { - POIDataSamples pds = POIDataSamples.getDiagramInstance(); - try (InputStream is = pds.openResourceAsStream("test.vsdx"); - OPCPackage open = PackageHelper.open(is)) { - - POIXMLDocumentPart part = new POIXMLDocumentPart(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT); - - assertNotNull(part); - assertEquals(0, part.getRelationCounter()); - } - } - - @Test - void testInvalidCoreRel() throws IOException { - POIDataSamples pds = POIDataSamples.getDiagramInstance(); - try (OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx"))) { - assertThrows(POIXMLException.class, () -> new POIXMLDocumentPart(open, "somethingillegal")); - } - } - - @Test - void dontParseEmbeddedDocuments() throws IOException { - // bug #62513 - POIDataSamples pds = POIDataSamples.getSlideShowInstance(); - try (InputStream is = pds.openResourceAsStream("bug62513.pptx"); - XMLSlideShow ppt = new XMLSlideShow(is)) { - POIXMLDocumentPart doc = ppt.getSlides().get(12).getRelationById("rId3"); - assertNotNull(doc); - assertEquals(POIXMLDocumentPart.class, doc.getClass()); - } - } - - @Test - void testOSGIClassLoading() throws IOException { - byte[] data; - try (InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream("table_test.pptx")) { - data = IOUtils.toByteArray(is); - } - - // the schema type loader is cached per thread in POIXMLTypeLoader. - // So create a new Thread and change the context class loader (which would normally be used) - // to not contain the OOXML classes - Runnable run = () -> assertDoesNotThrow(() -> { - try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(data))) { - assertNotNull(ppt.getSlides().get(0).getShapes()); - }} - ); - - ClassLoader cl = getClass().getClassLoader(); - UncaughtHandler uh = new UncaughtHandler(); - - // check schema type loading and check if we could run in an OOM - Thread[] ta = new Thread[30]; - for (int j=0; j<10; j++) { - for (int i=0; i<ta.length; i++) { - ta[i] = new Thread(run); - ta[i].setContextClassLoader(cl.getParent()); - ta[i].setUncaughtExceptionHandler(uh); - ta[i].start(); - } - for (Thread thread : ta) { - assertDoesNotThrow((Executable) thread::join, "failed to join thread"); - } - } - assertFalse(uh.hasException(), "Should not have an exception now, but had " + uh.e); - } - - private static class UncaughtHandler implements UncaughtExceptionHandler { - Throwable e; - - public synchronized void uncaughtException(Thread t, Throwable e) { - this.e = e; - } - - public synchronized boolean hasException() { - return e != null; - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLProperties.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLProperties.java deleted file mode 100644 index 57306d1637..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLProperties.java +++ /dev/null @@ -1,396 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ooxml; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.time.ZoneId; -import java.util.Calendar; -import java.util.Date; -import java.util.Optional; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ooxml.POIXMLProperties.CoreProperties; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * Test setting extended and custom OOXML properties - */ -public final class TestPOIXMLProperties { - private XWPFDocument sampleDoc; - private XWPFDocument sampleNoThumb; - private POIXMLProperties _props; - private CoreProperties _coreProperties; - - @BeforeEach - void setUp() throws IOException { - sampleDoc = XWPFTestDataSamples.openSampleDocument("documentProperties.docx"); - sampleNoThumb = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - assertNotNull(sampleDoc); - assertNotNull(sampleNoThumb); - _props = sampleDoc.getProperties(); - _coreProperties = _props.getCoreProperties(); - assertNotNull(_props); - } - - @AfterEach - void closeResources() throws Exception { - sampleDoc.close(); - sampleNoThumb.close(); - } - - @Test - void testWorkbookExtendedProperties() throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(); - POIXMLProperties props = workbook.getProperties(); - assertNotNull(props); - - POIXMLProperties.ExtendedProperties properties = - props.getExtendedProperties(); - - org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties - ctProps = properties.getUnderlyingProperties(); - - - String appVersion = "3.5 beta"; - String application = "POI"; - - ctProps.setApplication(application); - ctProps.setAppVersion(appVersion); - - XSSFWorkbook newWorkbook = - XSSFTestDataSamples.writeOutAndReadBack(workbook); - workbook.close(); - assertNotSame(workbook, newWorkbook); - - - POIXMLProperties newProps = newWorkbook.getProperties(); - assertNotNull(newProps); - POIXMLProperties.ExtendedProperties newProperties = - newProps.getExtendedProperties(); - - assertEquals(application, newProperties.getApplication()); - assertEquals(appVersion, newProperties.getAppVersion()); - - org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties - newCtProps = newProperties.getUnderlyingProperties(); - - assertEquals(application, newCtProps.getApplication()); - assertEquals(appVersion, newCtProps.getAppVersion()); - - newWorkbook.close(); - } - - @Test - void testWorkbookExtendedPropertiesGettersSetters() throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(); - POIXMLProperties props = workbook.getProperties(); - assertNotNull(props); - - POIXMLProperties.ExtendedProperties properties = - props.getExtendedProperties(); - - String appVersion = "3.5 beta"; - String application = "POI Modified"; - - assertEquals("Apache POI", properties.getApplication()); - properties.setApplication(application); - assertEquals(properties.getApplication(), application); - - assertNull(properties.getAppVersion()); - properties.setAppVersion(appVersion); - assertEquals(properties.getAppVersion(), appVersion); - - XSSFWorkbook newWorkbook = - XSSFTestDataSamples.writeOutAndReadBack(workbook); - workbook.close(); - assertNotSame(workbook, newWorkbook); - - POIXMLProperties newProps = newWorkbook.getProperties(); - assertNotNull(newProps); - POIXMLProperties.ExtendedProperties newProperties = - newProps.getExtendedProperties(); - - assertEquals(application, newProperties.getApplication()); - assertEquals(appVersion, newProperties.getAppVersion()); - - newWorkbook.close(); - } - - - /** - * Test usermodel API for setting custom properties - */ - @Test - void testCustomProperties() throws Exception { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - - POIXMLProperties.CustomProperties customProps = wb1.getProperties().getCustomProperties(); - customProps.addProperty("test-1", "string val"); - customProps.addProperty("test-2", 1974); - customProps.addProperty("test-3", 36.6); - //adding a duplicate - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> customProps.addProperty("test-3", 36.6)); - assertEquals("A property with this name already exists in the custom properties", e.getMessage()); - customProps.addProperty("test-4", true); - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { - org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties ctProps = - wb2.getProperties().getCustomProperties().getUnderlyingProperties(); - assertEquals(4, ctProps.sizeOfPropertyArray()); - org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty p; - - p = ctProps.getPropertyArray(0); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-1", p.getName()); - assertEquals("string val", p.getLpwstr()); - assertEquals(2, p.getPid()); - - p = ctProps.getPropertyArray(1); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-2", p.getName()); - assertEquals(1974, p.getI4()); - assertEquals(3, p.getPid()); - - p = ctProps.getPropertyArray(2); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-3", p.getName()); - assertEquals(36.6, p.getR8(), 0); - assertEquals(4, p.getPid()); - - p = ctProps.getPropertyArray(3); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-4", p.getName()); - assertTrue(p.getBool()); - assertEquals(5, p.getPid()); - } - } - } - - @Test - void testDocumentProperties() { - String category = _coreProperties.getCategory(); - assertEquals("test", category); - String contentStatus = "Draft"; - _coreProperties.setContentStatus(contentStatus); - assertEquals("Draft", contentStatus); - Date created = _coreProperties.getCreated(); - // the original file contains a following value: 2009-07-20T13:12:00Z - assertTrue(dateTimeEqualToUTCString(created, "2009-07-20T13:12:00Z")); - String creator = _coreProperties.getCreator(); - assertEquals("Paolo Mottadelli", creator); - String subject = _coreProperties.getSubject(); - assertEquals("Greetings", subject); - String title = _coreProperties.getTitle(); - assertEquals("Hello World", title); - } - - @Test - void testTransitiveSetters() throws IOException { - XWPFDocument doc = new XWPFDocument(); - CoreProperties cp = doc.getProperties().getCoreProperties(); - - - Date dateCreated = LocaleUtil.getLocaleCalendar(2010, 6, 15, 10, 0, 0).getTime(); - cp.setCreated(Optional.of(dateCreated)); - assertEquals(dateCreated, cp.getCreated()); - - XWPFDocument doc2 = XWPFTestDataSamples.writeOutAndReadBack(doc); - doc.close(); - cp = doc2.getProperties().getCoreProperties(); - Date dt3 = cp.getCreated(); - assertEquals(dateCreated, dt3); - doc2.close(); - } - - @Test - void testGetSetRevision() { - String revision = _coreProperties.getRevision(); - assertTrue(Integer.parseInt(revision) > 1, "Revision number is 1"); - _coreProperties.setRevision("20"); - assertEquals("20", _coreProperties.getRevision()); - _coreProperties.setRevision("20xx"); - assertEquals("20", _coreProperties.getRevision()); - } - - @Test - void testLastModifiedByUserProperty() { - String lastModifiedByUser = _coreProperties.getLastModifiedByUser(); - assertEquals("Paolo Mottadelli", lastModifiedByUser); - _coreProperties.setLastModifiedByUser("Test User"); - assertEquals("Test User", _coreProperties.getLastModifiedByUser()); - } - - public static boolean dateTimeEqualToUTCString(Date dateTime, String utcString) { - Calendar utcCalendar = LocaleUtil.getLocaleCalendar(LocaleUtil.TIMEZONE_UTC); - utcCalendar.setTimeInMillis(dateTime.getTime()); - String dateTimeUtcString = utcCalendar.get(Calendar.YEAR) + "-" + - zeroPad((utcCalendar.get(Calendar.MONTH)+1)) + "-" + - zeroPad(utcCalendar.get(Calendar.DAY_OF_MONTH)) + "T" + - zeroPad(utcCalendar.get(Calendar.HOUR_OF_DAY)) + ":" + - zeroPad(utcCalendar.get(Calendar.MINUTE)) + ":" + - zeroPad(utcCalendar.get(Calendar.SECOND)) + "Z"; - - return utcString.equals(dateTimeUtcString); - } - - @Disabled("Fails to add some of the thumbnails, needs more investigation") - @Test - void testThumbnails() throws Exception { - POIXMLProperties noThumbProps = sampleNoThumb.getProperties(); - - assertNotNull(_props.getThumbnailPart()); - assertNull(noThumbProps.getThumbnailPart()); - - assertNotNull(_props.getThumbnailFilename()); - assertNull(noThumbProps.getThumbnailFilename()); - - assertNotNull(_props.getThumbnailImage()); - assertNull(noThumbProps.getThumbnailImage()); - - assertEquals("/thumbnail.jpeg", _props.getThumbnailFilename()); - - - // Adding / changing - ByteArrayInputStream imageData = new ByteArrayInputStream(new byte[1]); - noThumbProps.setThumbnail("Testing.png", imageData); - assertNotNull(noThumbProps.getThumbnailPart()); - assertEquals("/Testing.png", noThumbProps.getThumbnailFilename()); - assertNotNull(noThumbProps.getThumbnailImage()); - assertEquals(1, IOUtils.toByteArray(noThumbProps.getThumbnailImage()).length); - - imageData = new ByteArrayInputStream(new byte[2]); - noThumbProps.setThumbnail("Testing2.png", imageData); - assertNotNull(noThumbProps.getThumbnailPart()); - assertEquals("/Testing.png", noThumbProps.getThumbnailFilename()); - assertNotNull(noThumbProps.getThumbnailImage()); - assertEquals(2, IOUtils.toByteArray(noThumbProps.getThumbnailImage()).length); - } - - private static String zeroPad(long i) { - if (i >= 0 && i <= 9) { - return "0" + i; - } else { - return String.valueOf(i); - } - } - - @Test - void testAddProperty() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("documentProperties.docx")) { - POIXMLProperties.CustomProperties cps = doc.getProperties().getCustomProperties(); - assertEquals(1, cps.getLastPid()); - cps.addProperty("prop1", "abc"); - assertEquals(2, cps.getLastPid()); - assertEquals(2, cps.getProperty("prop1").getPid()); - assertEquals("abc", cps.getProperty("prop1").getLpwstr()); - } - } - - @Test - void testOoxmlStrict() throws Exception { - POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("sample.strict.xlsx"))) { - POIXMLProperties props = new POIXMLProperties(pkg); - assertNotNull(props.getCoreProperties().getCreated()); - assertEquals(2007, props.getCoreProperties().getCreated().toInstant().atZone(ZoneId.of("UTC")).getYear()); - } - } - - @Test - void testBug60977() throws IOException { - - try (final XSSFWorkbook workbook = new XSSFWorkbook()) { - final Sheet sheet = workbook.createSheet("sheet"); - final Row row = sheet.createRow(0); - final Cell cell = row.createCell(0); - cell.setCellValue("cell"); - - final POIXMLProperties properties = workbook.getProperties(); - final POIXMLProperties.CustomProperties customProperties = properties.getCustomProperties(); - final String propName = "Project"; - final String propValue = "Some name"; - customProperties.addProperty(propName, propValue); - - // in the unit-test just try to write out the file more than once and see if we can still parse it - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertNotNull(wbBack); - // properties documents are read lazily, so we have to access them to verify they parse properly - assertNotNull(wbBack.getProperties(), "First writeOutAndReadBack"); - assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr(), "First prop check"); - - customProperties.addProperty(propName + "1", propValue); - wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertNotNull(wbBack); - // properties documents are read lazily, so we have to access them to verify they parse properly - assertNotNull(wbBack.getProperties(), "Second writeOutAndReadBack"); - assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr(), "Second prop check"); - assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName + "1").getLpwstr(), "Second prop check1"); - - wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertNotNull(wbBack); - // properties documents are read lazily, so we have to access them to verify they parse properly - assertNotNull(wbBack.getProperties(), "Third writeOutAndReadBack"); - assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName).getLpwstr(), "Third prop check"); - assertEquals(propValue, wbBack.getProperties().getCustomProperties().getProperty(propName + "1").getLpwstr(), "Third prop check1"); - - /* Manual test to write out the file more than once: - File test1 = File.createTempFile("test1", ".xlsx", new File("C:\\temp")); - File test2 = File.createTempFile("test2", ".xlsx", new File("C:\\temp")); - try (final java.io.FileOutputStream fs = new java.io.FileOutputStream(test1)) { - workbook.write(fs); - } - try (final XSSFWorkbook wb = new XSSFWorkbook(test1)) { - assertNotNull(wb.getProperties()); - } catch (InvalidFormatException e) { - fail("Test1 copy failed: " + e.getMessage()); - } - - try (final java.io.FileOutputStream fs = new java.io.FileOutputStream(test2)) { - workbook.write(fs); - } - - try (final XSSFWorkbook wb = new XSSFWorkbook(test2)) { - assertNotNull(wb.getProperties()); - } catch (InvalidFormatException e) { - fail("Test2 copy failed: " + e.getMessage()); - } - */ - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestTriggerCoverage.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestTriggerCoverage.java deleted file mode 100644 index 7745125ea4..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestTriggerCoverage.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ooxml; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.extractor.POITextExtractor; -import org.apache.poi.sl.draw.Drawable; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.ss.extractor.EmbeddedData; -import org.apache.poi.ss.extractor.EmbeddedExtractor; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import org.junit.platform.commons.util.ExceptionUtils; - -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -/** - * Test to trigger code-execution of various parts so - * that all required elements are inclueded in the ooxml-schema-lite package - */ -class TestTriggerCoverage { - private static final Set<String> FAILING = new HashSet<>(); - static { - FAILING.add("stress025.docx"); - } - - public static Stream<Arguments> files() { - String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY); - if(dataDirName == null) { - dataDirName = "test-data"; - } - - List<Arguments> files = new ArrayList<>(); - findFile(files, dataDirName + "/integration"); - - return files.stream(); - } - - private static void findFile(List<Arguments> list, String dir) { - String[] files = new File(dir).list(); - assertNotNull(files, "Did not find any files in directory " + dir); - - for(String file : files) { - list.add(Arguments.of(new File(dir, file))); - } - } - - @ParameterizedTest - @MethodSource("files") - void testFile(File file) throws Exception { - try (InputStream stream = new FileInputStream(file)) { - if (file.getName().endsWith(".docx")) { - try (XWPFDocument doc = new XWPFDocument(stream)) { - assertNotNull(doc); - } - } else if (file.getName().endsWith(".xlsx")) { - try (XSSFWorkbook xls = new XSSFWorkbook(stream)) { - assertNotNull(xls); - extractEmbedded(xls); - } - } else if (file.getName().endsWith(".pptx")) { - try (XMLSlideShow ppt = new XMLSlideShow(stream)) { - assertNotNull(ppt); - renderSlides(ppt); - } - } else { - throw new IllegalArgumentException("Don't know how to handle file " + file); - } - } catch (Exception e) { - Assumptions.assumeFalse(FAILING.contains(file.getName()), - "File " + file + " is expected to fail"); - - throw e; - } - - try (InputStream stream = new FileInputStream(file)) { - try (POITextExtractor extractor = ExtractorFactory.createExtractor(stream)) { - assertNotNull(extractor.getText()); - } - } - } - - private void extractEmbedded(Workbook wb) throws IOException { - EmbeddedExtractor ee = new EmbeddedExtractor(); - - for (Sheet s : wb) { - for (EmbeddedData ed : ee.extractAll(s)) { - assertNotNull(ed.getFilename()); - assertNotNull(ed.getEmbeddedData()); - assertNotNull(ed.getShape()); - } - } - } - - private void renderSlides(SlideShow<?,?> ss) { - Dimension pgSize = ss.getPageSize(); - - for (Slide<?,?> s : ss.getSlides()) { - BufferedImage img = new BufferedImage(pgSize.width, pgSize.height, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = img.createGraphics(); - - // default rendering options - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - graphics.setRenderingHint(Drawable.BUFFERED_IMAGE, new WeakReference<>(img)); - - try { - // draw stuff - s.draw(graphics); - } catch (ArrayIndexOutOfBoundsException e) { - // We saw exceptions with JDK 8 on Windows in the Jenkins CI which - // seem to only be triggered by some font (maybe Calibri?!) - // We cannot avoid this, so let's try to not make the tests fail in this case - Assumptions.assumeFalse( - e.getMessage().equals("-1") && - ExceptionUtils.readStackTrace(e).contains("ExtendedTextSourceLabel.getJustificationInfos"), - "JDK sometimes fails at this point on some fonts on Windows machines, but we " + - "should not fail the build because of this: " + ExceptionUtils.readStackTrace(e)); - - throw e; - } - - graphics.dispose(); - img.flush(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestXMLPropertiesTextExtractor.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestXMLPropertiesTextExtractor.java deleted file mode 100644 index c077e15085..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ooxml/TestXMLPropertiesTextExtractor.java +++ /dev/null @@ -1,144 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ooxml; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ooxml.extractor.POIXMLPropertiesTextExtractor; -import org.apache.poi.ooxml.util.PackageHelper; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xslf.usermodel.XSLFSlideShow; -import org.apache.poi.xssf.extractor.XSSFExcelExtractor; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -public final class TestXMLPropertiesTextExtractor { - private static final POIDataSamples _ssSamples = POIDataSamples.getSpreadSheetInstance(); - private static final POIDataSamples _slSamples = POIDataSamples.getSlideShowInstance(); - - @Test - void testGetFromMainExtractor() throws Exception { - OPCPackage pkg = PackageHelper.open(_ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm")); - - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - XSSFExcelExtractor ext = new XSSFExcelExtractor(wb); - POIXMLPropertiesTextExtractor textExt = ext.getMetadataTextExtractor(); - - // Check basics - assertNotNull(textExt); - assertTrue(textExt.getText().length() > 0); - - // Check some of the content - String text = textExt.getText(); - String cText = textExt.getCorePropertiesText(); - - assertContains(text, "LastModifiedBy = Yury Batrakov"); - assertContains(cText, "LastModifiedBy = Yury Batrakov"); - - textExt.close(); - ext.close(); - } - - @Test - void testCore() throws Exception { - OPCPackage pkg = PackageHelper.open( - _ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm") - ); - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(wb); - ext.getText(); - - // Now check - String text = ext.getText(); - String cText = ext.getCorePropertiesText(); - - assertContains(text, "LastModifiedBy = Yury Batrakov"); - assertContains(cText, "LastModifiedBy = Yury Batrakov"); - - ext.close(); - } - - @Test - void testExtended() throws Exception { - OPCPackage pkg = OPCPackage.open( - _ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm") - ); - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(wb); - ext.getText(); - - // Now check - String text = ext.getText(); - String eText = ext.getExtendedPropertiesText(); - - assertContains(text, "Application = Microsoft Excel"); - assertContains(text, "Company = Mera"); - assertContains(eText, "Application = Microsoft Excel"); - assertContains(eText, "Company = Mera"); - - ext.close(); - } - - @Test - void testCustom() throws Exception { - OPCPackage pkg = OPCPackage.open( - _ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm") - ); - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(wb); - ext.getText(); - - // Now check - String text = ext.getText(); - String cText = ext.getCustomPropertiesText(); - - assertContains(text, "description = another value"); - assertContains(cText, "description = another value"); - - ext.close(); - } - - /** - * Bug #49386 - some properties, especially - * dates can be null - */ - @Test - void testWithSomeNulls() throws Exception { - OPCPackage pkg = OPCPackage.open( - _slSamples.openResourceAsStream("49386-null_dates.pptx") - ); - XSLFSlideShow sl = new XSLFSlideShow(pkg); - - POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(sl); - ext.getText(); - - String text = ext.getText(); - assertFalse(text.contains("Created =")); // With date is null - assertContains(text, "CreatedString = "); // Via string is blank - assertContains(text, "LastModifiedBy = IT Client Services"); - - ext.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/lite/OOXMLLiteAgent.java b/src/ooxml/testcases/org/apache/poi/ooxml/lite/OOXMLLiteAgent.java deleted file mode 100644 index 64cec25ac6..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ooxml/lite/OOXMLLiteAgent.java +++ /dev/null @@ -1,140 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ooxml.lite; - -import static net.bytebuddy.matcher.ElementMatchers.named; - -import java.io.IOException; -import java.lang.instrument.ClassFileTransformer; -import java.lang.instrument.Instrumentation; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.security.ProtectionDomain; -import java.util.HashSet; -import java.util.Set; -import java.util.regex.Pattern; -import java.util.stream.Stream; - -import net.bytebuddy.agent.builder.AgentBuilder; -import net.bytebuddy.implementation.MethodDelegation; -import net.bytebuddy.implementation.SuperMethodCall; -import net.bytebuddy.matcher.ElementMatchers; -import org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl; - -/** - * OOXMLLiteAgent is the replacement for the former OOXMLLite, because in Java 12 - * it isn't possible to access the privates :) of the ClassLoader - */ -public class OOXMLLiteAgent { - - public static void premain(String agentArgs, Instrumentation inst) throws IOException { - String[] args = (agentArgs == null ? "" : agentArgs).split("\\|", 2); - String logBase = args.length >= 1 ? args[0] : "ooxml-lite-report"; - - XsbLogger.load(logBase+".xsb"); - - ClazzLogger log = new ClazzLogger(); - log.load(logBase+".clazz"); - log.setPattern(args.length >= 2 ? args[1] : ".*/schemas/.*"); - inst.addTransformer(log); - - new AgentBuilder.Default() - // .with(AgentBuilder.Listener.StreamWriting.toSystemOut()) - .type(named("org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl$XsbReader")) - .transform((builder, type, cl, m) -> - builder - .constructor(ElementMatchers.any()) - .intercept(MethodDelegation.to(XsbLogger.class).andThen(SuperMethodCall.INSTANCE)) - ) - .installOn(inst); - } - - /** - * This logger intercepts the loading of XmlBeans .xsb - * - * when ran in the ant junitlauncher, it's not possible to have the interceptor methods as - * instance method of ClazzLogger. the junit test will fail ... though it works ok in IntelliJ - * probably because of classpath vs. modulepath instantiation - */ - public static class XsbLogger { - private static Path logPath; - private static final Set<Integer> hashes = new HashSet<>(); - - static void load(String path) throws IOException { - logPath = Paths.get(path); - if (Files.exists(logPath)) { - try (Stream<String> stream = Files.lines(logPath)) { - stream.forEach((s) -> hashes.add(s.hashCode())); - } - } - } - - // SchemaTypeSystemImpl.XsbReader::new is delegated to here - method name doesn't matter - public static void loadXsb(SchemaTypeSystemImpl parent, String handle) { - write(logPath, handle, hashes); - } - - public static void loadXsb(SchemaTypeSystemImpl parent, String handle, int filetype) { - loadXsb(parent, handle); - } - } - - /** - * This logger is used to log the used XmlBeans classes - */ - public static class ClazzLogger implements ClassFileTransformer { - Path logPath; - Pattern includes; - final Set<Integer> hashes = new HashSet<>(); - - void setPattern(String regex) { - includes = Pattern.compile(regex); - } - - void load(String path) throws IOException { - this.logPath = Paths.get(path); - if (Files.exists(this.logPath)) { - try (Stream<String> stream = Files.lines(this.logPath)) { - stream.forEach((s) -> hashes.add(s.hashCode())); - } - } - } - - public byte[] transform(ClassLoader loader, String className, Class redefiningClass, ProtectionDomain domain, byte[] bytes) { - if (logPath != null && className != null && includes.matcher(className).find()) { - write(logPath, className, hashes); - } - return bytes; - } - } - - - static void write(Path path, String item, Set<Integer> hashes) { - if (!hashes.contains(item.hashCode())) { - try { - // TODO: check if this is atomic ... as transform() is probably called synchronized, it doesn't matter anyway - Files.write(path, (item+"\n").getBytes(StandardCharsets.ISO_8859_1), StandardOpenOption.CREATE, StandardOpenOption.APPEND); - hashes.add(item.hashCode()); - } catch (IOException ignored) { - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java b/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java deleted file mode 100644 index 1c6b942a58..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.TempFile; - -import java.io.File; -import java.io.InputStream; -import java.io.IOException; - -/** - * Centralises logic for finding/opening sample files for ooxml4j unit tests - */ -public final class OpenXML4JTestDataSamples { - private static final POIDataSamples _samples = POIDataSamples.getOpenXML4JInstance(); - - private OpenXML4JTestDataSamples() { - // no instances of this class - } - - public static InputStream openSampleStream(String sampleFileName) { - return _samples.openResourceAsStream(sampleFileName); - } - public static String getSampleFileName(String sampleFileName) { - return getSampleFile(sampleFileName).getAbsolutePath(); - } - - public static File getSampleFile(String sampleFileName) { - return _samples.getFile(sampleFileName); - } - - public static File getOutputFile(String outputFileName) throws IOException { - String suffix = outputFileName.substring(outputFileName.lastIndexOf('.')); - return TempFile.createTempFile(outputFileName, suffix); - } - - - public static InputStream openComplianceSampleStream(String sampleFileName) { - return _samples.openResourceAsStream(sampleFileName); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java deleted file mode 100644 index 7847507017..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java +++ /dev/null @@ -1,227 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.InputStream; - -import javax.xml.parsers.DocumentBuilderFactory; - -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.internal.ContentType; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -/** - * Tests for content type (ContentType class). - */ -public final class TestContentType { - - private static final String FEATURE_DISALLOW_DOCTYPE_DECL = "http://apache.org/xml/features/disallow-doctype-decl"; - - /** - * Check rule M1.13: Package implementers shall only create and only - * recognize parts with a content type; format designers shall specify a - * content type for each part included in the format. Content types for - * package parts shall fit the definition and syntax for media types as - * specified in RFC 2616, \u00A73.7. - */ - @ParameterizedTest - @ValueSource(strings = {"text/xml", "application/pgp-key", "application/vnd.hp-PCLXL", "application/vnd.lotus-1-2-3"}) - void testContentTypeValidation(String contentType) throws InvalidFormatException { - assertDoesNotThrow(() -> new ContentType(contentType)); - } - - /** - * Check rule M1.13 : Package implementers shall only create and only - * recognize parts with a content type; format designers shall specify a - * content type for each part included in the format. Content types for - * package parts shall fit the definition and syntax for media types as - * specified in RFC 2616, \u00A3.7. - * <p> - * Check rule M1.14: Content types shall not use linear white space either - * between the type and subtype or between an attribute and its value. - * Content types also shall not have leading or trailing white spaces. - * Package implementers shall create only such content types and shall - * require such content types when retrieving a part from a package; format - * designers shall specify only such content types for inclusion in the - * format. - */ - @ParameterizedTest - @ValueSource(strings = {"text/xml/app", "", - "test", "text(xml/xml", "text)xml/xml", "text<xml/xml", - "text>/xml", "text@/xml", "text,/xml", "text;/xml", - "text:/xml", "text\\/xml", "t/ext/xml", "t\"ext/xml", - "text[/xml", "text]/xml", "text?/xml", "tex=t/xml", - "te{xt/xml", "tex}t/xml", "te xt/xml", - "text\u0009/xml", "text xml", " text/xml "}) - void testContentTypeValidationFailure(String contentType) { - assertThrows(InvalidFormatException.class, () -> new ContentType(contentType), - "Must have fail for content type: '" + contentType + "' !"); - } - - /** - * Parameters are allowed, provides that they meet the - * criteria of rule [01.2] - * Invalid parameters are verified as incorrect in - * {@link #testContentTypeParameterFailure()} - */ - @ParameterizedTest - @ValueSource(strings = {"mail/toto;titi=tata", - "text/xml;a=b;c=d", "text/xml;key1=param1;key2=param2", - "application/pgp-key;version=\"2\"", - "application/x-resqml+xml;version=2.0;type=obj_global2dCrs"}) - void testContentTypeParam(String contentType) { - assertDoesNotThrow(() -> new ContentType(contentType)); - } - - /** - * Check rule [O1.2]: Format designers might restrict the usage of - * parameters for content types. - */ - @ParameterizedTest - @ValueSource(strings = { - "mail/toto;\"titi=tata\"", // quotes not allowed like that - "mail/toto;titi = tata", // spaces not allowed - "text/\u0080" // characters above ASCII are not allowed - }) - void testContentTypeParameterFailure(String contentType) { - assertThrows(InvalidFormatException.class, () -> new ContentType(contentType), - "Must have fail for content type: '" + contentType + "' !"); - } - - /** - * Check rule M1.15: The package implementer shall require a content type - * that does not include comments and the format designer shall specify such - * a content type. - */ - @ParameterizedTest - @ValueSource(strings = {"text/xml(comment)"}) - void testContentTypeCommentFailure(String contentType) { - assertThrows(InvalidFormatException.class, () -> new ContentType(contentType), - "Must have fail for content type: '" + contentType + "' !"); - } - - /** - * OOXML content types don't need entities and we shouldn't - * barf if we get one from a third party system that added them - * (expected = InvalidFormatException.class) - */ - @Test - void testFileWithContentTypeEntities() throws Exception { - try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("ContentTypeHasEntities.ooxml")) { - if (isOldXercesActive()) { - OPCPackage.open(is); - } else { - assertThrows(InvalidFormatException.class, () -> OPCPackage.open(is)); - } - } - } - - /** - * Check that we can open a file where there are valid - * parameters on a content type - */ - @Test - void testFileWithContentTypeParams() throws Exception { - try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("ContentTypeHasParameters.ooxml"); - OPCPackage p = OPCPackage.open(is)) { - - final String typeResqml = "application/x-resqml+xml"; - - // Check the types on everything - for (PackagePart part : p.getParts()) { - final String contentType = part.getContentType(); - final ContentType details = part.getContentTypeDetails(); - final int length = details.getParameterKeys().length; - final boolean hasParameters = details.hasParameters(); - - // _rels type doesn't have any params - if (part.isRelationshipPart()) { - assertEquals(ContentTypes.RELATIONSHIPS_PART, contentType); - assertEquals(ContentTypes.RELATIONSHIPS_PART, details.toString()); - assertFalse(hasParameters); - assertEquals(0, length); - } - // Core type doesn't have any params - else if (part.getPartName().toString().equals("/docProps/core.xml")) { - assertEquals(ContentTypes.CORE_PROPERTIES_PART, contentType); - assertEquals(ContentTypes.CORE_PROPERTIES_PART, details.toString()); - assertFalse(hasParameters); - assertEquals(0, length); - } - // Global Crs types do have params - else if (part.getPartName().toString().equals("/global1dCrs.xml")) { - assertTrue(part.getContentType().startsWith(typeResqml)); - assertEquals(typeResqml, details.toString(false)); - assertTrue(hasParameters); - assertContains("version=2.0", details.toString()); - assertContains("type=obj_global1dCrs", details.toString()); - assertEquals(2, length); - assertEquals("2.0", details.getParameter("version")); - assertEquals("obj_global1dCrs", details.getParameter("type")); - } else if (part.getPartName().toString().equals("/global2dCrs.xml")) { - assertTrue(part.getContentType().startsWith(typeResqml)); - assertEquals(typeResqml, details.toString(false)); - assertTrue(hasParameters); - assertContains("version=2.0", details.toString()); - assertContains("type=obj_global2dCrs", details.toString()); - assertEquals(2, length); - assertEquals("2.0", details.getParameter("version")); - assertEquals("obj_global2dCrs", details.getParameter("type")); - } - // Other thingy - else if (part.getPartName().toString().equals("/myTestingGuid.xml")) { - assertTrue(part.getContentType().startsWith(typeResqml)); - assertEquals(typeResqml, details.toString(false)); - assertTrue(hasParameters); - assertContains("version=2.0", details.toString()); - assertContains("type=obj_tectonicBoundaryFeature", details.toString()); - assertEquals(2, length); - assertEquals("2.0", details.getParameter("version")); - assertEquals("obj_tectonicBoundaryFeature", details.getParameter("type")); - } - // That should be it! - else { - fail("Unexpected part " + part); - } - } - } - } - - private static void assertContains(String needle, String haystack) { - assertTrue(haystack.contains(needle)); - } - - public static boolean isOldXercesActive() { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - try { - dbf.setFeature(FEATURE_DISALLOW_DOCTYPE_DECL, true); - return false; - } catch (Exception|AbstractMethodError ignored) {} - return true; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java deleted file mode 100644 index 7a5d012fed..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.File; -import java.util.TreeMap; - -import org.apache.poi.openxml4j.opc.internal.FileHelper; -import org.junit.jupiter.api.Test; - -/** - * Test TestFileHelper class. - * - * @author Julien Chable - */ -public final class TestFileHelper { - - /** - * TODO - use simple JDK methods on {@link File} instead:<br> - * {@link File#getParentFile()} instead of {@link FileHelper#getDirectory(File) - * {@link File#getName()} instead of {@link FileHelper#getFilename(File) - */ - @Test - void testGetDirectory() { - TreeMap<String, String> expectedValue = new TreeMap<>(); - expectedValue.put("/dir1/test.doc", "/dir1"); - expectedValue.put("/dir1/dir2/test.doc.xml", "/dir1/dir2"); - - for (String filename : expectedValue.keySet()) { - File f1 = new File(expectedValue.get(filename)); - File f2 = FileHelper.getDirectory(new File(filename)); - -// if (false) { -// // YK: The original version asserted expected values against File#getAbsolutePath(): -// assertTrue(expectedValue.get(filename).equalsIgnoreCase(f2.getAbsolutePath())); -// // This comparison is platform dependent. A better approach is below -// } - assertEquals(f1, f2); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java deleted file mode 100644 index 481ce98620..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java +++ /dev/null @@ -1,104 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; -import java.io.InputStream; -import java.util.TreeMap; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public final class TestListParts { - private static final Logger LOG = LogManager.getLogger(TestListParts.class); - - private TreeMap<PackagePartName, String> expectedValues; - - private TreeMap<PackagePartName, String> values; - - @BeforeEach - void setUp() throws Exception { - values = new TreeMap<>(); - - // Expected values - expectedValues = new TreeMap<>(); - expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"), - "application/vnd.openxmlformats-package.relationships+xml"); - - expectedValues - .put(PackagingURIHelper.createPartName("/docProps/app.xml"), - "application/vnd.openxmlformats-officedocument.extended-properties+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/docProps/core.xml"), - "application/vnd.openxmlformats-package.core-properties+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/word/_rels/document.xml.rels"), - "application/vnd.openxmlformats-package.relationships+xml"); - expectedValues - .put( - PackagingURIHelper.createPartName("/word/document.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/fontTable.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/word/media/image1.gif"), "image/gif"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/settings.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/styles.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/word/theme/theme1.xml"), - "application/vnd.openxmlformats-officedocument.theme+xml"); - expectedValues - .put( - PackagingURIHelper - .createPartName("/word/webSettings.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"); - } - - /** - * List all parts of a package. - */ - @Test - void testListParts() throws InvalidFormatException, IOException { - try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.docx"); - OPCPackage p = OPCPackage.open(is)) { - - for (PackagePart part : p.getParts()) { - values.put(part.getPartName(), part.getContentType()); - LOG.atDebug().log(part.getPartName()); - } - - // Compare expected values with values return by the package - for (PackagePartName partName : expectedValues.keySet()) { - assertNotNull(values.get(partName)); - assertEquals(expectedValues.get(partName), values.get(partName)); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java deleted file mode 100644 index 9f297f66c6..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java +++ /dev/null @@ -1,1102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getOutputFile; -import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFile; -import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFileName; -import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream; -import static org.apache.poi.openxml4j.opc.PackagingURIHelper.createPartName; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PushbackInputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.TreeMap; -import java.util.function.BiConsumer; -import java.util.regex.Pattern; -import java.util.stream.Stream; - -import com.google.common.hash.Hashing; -import com.google.common.io.Files; -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; -import org.apache.commons.compress.archivers.zip.ZipFile; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; -import org.apache.poi.POITestCase; -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.extractor.POITextExtractor; -import org.apache.poi.ooxml.POIXMLException; -import org.apache.poi.ooxml.util.DocumentHelper; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException; -import org.apache.poi.openxml4j.opc.internal.ContentTypeManager; -import org.apache.poi.openxml4j.opc.internal.FileHelper; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.openxml4j.opc.internal.ZipHelper; -import org.apache.poi.openxml4j.util.ZipSecureFile; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -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; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -public final class TestPackage { - private static final Logger LOG = LogManager.getLogger(TestPackage.class); - private static final String NS_OOXML_WP_MAIN = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"; - private static final String CONTENT_EXT_PROPS = "application/vnd.openxmlformats-officedocument.extended-properties+xml"; - private static final POIDataSamples xlsSamples = POIDataSamples.getSpreadSheetInstance(); - - @Test - void isStrictOoxmlFormat() throws IOException, InvalidFormatException { - try (OPCPackage p = OPCPackage.open(getSampleFileName("TestPackageCommon.docx"), PackageAccess.READ)) { - assertFalse(p.isStrictOoxmlFormat()); - } - try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("sample.xlsx"), PackageAccess.READ)) { - assertFalse(p.isStrictOoxmlFormat()); - } - try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("sample.strict.xlsx"), PackageAccess.READ)) { - assertTrue(p.isStrictOoxmlFormat()); - } - } - - - /** - * Test that just opening and closing the file doesn't alter the document. - */ - @Test - void openSave() throws IOException, InvalidFormatException { - String originalFile = getSampleFileName("TestPackageCommon.docx"); - File targetFile = getOutputFile("TestPackageOpenSaveTMP.docx"); - - try (OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE)) { - try { - p.save(targetFile.getAbsoluteFile()); - - // Compare the original and newly saved document - assertTrue(targetFile.exists()); - ZipFileAssert.assertEquals(new File(originalFile), targetFile); - assertTrue(targetFile.delete()); - } finally { - // use revert to not re-write the input file - p.revert(); - } - } - } - - /** - * Test that when we create a new Package, we give it - * the correct default content types - */ - @Test - void createGetsContentTypes() - throws IOException, InvalidFormatException, SecurityException, IllegalArgumentException { - File targetFile = getOutputFile("TestCreatePackageTMP.docx"); - - // Zap the target file, in case of an earlier run - if(targetFile.exists()) { - assertTrue(targetFile.delete()); - } - - try (OPCPackage pkg = OPCPackage.create(targetFile)) { - try { - // Check it has content types for rels and xml - ContentTypeManager ctm = getContentTypeManager(pkg); - assertEquals("application/xml", ctm.getContentType(createPartName("/foo.xml"))); - assertEquals(ContentTypes.RELATIONSHIPS_PART, ctm.getContentType(createPartName("/foo.rels"))); - assertNull(ctm.getContentType(createPartName("/foo.txt"))); - } finally { - pkg.revert(); - } - } - } - - /** - * Test package creation. - */ - @Test - void createPackageAddPart() throws IOException, InvalidFormatException { - File targetFile = getOutputFile("TestCreatePackageTMP.docx"); - - File expectedFile = getSampleFile("TestCreatePackageOUTPUT.docx"); - - // Zap the target file, in case of an earlier run - if(targetFile.exists()) { - assertTrue(targetFile.delete()); - } - - // Create a package - OPCPackage pkg = OPCPackage.create(targetFile); - PackagePartName corePartName = createPartName("/word/document.xml"); - - pkg.addRelationship(corePartName, TargetMode.INTERNAL, - PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); - - PackagePart corePart = pkg.createPart(corePartName, XWPFRelation.DOCUMENT.getContentType()); - - Document doc = DocumentHelper.createDocument(); - Element elDocument = doc.createElementNS(NS_OOXML_WP_MAIN, "w:document"); - doc.appendChild(elDocument); - Element elBody = doc.createElementNS(NS_OOXML_WP_MAIN, "w:body"); - elDocument.appendChild(elBody); - Element elParagraph = doc.createElementNS(NS_OOXML_WP_MAIN, "w:p"); - elBody.appendChild(elParagraph); - Element elRun = doc.createElementNS(NS_OOXML_WP_MAIN, "w:r"); - elParagraph.appendChild(elRun); - Element elText = doc.createElementNS(NS_OOXML_WP_MAIN, "w:t"); - elRun.appendChild(elText); - elText.setTextContent("Hello Open XML !"); - - StreamHelper.saveXmlInStream(doc, corePart.getOutputStream()); - pkg.close(); - - ZipFileAssert.assertEquals(expectedFile, targetFile); - assertTrue(targetFile.delete()); - } - - /** - * Tests that we can create a new package, add a core - * document and another part, save and re-load and - * have everything setup as expected - */ - @Test - void createPackageWithCoreDocument() throws IOException, InvalidFormatException, URISyntaxException, SAXException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try (OPCPackage pkg = OPCPackage.create(baos)) { - - // Add a core document - PackagePartName corePartName = createPartName("/xl/workbook.xml"); - // Create main part relationship - pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); - // Create main document part - PackagePart corePart = pkg.createPart(corePartName, XSSFRelation.WORKBOOK.getContentType()); - // Put in some dummy content - try (OutputStream coreOut = corePart.getOutputStream()) { - coreOut.write("<dummy-xml />".getBytes(StandardCharsets.UTF_8)); - } - - // And another bit - PackagePartName sheetPartName = createPartName("/xl/worksheets/sheet1.xml"); - PackageRelationship rel = corePart.addRelationship( - sheetPartName, TargetMode.INTERNAL, XSSFRelation.WORKSHEET.getRelation(), "rSheet1"); - assertNotNull(rel); - - PackagePart part = pkg.createPart(sheetPartName, XSSFRelation.WORKSHEET.getContentType()); - assertNotNull(part); - - // Dummy content again - try (OutputStream coreOut = corePart.getOutputStream()) { - coreOut.write("<dummy-xml2 />".getBytes(StandardCharsets.UTF_8)); - } - - //add a relationship with internal target: "#Sheet1!A1" - corePart.addRelationship(new URI("#Sheet1!A1"), TargetMode.INTERNAL, PackageRelationshipTypes.HYPERLINK_PART, "rId2"); - - // Check things are as expected - PackageRelationshipCollection coreRels = - pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); - assertEquals(1, coreRels.size()); - PackageRelationship coreRel = coreRels.getRelationship(0); - assertNotNull(coreRel); - assertEquals("/", coreRel.getSourceURI().toString()); - assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString()); - assertNotNull(pkg.getPart(coreRel)); - } - - - // Save and re-load - File tmp = TempFile.createTempFile("testCreatePackageWithCoreDocument", ".zip"); - try (OutputStream fout = new FileOutputStream(tmp)) { - baos.writeTo(fout); - fout.flush(); - } - - try (OPCPackage pkg = OPCPackage.open(tmp.getPath())) { - // Check still right - PackageRelationshipCollection coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); - assertEquals(1, coreRels.size()); - PackageRelationship coreRel = coreRels.getRelationship(0); - - assertNotNull(coreRel); - assertEquals("/", coreRel.getSourceURI().toString()); - assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString()); - PackagePart corePart = pkg.getPart(coreRel); - assertNotNull(corePart); - - PackageRelationshipCollection rels = corePart.getRelationshipsByType(PackageRelationshipTypes.HYPERLINK_PART); - assertEquals(1, rels.size()); - PackageRelationship rel = rels.getRelationship(0); - assertNotNull(rel); - assertEquals("Sheet1!A1", rel.getTargetURI().getRawFragment()); - - assertMSCompatibility(pkg); - } - } - - private void assertMSCompatibility(OPCPackage pkg) throws IOException, InvalidFormatException, SAXException { - PackagePartName relName = createPartName(PackageRelationship.getContainerPartRelationship()); - PackagePart relPart = pkg.getPart(relName); - - Document xmlRelationshipsDoc = DocumentHelper.readDocument(relPart.getInputStream()); - - Element root = xmlRelationshipsDoc.getDocumentElement(); - NodeList nodeList = root.getElementsByTagName(PackageRelationship.RELATIONSHIP_TAG_NAME); - int nodeCount = nodeList.getLength(); - for (int i = 0; i < nodeCount; i++) { - Element element = (Element) nodeList.item(i); - String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME); - assertTrue(value.charAt(0) != '/', "Root target must not start with a leading slash ('/'): " + value); - } - - } - - /** - * Test package opening. - */ - @Test - void openPackage() throws IOException, InvalidFormatException { - File targetFile = getOutputFile("TestOpenPackageTMP.docx"); - - File inputFile = getSampleFile("TestOpenPackageINPUT.docx"); - - File expectedFile = getSampleFile("TestOpenPackageOUTPUT.docx"); - - // Copy the input file in the output directory - FileHelper.copyFile(inputFile, targetFile); - - // Create a package - OPCPackage pkg = OPCPackage.open(targetFile.getAbsolutePath()); - - // Modify core part - PackagePartName corePartName = createPartName("/word/document.xml"); - - PackagePart corePart = pkg.getPart(corePartName); - - // Delete some part to have a valid document - for (PackageRelationship rel : corePart.getRelationships()) { - corePart.removeRelationship(rel.getId()); - pkg.removePart(createPartName(PackagingURIHelper - .resolvePartUri(corePart.getPartName().getURI(), rel - .getTargetURI()))); - } - - // Create a content - Document doc = DocumentHelper.createDocument(); - Element elDocument = doc.createElementNS(NS_OOXML_WP_MAIN, "w:document"); - doc.appendChild(elDocument); - Element elBody = doc.createElementNS(NS_OOXML_WP_MAIN, "w:body"); - elDocument.appendChild(elBody); - Element elParagraph = doc.createElementNS(NS_OOXML_WP_MAIN, "w:p"); - elBody.appendChild(elParagraph); - Element elRun = doc.createElementNS(NS_OOXML_WP_MAIN, "w:r"); - elParagraph.appendChild(elRun); - Element elText = doc.createElementNS(NS_OOXML_WP_MAIN, "w:t"); - elRun.appendChild(elText); - elText.setTextContent("Hello Open XML !"); - - StreamHelper.saveXmlInStream(doc, corePart.getOutputStream()); - - // Save and close - assertDoesNotThrow(pkg::close); - - ZipFileAssert.assertEquals(expectedFile, targetFile); - assertTrue(targetFile.delete()); - } - - /** - * Checks that we can write a package to a simple - * OutputStream, in addition to the normal writing - * to a file - */ - @Test - void saveToOutputStream() throws IOException, InvalidFormatException { - String originalFile = getSampleFileName("TestPackageCommon.docx"); - File targetFile = getOutputFile("TestPackageOpenSaveTMP.docx"); - - try (OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE)) { - try { - try (FileOutputStream fout = new FileOutputStream(targetFile)) { - p.save(fout); - } - - // Compare the original and newly saved document - assertTrue(targetFile.exists()); - ZipFileAssert.assertEquals(new File(originalFile), targetFile); - assertTrue(targetFile.delete()); - } finally { - // use revert to not re-write the input file - p.revert(); - } - } - } - - /** - * Checks that we can open+read a package from a - * simple InputStream, in addition to the normal - * reading from a file - */ - @Test - void openFromInputStream() throws IOException, InvalidFormatException { - String originalFile = getSampleFileName("TestPackageCommon.docx"); - - try (FileInputStream finp = new FileInputStream(originalFile); - OPCPackage p = OPCPackage.open(finp)) { - try { - assertNotNull(p); - assertNotNull(p.getRelationships()); - assertEquals(12, p.getParts().size()); - - // Check it has the usual bits - assertTrue(p.hasRelationships()); - assertTrue(p.containPart(createPartName("/_rels/.rels"))); - } finally { - p.revert(); - } - } - } - - /** - * TODO: fix and enable - */ - @Test - @Disabled - void removePartRecursive() throws IOException, InvalidFormatException, URISyntaxException { - String originalFile = getSampleFileName("TestPackageCommon.docx"); - File targetFile = getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx"); - File tempFile = getOutputFile("TestPackageRemovePartRecursiveTMP.docx"); - - try (OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE)) { - p.removePartRecursive(createPartName(new URI("/word/document.xml"))); - p.save(tempFile.getAbsoluteFile()); - - // Compare the original and newly saved document - assertTrue(targetFile.exists()); - ZipFileAssert.assertEquals(targetFile, tempFile); - assertTrue(targetFile.delete()); - p.revert(); - } - } - - @Test - void deletePart() throws InvalidFormatException, IOException { - final TreeMap<PackagePartName, String> expectedValues = new TreeMap<>(); - final TreeMap<PackagePartName, String> values = new TreeMap<>(); - - // Expected values - expectedValues.put(createPartName("/_rels/.rels"), ContentTypes.RELATIONSHIPS_PART); - expectedValues.put(createPartName("/docProps/app.xml"), CONTENT_EXT_PROPS); - expectedValues.put(createPartName("/docProps/core.xml"), ContentTypes.CORE_PROPERTIES_PART); - expectedValues.put(createPartName("/word/fontTable.xml"), XWPFRelation.FONT_TABLE.getContentType()); - expectedValues.put(createPartName("/word/media/image1.gif"), XWPFRelation.IMAGE_GIF.getContentType()); - expectedValues.put(createPartName("/word/settings.xml"), XWPFRelation.SETTINGS.getContentType()); - expectedValues.put(createPartName("/word/styles.xml"), XWPFRelation.STYLES.getContentType()); - expectedValues.put(createPartName("/word/theme/theme1.xml"), XWPFRelation.THEME.getContentType()); - expectedValues.put(createPartName("/word/webSettings.xml"), XWPFRelation.WEB_SETTINGS.getContentType()); - - String filepath = getSampleFileName("sample.docx"); - - try (OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE)) { - try { - // Remove the core part - p.deletePart(createPartName("/word/document.xml")); - - for (PackagePart part : p.getParts()) { - values.put(part.getPartName(), part.getContentType()); - LOG.atDebug().log(part.getPartName()); - } - - // Compare expected values with values return by the package - for (PackagePartName partName : expectedValues.keySet()) { - assertNotNull(values.get(partName)); - assertEquals(expectedValues.get(partName), values.get(partName)); - } - } finally { - // Don't save modifications - p.revert(); - } - } - } - - @Test - void deletePartRecursive() throws InvalidFormatException, IOException { - final TreeMap<PackagePartName, String> expectedValues = new TreeMap<>(); - final TreeMap<PackagePartName, String> values = new TreeMap<>(); - - // Expected values - expectedValues.put(createPartName("/_rels/.rels"), ContentTypes.RELATIONSHIPS_PART); - expectedValues.put(createPartName("/docProps/app.xml"), CONTENT_EXT_PROPS); - expectedValues.put(createPartName("/docProps/core.xml"), ContentTypes.CORE_PROPERTIES_PART); - - String filepath = getSampleFileName("sample.docx"); - - try (OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE)) { - try { - // Remove the core part - p.deletePartRecursive(createPartName("/word/document.xml")); - - for (PackagePart part : p.getParts()) { - values.put(part.getPartName(), part.getContentType()); - LOG.atDebug().log(part.getPartName()); - } - - // Compare expected values with values return by the package - for (PackagePartName partName : expectedValues.keySet()) { - assertNotNull(values.get(partName)); - assertEquals(expectedValues.get(partName), values.get(partName)); - } - } finally { - // Don't save modifications - p.revert(); - } - } - } - - /** - * Test that we can open a file by path, and then - * write changes to it. - */ - @Test - void openFileThenOverwrite() throws IOException, InvalidFormatException { - File tempFile = TempFile.createTempFile("poiTesting","tmp"); - File origFile = getSampleFile("TestPackageCommon.docx"); - FileHelper.copyFile(origFile, tempFile); - - // Open and close the temp file - try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE)) { - assertNotNull(p); - } - // Delete it - assertTrue(tempFile.delete()); - - // Reset - FileHelper.copyFile(origFile, tempFile); - try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE)) { - // Save it to the same file - not allowed - assertThrows(InvalidOperationException.class, () -> p.save(tempFile), - "You shouldn't be able to call save(File) to overwrite the current file"); - } - // Delete it - assertTrue(tempFile.delete()); - - - // Open it read only, then close and delete - allowed - FileHelper.copyFile(origFile, tempFile); - try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ)) { - assertNotNull(p); - } - assertTrue(tempFile.delete()); - } - - /** - * Test that we can open a file by path, save it - * to another file, then delete both - */ - @Test - void openFileThenSaveDelete() throws IOException, InvalidFormatException { - File tempFile = TempFile.createTempFile("poiTesting","tmp"); - File tempFile2 = TempFile.createTempFile("poiTesting","tmp"); - File origFile = getSampleFile("TestPackageCommon.docx"); - FileHelper.copyFile(origFile, tempFile); - - // Open the temp file - try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE)) { - // Save it to a different file - p.save(tempFile2); - } - - // Delete both the files - assertTrue(tempFile.delete()); - assertTrue(tempFile2.delete()); - } - - private static ContentTypeManager getContentTypeManager(OPCPackage pkg) { - return POITestCase.getFieldValue(OPCPackage.class, pkg, ContentTypeManager.class, "contentTypeManager"); - } - - @Test - void getPartsByName() throws InvalidFormatException, IOException { - String filepath = getSampleFileName("sample.docx"); - - try (OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE)) { - try { - List<PackagePart> rs = pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml")); - HashMap<String, PackagePart> selected = new HashMap<>(); - - for (PackagePart p : rs) - selected.put(p.getPartName().getName(), p); - - assertEquals(6, selected.size()); - assertTrue(selected.containsKey("/word/document.xml")); - assertTrue(selected.containsKey("/word/fontTable.xml")); - assertTrue(selected.containsKey("/word/settings.xml")); - assertTrue(selected.containsKey("/word/styles.xml")); - assertTrue(selected.containsKey("/word/theme/theme1.xml")); - assertTrue(selected.containsKey("/word/webSettings.xml")); - } finally { - // use revert to not re-write the input file - pkg.revert(); - } - } - } - - @Test - void getPartSize() throws IOException, InvalidFormatException { - String filepath = getSampleFileName("sample.docx"); - try (OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ)) { - int checked = 0; - for (PackagePart part : pkg.getParts()) { - // Can get the size of zip parts - if (part.getPartName().getName().equals("/word/document.xml")) { - checked++; - assertEquals(ZipPackagePart.class, part.getClass()); - assertEquals(6031L, part.getSize()); - } - if (part.getPartName().getName().equals("/word/fontTable.xml")) { - checked++; - assertEquals(ZipPackagePart.class, part.getClass()); - assertEquals(1312L, part.getSize()); - } - - // But not from the others - if (part.getPartName().getName().equals("/docProps/core.xml")) { - checked++; - assertEquals(PackagePropertiesPart.class, part.getClass()); - assertEquals(-1, part.getSize()); - } - } - // Ensure we actually found the parts we want to check - assertEquals(3, checked); - } - } - - @Test - void replaceContentType() throws IOException, InvalidFormatException { - try (InputStream is = openSampleStream("sample.xlsx"); - OPCPackage p = OPCPackage.open(is)) { - try { - ContentTypeManager mgr = getContentTypeManager(p); - - assertTrue(mgr.isContentTypeRegister(XSSFRelation.WORKBOOK.getContentType())); - assertFalse(mgr.isContentTypeRegister(XSSFRelation.MACROS_WORKBOOK.getContentType())); - assertTrue(p.replaceContentType(XSSFRelation.WORKBOOK.getContentType(), XSSFRelation.MACROS_WORKBOOK.getContentType())); - - assertFalse(mgr.isContentTypeRegister(XSSFRelation.WORKBOOK.getContentType())); - assertTrue(mgr.isContentTypeRegister(XSSFRelation.MACROS_WORKBOOK.getContentType())); - } finally { - p.revert(); - } - } - } - - @SuppressWarnings("unchecked") - @ParameterizedTest - @CsvSource({ - "SampleSS.xls, org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException, The supplied data appears to be in the OLE2 Format, You are calling the part of POI that deals with OOXML", - "SampleSS.xml, org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException, The supplied data appears to be a raw XML file, Formats such as Office 2003 XML", - "SampleSS.ods, org.apache.poi.openxml4j.exceptions.ODFNotOfficeXmlFileException, The supplied data appears to be in ODF, Formats like these (eg ODS", - "SampleSS.txt, org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException, No valid entries or contents found, not a valid OOXML" - }) - void NonOOXML_File(String file, String exClazzStr, String msg1, String msg2) throws Exception { - Class<? extends Exception> exClazz = (Class<? extends Exception>)Class.forName(exClazzStr); - - try (InputStream stream = xlsSamples.openResourceAsStream(file)) { - Executable[] trs = { - () -> OPCPackage.open(stream), - () -> OPCPackage.open(xlsSamples.getFile(file)) - }; - for (Executable tr : trs) { - Exception ex = assertThrows(exClazz, tr, "Shouldn't be able to open "+file); - Stream.of(msg1, msg2).forEach(mp -> assertTrue(ex.getMessage().contains(mp))); - } - } - } - - /** - * Zip bomb handling test - * - * see bug #50090 / #56865 - */ - @Test - void zipBombCreateAndHandle() - throws IOException, EncryptedDocumentException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(2500000); - - try (ZipFile zipFile = ZipHelper.openZipFile(getSampleFile("sample.xlsx")); - ZipArchiveOutputStream append = new ZipArchiveOutputStream(bos)) { - assertNotNull(zipFile); - - // first, copy contents from existing war - Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries(); - while (entries.hasMoreElements()) { - final ZipArchiveEntry eIn = entries.nextElement(); - final ZipArchiveEntry eOut = new ZipArchiveEntry(eIn.getName()); - eOut.setTime(eIn.getTime()); - eOut.setComment(eIn.getComment()); - eOut.setSize(eIn.getSize()); - - append.putArchiveEntry(eOut); - if (!eOut.isDirectory()) { - try (InputStream is = zipFile.getInputStream(eIn)) { - if (eOut.getName().equals("[Content_Types].xml")) { - ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); - IOUtils.copy(is, bos2); - long size = bos2.size() - "</Types>".length(); - append.write(bos2.toByteArray(), 0, (int) size); - byte[] spam = new byte[0x7FFF]; - Arrays.fill(spam, (byte) ' '); - // 0x7FFF0000 is the maximum for 32-bit zips, but less still works - while (size < 0x7FFF00) { - append.write(spam); - size += spam.length; - } - append.write("</Types>".getBytes(StandardCharsets.UTF_8)); - size += 8; - eOut.setSize(size); - } else { - IOUtils.copy(is, append); - } - } - } - append.closeArchiveEntry(); - } - } - - IOException ex = assertThrows( - IOException.class, - () -> WorkbookFactory.create(new ByteArrayInputStream(bos.toByteArray())) - ); - assertTrue(ex.getMessage().contains("Zip bomb detected!")); - } - - @Test - void testZipEntityExpansionTerminates() { - IllegalStateException ex = assertThrows( - IllegalStateException.class, - () -> openXmlBombFile("poc-shared-strings.xlsx") - ); - assertTrue(ex.getMessage().contains("The text would exceed the max allowed overall size of extracted text.")); - } - - @Test - void testZipEntityExpansionSharedStringTableEvents() { - boolean before = ExtractorFactory.getThreadPrefersEventExtractors(); - ExtractorFactory.setThreadPrefersEventExtractors(true); - try { - IllegalStateException ex = assertThrows( - IllegalStateException.class, - () -> openXmlBombFile("poc-shared-strings.xlsx") - ); - assertTrue(ex.getMessage().contains("The text would exceed the max allowed overall size of extracted text.")); - } finally { - ExtractorFactory.setThreadPrefersEventExtractors(before); - } - } - - - @Test - void testZipEntityExpansionExceedsMemory() { - IOException ex = assertThrows( - IOException.class, - () -> openXmlBombFile("poc-xmlbomb.xlsx") - ); - assertTrue(ex.getMessage().contains("unable to parse shared strings table")); - assertTrue(matchSAXEx(ex)); - } - - @Test - void testZipEntityExpansionExceedsMemory2() { - IOException ex = assertThrows( - IOException.class, - () -> openXmlBombFile("poc-xmlbomb-empty.xlsx") - ); - assertTrue(ex.getMessage().contains("unable to parse shared strings table")); - assertTrue(matchSAXEx(ex)); - } - - private static boolean matchSAXEx(Exception root) { - for (Throwable t = root; t != null; t = t.getCause()) { - if (t.getClass().isAssignableFrom(SAXParseException.class) && - t.getMessage().contains("The parser has encountered more than")) { - return true; - } - } - return false; - } - - private void openXmlBombFile(String file) throws IOException { - final double minInf = ZipSecureFile.getMinInflateRatio(); - ZipSecureFile.setMinInflateRatio(0.002); - try (POITextExtractor extractor = ExtractorFactory.createExtractor(XSSFTestDataSamples.getSampleFile(file))) { - assertNotNull(extractor); - extractor.getText(); - } finally { - ZipSecureFile.setMinInflateRatio(minInf); - } - } - - @Test - void zipBombCheckSizesWithinLimits() throws IOException, EncryptedDocumentException { - getZipStatsAndConsume((max_size, min_ratio) -> { - // use values close to, but within the limits - ZipSecureFile.setMinInflateRatio(min_ratio - 0.002); - assertEquals(min_ratio - 0.002, ZipSecureFile.getMinInflateRatio(), 0.00001); - ZipSecureFile.setMaxEntrySize(max_size + 1); - assertEquals(max_size + 1, ZipSecureFile.getMaxEntrySize()); - }); - } - - @Test - void zipBombCheckSizesRatioTooSmall() { - POIXMLException ex = assertThrows( - POIXMLException.class, - () -> getZipStatsAndConsume((max_size, min_ratio) -> { - // check ratio out of bounds - ZipSecureFile.setMinInflateRatio(min_ratio+0.002); - }) - ); - assertTrue(ex.getMessage().contains("You can adjust this limit via ZipSecureFile.setMinInflateRatio()")); - } - - @Test - void zipBombCheckSizesSizeTooBig() throws EncryptedDocumentException { - POIXMLException ex = assertThrows( - POIXMLException.class, - () -> getZipStatsAndConsume((max_size, min_ratio) -> { - // check max entry size ouf of bounds - ZipSecureFile.setMinInflateRatio(min_ratio-0.002); - ZipSecureFile.setMaxEntrySize(max_size-200); - }) - ); - assertTrue(ex.getMessage().contains("You can adjust this limit via ZipSecureFile.setMaxEntrySize()")); - } - - private void getZipStatsAndConsume(BiConsumer<Long,Double> ratioCon) throws IOException { - // use a test file with a xml file bigger than 100k (ZipArchiveThresholdInputStream.GRACE_ENTRY_SIZE) - final File file = XSSFTestDataSamples.getSampleFile("poc-shared-strings.xlsx"); - - double min_ratio = Double.MAX_VALUE; - long max_size = 0; - try (ZipFile zf = ZipHelper.openZipFile(file)) { - assertNotNull(zf); - Enumeration<? extends ZipArchiveEntry> entries = zf.getEntries(); - while (entries.hasMoreElements()) { - ZipArchiveEntry ze = entries.nextElement(); - if (ze.getSize() == 0) { - continue; - } - // add zip entry header ~ 128 bytes - long size = ze.getSize()+128; - double ratio = ze.getCompressedSize() / (double)size; - min_ratio = Math.min(min_ratio, ratio); - max_size = Math.max(max_size, size); - } - } - ratioCon.accept(max_size, min_ratio); - - //noinspection EmptyTryBlock,unused - try (Workbook wb = WorkbookFactory.create(file, null, true)) { - } finally { - // reset otherwise a lot of ooxml tests will fail - ZipSecureFile.setMinInflateRatio(0.01d); - ZipSecureFile.setMaxEntrySize(0xFFFFFFFFL); - } - } - - @Test - void testConstructors() throws IOException { - // verify the various ways to construct a ZipSecureFile - File file = getSampleFile("sample.xlsx"); - try (ZipSecureFile zipFile = new ZipSecureFile(file)) { - assertNotNull(zipFile.getName()); - } - - try (ZipSecureFile zipFile = new ZipSecureFile(file.getAbsolutePath())) { - assertNotNull(zipFile.getName()); - } - } - - @Test - void testMaxTextSize() { - long before = ZipSecureFile.getMaxTextSize(); - try { - ZipSecureFile.setMaxTextSize(12345); - assertEquals(12345, ZipSecureFile.getMaxTextSize()); - } finally { - ZipSecureFile.setMaxTextSize(before); - } - } - - // bug 60128 - @Test - void testCorruptFile() { - File file = getSampleFile("invalid.xlsx"); - assertThrows(NotOfficeXmlFileException.class, () -> OPCPackage.open(file, PackageAccess.READ)); - } - - private interface CountingStream { - InputStream create(InputStream is, int length); - } - - // bug 61381 - @Test - void testTooShortFilterStreams() throws IOException { - for (String file : new String[]{"sample.xlsx","SampleSS.xls"}) { - for (CountingStream cs : new CountingStream[]{PushbackInputStream::new, BufferedInputStream::new}) { - try (InputStream is = cs.create(xlsSamples.openResourceAsStream(file), 2); - Workbook wb = WorkbookFactory.create(is)) { - assertEquals(3, wb.getNumberOfSheets()); - } - } - } - } - - @Test - void testBug56479() throws Exception { - try (InputStream is = openSampleStream("dcterms_bug_56479.zip"); - OPCPackage p = OPCPackage.open(is)) { - - // Check we found the contents of it - boolean foundCoreProps = false, foundDocument = false, foundTheme1 = false; - for (final PackagePart part : p.getParts()) { - final String partName = part.getPartName().toString(); - final String contentType = part.getContentType(); - switch (partName) { - case "/docProps/core.xml": - assertEquals(ContentTypes.CORE_PROPERTIES_PART, contentType); - foundCoreProps = true; - break; - case "/word/document.xml": - assertEquals(XWPFRelation.DOCUMENT.getContentType(), contentType); - foundDocument = true; - break; - case "/word/theme/theme1.xml": - assertEquals(XWPFRelation.THEME.getContentType(), contentType); - foundTheme1 = true; - break; - } - } - assertTrue(foundCoreProps, "Core not found in " + p.getParts()); - assertFalse(foundDocument, "Document should not be found in " + p.getParts()); - assertFalse(foundTheme1, "Theme1 should not found in " + p.getParts()); - } - } - - @Test - void unparseableCentralDirectory() throws IOException { - File f = getSampleFile("at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx"); - try (SlideShow<?,?> ppt = SlideShowFactory.create(f, null, true)) { - assertNotNull(ppt); - assertNotNull(ppt.getSlides().get(0)); - } - } - - @Test - void testClosingStreamOnException() throws IOException { - File tmp = File.createTempFile("poi-test-truncated-zip", ""); - - // create a corrupted zip file by truncating a valid zip file to the first 100 bytes - try (InputStream is = openSampleStream("dcterms_bug_56479.zip"); - OutputStream os = new FileOutputStream(tmp)) { - IOUtils.copy(is, os, 100); - } - - // feed the corrupted zip file to OPCPackage - // expected: the zip file is invalid - // this test does not care if open() throws an exception or not. - assertThrows(Exception.class, () -> OPCPackage.open(tmp, PackageAccess.READ)); - - // If the stream is not closed on exception, it will keep a file descriptor to tmp, - // and requests to the OS to delete the file will fail. - assertTrue(tmp.delete(), "Can't delete tmp file"); - } - - /** - * If ZipPackage is passed an invalid file, a call to close - * (eg from the OPCPackage open method) should tidy up the - * stream / file the broken file is being read from. - * See bug #60128 for more - */ - @Test - void testTidyStreamOnInvalidFile1() throws Exception { - openInvalidFile("SampleSS.ods", false); - } - - @Test - void testTidyStreamOnInvalidFile2() throws Exception { - openInvalidFile("SampleSS.ods", true); - } - - @Test - void testTidyStreamOnInvalidFile3() throws Exception { - openInvalidFile("SampleSS.txt", false); - } - - @Test - void testTidyStreamOnInvalidFile4() throws Exception { - openInvalidFile("SampleSS.txt", true); - } - - @Test - void testBug62592() throws Exception { - try (InputStream is = openSampleStream("62592.thmx")) { - assertThrows(InvalidFormatException.class, () -> OPCPackage.open(is)); - } - } - - @Test - void testBug62592SequentialCallsToGetParts() throws Exception { - //make absolutely certain that sequential calls don't throw InvalidFormatExceptions - String originalFile = getSampleFileName("TestPackageCommon.docx"); - try (OPCPackage p2 = OPCPackage.open(originalFile, PackageAccess.READ)) { - assertDoesNotThrow(p2::getParts); - assertDoesNotThrow(p2::getParts); - } - } - - @Test - void testDoNotCloseStream() throws IOException { - // up to JDK 10 we did use Mockito here, but OutputStream is - // an abstract class and fails mocking with some changes in JDK 11 - // so we use a simple empty output stream implementation instead - OutputStream os = new OutputStream() { - @Override - public void write(int b) { - } - - @Override - public void close() { - fail("close should not be called here"); - } - }; - - try (XSSFWorkbook wb = new XSSFWorkbook()) { - wb.createSheet(); - wb.write(os); - } - - try (SXSSFWorkbook wb = new SXSSFWorkbook()) { - wb.createSheet(); - wb.write(os); - } - } - - - - private static void openInvalidFile(final String name, final boolean useStream) throws IOException { - ZipPackage[] pkgTest = { null }; - try (final InputStream is = (useStream) ? xlsSamples.openResourceAsStream(name) : null) { - assertThrows(NotOfficeXmlFileException.class, () -> { - try (final ZipPackage pkg = (useStream) - ? new ZipPackage(is, PackageAccess.READ) - : new ZipPackage(xlsSamples.getFile(name), PackageAccess.READ)) { - pkgTest[0] = pkg; - assertNotNull(pkg.getZipArchive()); - assertFalse(pkg.getZipArchive().isClosed()); - pkg.getParts(); - } - }); - } finally { - if (pkgTest[0] != null) { - assertNotNull(pkgTest[0].getZipArchive()); - assertTrue(pkgTest[0].getZipArchive().isClosed()); - } - } - } - - @SuppressWarnings("UnstableApiUsage") - @Test - void testBug63029() throws Exception { - File testFile = getSampleFile("sample.docx"); - File tmpFile = getOutputFile("Bug63029.docx"); - Files.copy(testFile, tmpFile); - - int numPartsBefore = 0; - String md5Before = Files.asByteSource(tmpFile).hash(Hashing.sha256()).toString(); - - try(OPCPackage pkg = OPCPackage.open(tmpFile, PackageAccess.READ_WRITE)) - { - numPartsBefore = pkg.getParts().size(); - - // add a marshaller that will throw an exception on save - pkg.addMarshaller("poi/junit", (part, out) -> { - throw new RuntimeException("Bugzilla 63029"); - }); - - pkg.createPart(createPartName("/poi/test.xml"), "poi/junit"); - - RuntimeException ex = assertThrows(RuntimeException.class, pkg::close); - // verify there was an exception while closing the file - assertEquals("Fail to save: an error occurs while saving the package : Bugzilla 63029", ex.getMessage()); - } - - // assert that md5 after closing is the same, i.e. the source is left intact - String md5After = Files.asByteSource(tmpFile).hash(Hashing.sha256()).toString(); - assertEquals(md5Before, md5After); - - // try to read the source file once again - try ( OPCPackage pkg = OPCPackage.open(tmpFile, PackageAccess.READ_WRITE)){ - // the source is still a valid zip archive. - // prior to the fix this used to throw NotOfficeXmlFileException("archive is not a ZIP archive") - - // assert that the number of parts remained the same - assertEquals(pkg.getParts().size(), numPartsBefore); - } - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java deleted file mode 100644 index 317d1009a0..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java +++ /dev/null @@ -1,323 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.InputStream; -import java.text.ParsePosition; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.Optional; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty; - -import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive; -import static org.junit.jupiter.api.Assertions.*; - -public final class TestPackageCoreProperties { - /** - * Test package core properties getters. - */ - @Test - void testGetProperties() throws Exception { - // Open the package - @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(OpenXML4JTestDataSamples.openSampleStream("TestPackageCoreProperiesGetters.docx")); - compareProperties(p); - p.revert(); - } - - /** - * Test package core properties setters. - */ - @Test - void testSetProperties() throws Exception { - String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCoreProperiesSetters.docx"); - - File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx"); - - // Open package - @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE); - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - Date dateToInsert = df.parse("2007-05-12T08:00:00Z", new ParsePosition(0)); - - SimpleDateFormat msdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT); - msdf.setTimeZone(LocaleUtil.TIMEZONE_UTC); - - PackageProperties props = p.getPackageProperties(); - - //test various date formats - props.setCreatedProperty("2007-05-12T08:00:00Z"); - assertEquals(dateToInsert, props.getCreatedProperty().get()); - - props.setCreatedProperty("2007-05-12T08:00:00"); //no Z, assume Z - assertEquals(dateToInsert, props.getCreatedProperty().get()); - - props.setCreatedProperty("2007-05-12T08:00:00.123Z");//millis - assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().get()); - - props.setCreatedProperty("2007-05-12T10:00:00+0200"); - assertEquals(dateToInsert, props.getCreatedProperty().get()); - - props.setCreatedProperty("2007-05-12T10:00:00+02:00");//colon in tz - assertEquals(dateToInsert, props.getCreatedProperty().get()); - - props.setCreatedProperty("2007-05-12T06:00:00-0200"); - assertEquals(dateToInsert, props.getCreatedProperty().get()); - - props.setCreatedProperty("2015-07-27"); - assertEquals(msdf.parse("2015-07-27T00:00:00.000Z"), props.getCreatedProperty().get()); - - props.setCreatedProperty("2007-05-12T10:00:00.123+0200"); - assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().get()); - - props.setCategoryProperty("MyCategory"); - props.setContentStatusProperty("MyContentStatus"); - props.setContentTypeProperty("MyContentType"); - props.setCreatorProperty("MyCreator"); - props.setDescriptionProperty("MyDescription"); - props.setIdentifierProperty("MyIdentifier"); - props.setKeywordsProperty("MyKeywords"); - props.setLanguageProperty("MyLanguage"); - props.setLastModifiedByProperty("Julien Chable"); - props.setLastPrintedProperty(Optional.of(dateToInsert)); - props.setModifiedProperty(Optional.of(dateToInsert)); - props.setRevisionProperty("2"); - props.setTitleProperty("MyTitle"); - props.setSubjectProperty("MySubject"); - props.setVersionProperty("2"); - // Save the package in the output directory - p.save(outputFile); - p.revert(); - - // Open the newly created file to check core properties saved values. - @SuppressWarnings("resource") - OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ); - compareProperties(p2); - p2.revert(); - outputFile.delete(); - } - - private void compareProperties(OPCPackage p) throws InvalidFormatException { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - Date expectedDate = df.parse("2007-05-12T08:00:00Z", new ParsePosition(0)); - - // Gets the core properties - PackageProperties props = p.getPackageProperties(); - assertEquals("MyCategory", props.getCategoryProperty().get()); - assertEquals("MyContentStatus", props.getContentStatusProperty().get()); - assertEquals("MyContentType", props.getContentTypeProperty().get()); - assertEquals(expectedDate, props.getCreatedProperty().get()); - assertEquals("MyCreator", props.getCreatorProperty().get()); - assertEquals("MyDescription", props.getDescriptionProperty().get()); - assertEquals("MyIdentifier", props.getIdentifierProperty().get()); - assertEquals("MyKeywords", props.getKeywordsProperty().get()); - assertEquals("MyLanguage", props.getLanguageProperty().get()); - assertEquals("Julien Chable", props.getLastModifiedByProperty().get()); - assertEquals(expectedDate, props.getLastPrintedProperty().get()); - assertEquals(expectedDate, props.getModifiedProperty().get()); - assertEquals("2", props.getRevisionProperty().get()); - assertEquals("MySubject", props.getSubjectProperty().get()); - assertEquals("MyTitle", props.getTitleProperty().get()); - assertEquals("2", props.getVersionProperty().get()); - } - - @Test - void testCoreProperties_bug51374() throws Exception { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - String strDate = "2007-05-12T08:00:00Z"; - Date date = df.parse(strDate); - - OPCPackage pkg = new ZipPackage(); - PackagePropertiesPart props = (PackagePropertiesPart)pkg.getPackageProperties(); - - // created - assertEquals("", props.getCreatedPropertyString()); - assertFalse(props.getCreatedProperty().isPresent()); - props.setCreatedProperty((String)null); - assertEquals("", props.getCreatedPropertyString()); - assertFalse(props.getCreatedProperty().isPresent()); - props.setCreatedProperty(Optional.empty()); - assertEquals("", props.getCreatedPropertyString()); - assertFalse(props.getCreatedProperty().isPresent()); - props.setCreatedProperty(Optional.of(date)); - assertEquals(strDate, props.getCreatedPropertyString()); - assertEquals(date, props.getCreatedProperty().get()); - props.setCreatedProperty(strDate); - assertEquals(strDate, props.getCreatedPropertyString()); - assertEquals(date, props.getCreatedProperty().get()); - - // lastPrinted - assertEquals("", props.getLastPrintedPropertyString()); - assertFalse(props.getLastPrintedProperty().isPresent()); - props.setLastPrintedProperty((String)null); - assertEquals("", props.getLastPrintedPropertyString()); - assertFalse(props.getLastPrintedProperty().isPresent()); - props.setLastPrintedProperty(Optional.empty()); - assertEquals("", props.getLastPrintedPropertyString()); - assertFalse(props.getLastPrintedProperty().isPresent()); - props.setLastPrintedProperty(Optional.of(date)); - assertEquals(strDate, props.getLastPrintedPropertyString()); - assertEquals(date, props.getLastPrintedProperty().get()); - props.setLastPrintedProperty(strDate); - assertEquals(strDate, props.getLastPrintedPropertyString()); - assertEquals(date, props.getLastPrintedProperty().get()); - - // modified - assertFalse(props.getModifiedProperty().isPresent()); - props.setModifiedProperty((String)null); - assertFalse(props.getModifiedProperty().isPresent()); - props.setModifiedProperty(Optional.empty()); - assertFalse(props.getModifiedProperty().isPresent()); - props.setModifiedProperty(Optional.of(date)); - assertEquals(strDate, props.getModifiedPropertyString()); - assertEquals(date, props.getModifiedProperty().get()); - props.setModifiedProperty(strDate); - assertEquals(strDate, props.getModifiedPropertyString()); - assertEquals(date, props.getModifiedProperty().get()); - - // Tidy - pkg.close(); - } - - @Test - void testGetPropertiesLO() throws Exception { - // Open the package - OPCPackage pkg1 = OPCPackage.open(OpenXML4JTestDataSamples.openSampleStream("51444.xlsx")); - PackageProperties props1 = pkg1.getPackageProperties(); - assertFalse(props1.getTitleProperty().isPresent()); - props1.setTitleProperty("Bug 51444 fixed"); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - pkg1.save(out); - out.close(); - pkg1.close(); - - OPCPackage pkg2 = OPCPackage.open(new ByteArrayInputStream(out.toByteArray())); - PackageProperties props2 = pkg2.getPackageProperties(); - props2.setTitleProperty("Bug 51444 fixed"); - pkg2.close(); - } - - @Test - void testEntitiesInCoreProps_56164() throws Exception { - try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("CorePropertiesHasEntities.ooxml"); - OPCPackage p = OPCPackage.open(is)) { - - // Should have 3 root relationships - boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false; - for (PackageRelationship pr : p.getRelationships()) { - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT)) - foundDocRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) - foundCorePropRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES)) - foundExtPropRel = true; - } - assertTrue(foundDocRel, "Core Doc Relationship not found in " + p.getRelationships()); - assertTrue(foundCorePropRel, "Core Props Relationship not found in " + p.getRelationships()); - assertTrue(foundExtPropRel, "Ext Props Relationship not found in " + p.getRelationships()); - - // Get the Core Properties - PackagePropertiesPart props = (PackagePropertiesPart) p.getPackageProperties(); - - // used to resolve a value but now we ignore DTD entities for security reasons - assertEquals(isOldXercesActive(), props.getCreatorProperty().isPresent()); - } - } - - @Test - void testListOfCustomProperties() throws Exception { - File inp = POIDataSamples.getSpreadSheetInstance().getFile("ExcelWithAttachments.xlsm"); - OPCPackage pkg = OPCPackage.open(inp, PackageAccess.READ); - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - assertNotNull(wb.getProperties()); - assertNotNull(wb.getProperties().getCustomProperties()); - - for (CTProperty prop : wb.getProperties().getCustomProperties().getUnderlyingProperties().getPropertyList()) { - assertNotNull(prop); - } - - wb.close(); - pkg.close(); - } - - @Test - void testAlternateCorePropertyTimezones() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("OPCCompliance_CoreProperties_AlternateTimezones.docx"); - OPCPackage pkg = OPCPackage.open(is); - PackagePropertiesPart props = (PackagePropertiesPart)pkg.getPackageProperties(); - is.close(); - - // We need predictable dates for testing! - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - - // Check text properties first - assertEquals("Lorem Ipsum", props.getTitleProperty().get()); - assertEquals("Apache POI", props.getCreatorProperty().get()); - - // Created at has a +3 timezone and milliseconds - // 2006-10-13T18:06:00.123+03:00 - // = 2006-10-13T15:06:00.123+00:00 - assertEquals("2006-10-13T15:06:00Z", props.getCreatedPropertyString()); - assertEquals("2006-10-13T15:06:00.123Z", df.format(props.getCreatedProperty().get())); - - // Modified at has a -13 timezone but no milliseconds - // 2007-06-20T07:59:00-13:00 - // = 2007-06-20T20:59:00-13:00 - assertEquals("2007-06-20T20:59:00Z", props.getModifiedPropertyString()); - assertEquals("2007-06-20T20:59:00.000Z", df.format(props.getModifiedProperty().get())); - - - // Ensure we can change them with other timezones and still read back OK - props.setCreatedProperty("2007-06-20T20:57:00+13:00"); - props.setModifiedProperty("2007-06-20T20:59:00.123-13:00"); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - pkg.save(baos); - pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray())); - - // Check text properties first - should be unchanged - assertEquals("Lorem Ipsum", props.getTitleProperty().get()); - assertEquals("Apache POI", props.getCreatorProperty().get()); - - // Check the updated times - // 2007-06-20T20:57:00+13:00 - // = 2007-06-20T07:57:00Z - assertEquals("2007-06-20T07:57:00.000Z", df.format(props.getCreatedProperty().get())); - - // 2007-06-20T20:59:00.123-13:00 - // = 2007-06-21T09:59:00.123Z - assertEquals("2007-06-21T09:59:00.123Z", df.format(props.getModifiedProperty().get())); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java deleted file mode 100644 index 2572aadfad..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -public final class TestPackagePartName { - - /** - * Test method getExtension(). - */ - @Test - void testGetExtension() throws Exception{ - PackagePartName name1 = PackagingURIHelper.createPartName("/doc/props/document.xml"); - PackagePartName name2 = PackagingURIHelper.createPartName("/root/document"); - assertEquals("xml", name1.getExtension()); - assertEquals("", name2.getExtension()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java deleted file mode 100644 index e68a92d200..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.File; - -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * Test the addition of thumbnail in a package. - */ -public final class TestPackageThumbnail { - - /** - * Test package addThumbnail() method. - */ - @Test - void testSetProperties() throws Exception { - String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageThumbnail.docx"); - - String imagePath = OpenXML4JTestDataSamples.getSampleFileName("thumbnail.jpg"); - - File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageThumbnailOUTPUT.docx"); - - // Open package - try (OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE)) { - p.addThumbnail(imagePath); - // Save the package in the output directory - p.save(outputFile); - - // Open the newly created file to check core properties saved values. - try (OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ)) { - assertNotEquals(0, p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL).size(), - "Thumbnail not added to the package !"); - p2.revert(); - } - p.revert(); - } - assertTrue(outputFile.delete()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java deleted file mode 100644 index 714d81180b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java +++ /dev/null @@ -1,146 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.openxml4j.opc; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.net.URI; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.junit.jupiter.api.Test; - -class TestPackagingURIHelper { - - /** - * Test relativizePartName() method. - */ - @Test - void testRelativizeURI() throws Exception { - URI uri1 = new URI("/word/document.xml"); - URI uri2 = new URI("/word/media/image1.gif"); - URI uri3 = new URI("/word/media/image1.gif#Sheet1!A1"); - URI uri4 = new URI("#'My%20Sheet1'!A1"); - - // Document to image is down a directory - URI retURI1to2 = PackagingURIHelper.relativizeURI(uri1, uri2); - assertEquals("media/image1.gif", retURI1to2.getPath()); - // Image to document is up a directory - URI retURI2to1 = PackagingURIHelper.relativizeURI(uri2, uri1); - assertEquals("../document.xml", retURI2to1.getPath()); - - // Document and CustomXML parts totally different [Julien C.] - URI uriCustomXml = new URI("/customXml/item1.xml"); - URI uriRes = PackagingURIHelper.relativizeURI(uri1, uriCustomXml); - assertEquals("../customXml/item1.xml", uriRes.toString()); - - // Document to itself is the same place (empty URI) - URI retURI2 = PackagingURIHelper.relativizeURI(uri1, uri1); - // YK: the line below used to assert empty string which is wrong - // if source and target are the same they should be relaitivized as the last segment, - // see Bugzilla 51187 - assertEquals("document.xml", retURI2.getPath()); - - // relativization against root - URI root = new URI("/"); - uriRes = PackagingURIHelper.relativizeURI(root, uri1); - assertEquals("/word/document.xml", uriRes.toString()); - - //URI compatible with MS Office and OpenOffice: leading slash is removed - uriRes = PackagingURIHelper.relativizeURI(root, uri1, true); - assertNotNull(uriRes); - assertEquals("word/document.xml", uriRes.toString()); - - //preserve URI fragments - uriRes = PackagingURIHelper.relativizeURI(uri1, uri3, true); - assertNotNull(uriRes); - assertEquals("media/image1.gif#Sheet1!A1", uriRes.toString()); - assertNotNull(uriRes); - uriRes = PackagingURIHelper.relativizeURI(root, uri4, true); - assertNotNull(uriRes); - assertEquals("#'My%20Sheet1'!A1", uriRes.toString()); - } - - /** - * Test createPartName(String, y) - */ - @Test - void testCreatePartNameRelativeString() - throws InvalidFormatException { - PackagePartName partNameToValid = PackagingURIHelper - .createPartName("/word/media/image1.gif"); - - OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); - // Base part - PackagePartName nameBase = PackagingURIHelper - .createPartName("/word/document.xml"); - PackagePart partBase = pkg.createPart(nameBase, ContentTypes.XML); - // Relative part name - PackagePartName relativeName = PackagingURIHelper.createPartName( - "media/image1.gif", partBase); - assertEquals(partNameToValid, relativeName, "The part name must be equal to " + partNameToValid.getName()); - pkg.revert(); - } - - /** - * Test createPartName(URI, y) - */ - @Test - void testCreatePartNameRelativeURI() throws Exception { - PackagePartName partNameToValid = PackagingURIHelper - .createPartName("/word/media/image1.gif"); - - OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); - // Base part - PackagePartName nameBase = PackagingURIHelper - .createPartName("/word/document.xml"); - PackagePart partBase = pkg.createPart(nameBase, ContentTypes.XML); - // Relative part name - PackagePartName relativeName = PackagingURIHelper.createPartName( - new URI("media/image1.gif"), partBase); - assertEquals(partNameToValid, relativeName, "The part name must be equal to " + partNameToValid.getName()); - pkg.revert(); - } - - @Test - void testCreateURIFromString() throws Exception { - String[] href = { - "..\\\\\\cygwin\\home\\yegor\\.vim\\filetype.vim", - "..\\Program%20Files\\AGEIA%20Technologies\\v2.3.3\\NxCooking.dll", - "file:///D:\\seva\\1981\\r810102ns.mp3", - "..\\cygwin\\home\\yegor\\dinom\\%5baccess%5d.2010-10-26.log", - "#'Instructions (Text)'!B21", - "#'性'!B21", - "javascript://", - "#ctl||rId16||cmdAddAction||_x0000_i1029" - }; - - for(String s : href){ - URI uri = PackagingURIHelper.toURI(s); - assertNotNull(uri); - } - } - - @Test - void test53734() throws Exception { - URI uri = PackagingURIHelper.toURI("javascript://"); - // POI appends a trailing slash tpo avoid "Expected authority at index 13: javascript://" - // https://issues.apache.org/bugzilla/show_bug.cgi?id=53734 - assertEquals("javascript:///", uri.toASCIIString()); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java deleted file mode 100644 index d80c88ae12..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java +++ /dev/null @@ -1,442 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream; -import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive; -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.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.net.URI; -import java.util.regex.Pattern; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.junit.jupiter.api.Test; - - -class TestRelationships { - private static final String HYPERLINK_REL_TYPE = - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; - private static final String COMMENTS_REL_TYPE = - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"; - private static final String SHEET_WITH_COMMENTS = - "/xl/worksheets/sheet1.xml"; - - private static final Logger LOG = LogManager.getLogger(TestPackageCoreProperties.class); - - /** - * Test relationships are correctly loaded. This at the moment fails (as of r499) - * whenever a document is loaded before its correspondig .rels file has been found. - * The code in this case assumes there are no relationships defined, but it should - * really look also for not yet loaded parts. - */ - @Test - void testLoadRelationships() throws Exception { - InputStream is = openSampleStream("sample.xlsx"); - try (OPCPackage pkg = OPCPackage.open(is)) { - LOG.atDebug().log("1: {}", pkg); - PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); - PackageRelationship coreDocRelationship = rels.getRelationship(0); - PackagePart corePart = pkg.getPart(coreDocRelationship); - String[] relIds = {"rId1", "rId2", "rId3"}; - for (String relId : relIds) { - PackageRelationship rel = corePart.getRelationship(relId); - assertNotNull(rel); - PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI()); - PackagePart sheetPart = pkg.getPart(relName); - assertEquals(1, sheetPart.getRelationships().size(), "Number of relationships1 for " + sheetPart.getPartName()); - } - } - } - - /** - * Checks that we can fetch a collection of relations by - * type, then grab from within there by id - */ - @Test - void testFetchFromCollection() throws Exception { - InputStream is = openSampleStream("ExcelWithHyperlinks.xlsx"); - try (OPCPackage pkg = OPCPackage.open(is)) { - PackagePart sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - assertNotNull(sheet); - - assertTrue(sheet.hasRelationships()); - assertEquals(6, sheet.getRelationships().size()); - - // Should have three hyperlinks, and one comment - PackageRelationshipCollection hyperlinks = - sheet.getRelationshipsByType(HYPERLINK_REL_TYPE); - PackageRelationshipCollection comments = - sheet.getRelationshipsByType(COMMENTS_REL_TYPE); - assertEquals(3, hyperlinks.size()); - assertEquals(1, comments.size()); - - // Check we can get bits out by id - // Hyperlinks are rId1, rId2 and rId3 - // Comment is rId6 - assertNotNull(hyperlinks.getRelationshipByID("rId1")); - assertNotNull(hyperlinks.getRelationshipByID("rId2")); - assertNotNull(hyperlinks.getRelationshipByID("rId3")); - assertNull(hyperlinks.getRelationshipByID("rId6")); - - assertNull(comments.getRelationshipByID("rId1")); - assertNull(comments.getRelationshipByID("rId2")); - assertNull(comments.getRelationshipByID("rId3")); - assertNotNull(comments.getRelationshipByID("rId6")); - - assertNotNull(sheet.getRelationship("rId1")); - assertNotNull(sheet.getRelationship("rId2")); - assertNotNull(sheet.getRelationship("rId3")); - assertNotNull(sheet.getRelationship("rId6")); - } - } - - /** - * Excel uses relations on sheets to store the details of - * external hyperlinks. Check we can load these ok. - */ - @Test - void testLoadExcelHyperlinkRelations() throws Exception { - InputStream is = openSampleStream("ExcelWithHyperlinks.xlsx"); - try (OPCPackage pkg = OPCPackage.open(is)) { - PackagePart sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - assertNotNull(sheet); - - // rId1 is url - PackageRelationship url = sheet.getRelationship("rId1"); - assertNotNull(url); - assertEquals("rId1", url.getId()); - assertEquals("/xl/worksheets/sheet1.xml", url.getSourceURI().toString()); - assertEquals("http://poi.apache.org/", url.getTargetURI().toString()); - - // rId2 is file - PackageRelationship file = sheet.getRelationship("rId2"); - assertNotNull(file); - assertEquals("rId2", file.getId()); - assertEquals("/xl/worksheets/sheet1.xml", file.getSourceURI().toString()); - assertEquals("WithVariousData.xlsx", file.getTargetURI().toString()); - - // rId3 is mailto - PackageRelationship mailto = sheet.getRelationship("rId3"); - assertNotNull(mailto); - assertEquals("rId3", mailto.getId()); - assertEquals("/xl/worksheets/sheet1.xml", mailto.getSourceURI().toString()); - assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", mailto.getTargetURI().toString()); - } - } - - /* - * Excel uses relations on sheets to store the details of - * external hyperlinks. Check we can create these OK, - * then still read them later - */ - @Test - void testCreateExcelHyperlinkRelations() throws Exception { - String filepath = OpenXML4JTestDataSamples.getSampleFileName("ExcelWithHyperlinks.xlsx"); - OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE); - PackagePart sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - assertNotNull(sheet); - - assertEquals(3, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); - - // Add three new ones - PackageRelationship openxml4j = - sheet.addExternalRelationship("http://www.openxml4j.org/", HYPERLINK_REL_TYPE); - PackageRelationship sf = - sheet.addExternalRelationship("http://openxml4j.sf.net/", HYPERLINK_REL_TYPE); - PackageRelationship file = - sheet.addExternalRelationship("MyDocument.docx", HYPERLINK_REL_TYPE); - - // Check they were added properly - assertNotNull(openxml4j); - assertNotNull(sf); - assertNotNull(file); - - assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); - - assertEquals("http://www.openxml4j.org/", openxml4j.getTargetURI().toString()); - assertEquals("/xl/worksheets/sheet1.xml", openxml4j.getSourceURI().toString()); - assertEquals(HYPERLINK_REL_TYPE, openxml4j.getRelationshipType()); - - assertEquals("http://openxml4j.sf.net/", sf.getTargetURI().toString()); - assertEquals("/xl/worksheets/sheet1.xml", sf.getSourceURI().toString()); - assertEquals(HYPERLINK_REL_TYPE, sf.getRelationshipType()); - - assertEquals("MyDocument.docx", file.getTargetURI().toString()); - assertEquals("/xl/worksheets/sheet1.xml", file.getSourceURI().toString()); - assertEquals(HYPERLINK_REL_TYPE, file.getRelationshipType()); - - // Will get ids 7, 8 and 9, as we already have 1-6 - assertEquals("rId7", openxml4j.getId()); - assertEquals("rId8", sf.getId()); - assertEquals("rId9", file.getId()); - - - // Write out and re-load - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - pkg.save(baos); - - // use revert to not re-write the input file - pkg.revert(); - - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); - - // Check again - sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - - assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); - - assertEquals("http://poi.apache.org/", - sheet.getRelationship("rId1").getTargetURI().toString()); - assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", - sheet.getRelationship("rId3").getTargetURI().toString()); - - assertEquals("http://www.openxml4j.org/", - sheet.getRelationship("rId7").getTargetURI().toString()); - assertEquals("http://openxml4j.sf.net/", - sheet.getRelationship("rId8").getTargetURI().toString()); - assertEquals("MyDocument.docx", - sheet.getRelationship("rId9").getTargetURI().toString()); - } - - @Test - void testCreateRelationsFromScratch() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - OPCPackage pkg = OPCPackage.create(baos); - - PackagePart partA = - pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain"); - PackagePart partB = - pkg.createPart(PackagingURIHelper.createPartName("/partB"), "image/png"); - assertNotNull(partA); - assertNotNull(partB); - - // Internal - partA.addRelationship(partB.getPartName(), TargetMode.INTERNAL, "http://example/Rel"); - - // External - partA.addExternalRelationship("http://poi.apache.org/", "http://example/poi"); - partB.addExternalRelationship("http://poi.apache.org/ss/", "http://example/poi/ss"); - - // Check as expected currently - assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/", - partA.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/ss/", - partB.getRelationship("rId1").getTargetURI().toString()); - - - // Save, and re-load - pkg.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); - - partA = pkg.getPart(PackagingURIHelper.createPartName("/partA")); - partB = pkg.getPart(PackagingURIHelper.createPartName("/partB")); - - - // Check the relations - assertEquals(2, partA.getRelationships().size()); - assertEquals(1, partB.getRelationships().size()); - - assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/", - partA.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/ss/", - partB.getRelationship("rId1").getTargetURI().toString()); - // Check core too - PackageRelationship relationship = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_PROPERTIES).getRelationship(0); - assertNotNull(relationship); - assertEquals("/docProps/core.xml", relationship.getTargetURI().toString()); - - // Add some more - partB.addExternalRelationship("http://poi.apache.org/new", "http://example/poi/new"); - partB.addExternalRelationship("http://poi.apache.org/alt", "http://example/poi/alt"); - - // Check the relations - assertEquals(2, partA.getRelationships().size()); - assertEquals(3, partB.getRelationships().size()); - - assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/", - partA.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/ss/", - partB.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/new", - partB.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/alt", - partB.getRelationship("rId3").getTargetURI().toString()); - } - - @Test - void testTargetWithSpecialChars() throws Exception{ - OPCPackage pkg; - - String filepath = OpenXML4JTestDataSamples.getSampleFileName("50154.xlsx"); - pkg = OPCPackage.open(filepath); - assert_50154(pkg); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - pkg.save(baos); - - // use revert to not re-write the input file - pkg.revert(); - - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); - - assert_50154(pkg); - } - - private void assert_50154(OPCPackage pkg) throws Exception { - URI drawingURI = new URI("/xl/drawings/drawing1.xml"); - PackagePart drawingPart = pkg.getPart(PackagingURIHelper.createPartName(drawingURI)); - PackageRelationshipCollection drawingRels = drawingPart.getRelationships(); - - assertEquals(6, drawingRels.size()); - - // expected one image - assertEquals(1, drawingPart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image").size()); - // and three hyperlinks - assertEquals(5, drawingPart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink").size()); - - PackageRelationship rId1 = drawingPart.getRelationship("rId1"); - URI parent = drawingPart.getPartName().getURI(); - URI rel1 = parent.relativize(rId1.getTargetURI()); - URI rel11 = PackagingURIHelper.relativizeURI(drawingPart.getPartName().getURI(), rId1.getTargetURI()); - assertEquals("'Another Sheet'!A1", rel1.getFragment()); - assertEquals("'Another Sheet'!A1", rel11.getFragment()); - - PackageRelationship rId2 = drawingPart.getRelationship("rId2"); - URI rel2 = PackagingURIHelper.relativizeURI(drawingPart.getPartName().getURI(), rId2.getTargetURI()); - assertEquals("../media/image1.png", rel2.getPath()); - - PackageRelationship rId3 = drawingPart.getRelationship("rId3"); - URI rel3 = parent.relativize(rId3.getTargetURI()); - assertEquals("ThirdSheet!A1", rel3.getFragment()); - - PackageRelationship rId4 = drawingPart.getRelationship("rId4"); - URI rel4 = parent.relativize(rId4.getTargetURI()); - assertEquals("'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A1", rel4.getFragment()); - - PackageRelationship rId5 = drawingPart.getRelationship("rId5"); - URI rel5 = parent.relativize(rId5.getTargetURI()); - // back slashed have been replaced with forward - assertEquals("file:///D:/chan-chan.mp3", rel5.toString()); - - PackageRelationship rId6 = drawingPart.getRelationship("rId6"); - URI rel6 = parent.relativize(rId6.getTargetURI()); - assertEquals("../../../../../../../cygwin/home/yegor/dinom/&&&[access].2010-10-26.log", rel6.getPath()); - assertEquals("'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A5", rel6.getFragment()); - } - - @Test - void testSelfRelations_bug51187() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PackageRelationship rel1; - try (OPCPackage pkg = OPCPackage.create(baos)) { - - PackagePart partA = - pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain"); - assertNotNull(partA); - - // reference itself - rel1 = partA.addRelationship(partA.getPartName(), TargetMode.INTERNAL, "partA"); - - - // Save, and re-load - } - - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - try (OPCPackage pkg = OPCPackage.open(bais)) { - PackagePart partA = pkg.getPart(PackagingURIHelper.createPartName("/partA")); - - - // Check the relations - assertEquals(1, partA.getRelationships().size()); - - PackageRelationship rel2 = partA.getRelationships().getRelationship(0); - - assertNotNull(rel2); - assertEquals(rel1.getRelationshipType(), rel2.getRelationshipType()); - assertEquals(rel1.getId(), rel2.getId()); - assertEquals(rel1.getSourceURI(), rel2.getSourceURI()); - assertEquals(rel1.getTargetURI(), rel2.getTargetURI()); - assertEquals(rel1.getTargetMode(), rel2.getTargetMode()); - } - } - - @Test - void testTrailingSpacesInURI_53282() throws Exception { - try (InputStream is = openSampleStream("53282.xlsx"); - OPCPackage pkg1 = OPCPackage.open(is)) { - - PackageRelationshipCollection sheetRels = pkg1.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships(); - assertEquals(3, sheetRels.size()); - PackageRelationship rId1 = sheetRels.getRelationshipByID("rId1"); - assertEquals(TargetMode.EXTERNAL, rId1.getTargetMode()); - URI targetUri = rId1.getTargetURI(); - assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString()); - assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart()); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - pkg1.save(out); - out.close(); - - try (OPCPackage pkg2 = OPCPackage.open(new ByteArrayInputStream(out.toByteArray()))) { - sheetRels = pkg2.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships(); - assertEquals(3, sheetRels.size()); - rId1 = sheetRels.getRelationshipByID("rId1"); - assertEquals(TargetMode.EXTERNAL, rId1.getTargetMode()); - targetUri = rId1.getTargetURI(); - assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString()); - assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart()); - } - } - } - - @Test - void testEntitiesInRels_56164() throws Exception { - try (InputStream is = openSampleStream("PackageRelsHasEntities.ooxml"); - OPCPackage p = OPCPackage.open(is)) { - - // Should have 3 root relationships - boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false; - for (PackageRelationship pr : p.getRelationships()) { - foundDocRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT); - foundCorePropRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES); - foundExtPropRel |= pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES); - } - assertEquals(isOldXercesActive(), foundDocRel, "Core Doc Relationship not found in " + p.getRelationships()); - assertEquals(isOldXercesActive(), foundCorePropRel, "Core Props Relationship not found in " + p.getRelationships()); - assertEquals(isOldXercesActive(), foundExtPropRel, "Ext Props Relationship not found in " + p.getRelationships()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java deleted file mode 100644 index fcc6e3cff8..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java +++ /dev/null @@ -1,163 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Set; -import java.util.TreeMap; - -import org.apache.commons.compress.archivers.ArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; -import org.apache.poi.util.IOUtils; -import org.junit.jupiter.api.Assertions; -import org.xmlunit.builder.DiffBuilder; -import org.xmlunit.builder.Input; -import org.xmlunit.diff.Comparison; -import org.xmlunit.diff.ComparisonResult; -import org.xmlunit.diff.DefaultNodeMatcher; -import org.xmlunit.diff.Diff; -import org.xmlunit.diff.DifferenceEvaluator; -import org.xmlunit.diff.ElementSelectors; - -/** - * Compare the contents of 2 zip files. - */ -public final class ZipFileAssert { - private ZipFileAssert() { - } - - private static void equals( - TreeMap<String, ByteArrayOutputStream> file1, - TreeMap<String, ByteArrayOutputStream> file2) { - Set<String> listFile1 = file1.keySet(); - Assertions.assertEquals(listFile1.size(), file2.keySet().size(), "not the same number of files in zip:"); - - for (String fileName : listFile1) { - // extract the contents for both - ByteArrayOutputStream contain1 = file1.get(fileName); - ByteArrayOutputStream contain2 = file2.get(fileName); - - assertNotNull(contain2, fileName + " not found in 2nd zip"); - // no need to check for contain1. The key come from it - - if (fileName.matches(".*\\.(xml|rels)$")) { - // we have a xml file - final Diff diff = DiffBuilder. - compare(Input.fromByteArray(contain1.toByteArray())). - withTest(Input.fromByteArray(contain2.toByteArray())). - ignoreWhitespace(). - checkForSimilar(). - withDifferenceEvaluator(new IgnoreXMLDeclEvaluator()). - withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndAllAttributes, ElementSelectors.byNameAndText)). - build(); - assertFalse(diff.hasDifferences(), fileName+": "+diff.toString()); - } else { - // not xml, may be an image or other binary format - Assertions.assertEquals(contain1.size(), contain2.size(), fileName + " does not have the same size in both zip:"); - assertArrayEquals(contain1.toByteArray(), contain2.toByteArray(), "contents differ"); - } - } - } - - private static TreeMap<String, ByteArrayOutputStream> decompress( - File filename) throws IOException { - // store the zip content in memory - // let s assume it is not Go ;-) - TreeMap<String, ByteArrayOutputStream> zipContent = new TreeMap<>(); - - try ( - /* Open file to decompress */ - FileInputStream file_decompress = new FileInputStream(filename); - - /* Create a buffer for the decompressed files */ - BufferedInputStream buffi = new BufferedInputStream(file_decompress); - - /* Open the file with the buffer */ - ZipArchiveInputStream zis = new ZipArchiveInputStream(buffi) - ) { - - /* Processing entries of the zip file */ - ArchiveEntry entree; - while ((entree = zis.getNextEntry()) != null) { - - /* Create a array for the current entry */ - ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); - IOUtils.copy(zis, byteArray); - zipContent.put(entree.getName(), byteArray); - } - - } - - return zipContent; - } - - /** - * Asserts that two files are equal. Throws an <tt>AssertionFailedError</tt> - * if they are not. - * <p> - * - */ - public static void assertEquals(File expected, File actual) { - assertNotNull(expected); - assertNotNull(actual); - - assertTrue(expected.exists(), "File does not exist [" + expected.getAbsolutePath() + "]"); - assertTrue(actual.exists(), "File does not exist [" + actual.getAbsolutePath() + "]"); - assertTrue(expected.canRead(), "Expected file not readable"); - assertTrue(actual.canRead(), "Actual file not readable"); - - assertDoesNotThrow(() -> equals(decompress(expected), decompress(actual))); - } - - private static class IgnoreXMLDeclEvaluator implements DifferenceEvaluator { - @Override - public ComparisonResult evaluate(final Comparison comparison, final ComparisonResult outcome) { - if (outcome != ComparisonResult.EQUAL) { - // only evaluate differences - switch (comparison.getType()) { - case CHILD_NODELIST_SEQUENCE: - case XML_STANDALONE: - case NAMESPACE_PREFIX: - return ComparisonResult.SIMILAR; - case TEXT_VALUE: - switch (comparison.getControlDetails().getTarget().getParentNode().getNodeName()) { - case "dcterms:created": - case "dc:creator": - return ComparisonResult.SIMILAR; - } - break; - default: - break; - } - } - - return outcome; - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java deleted file mode 100644 index 3ebd4041a3..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java +++ /dev/null @@ -1,300 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.compliance; - -import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openComplianceSampleStream; -import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -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.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.Test; - -/** - * Test core properties Open Packaging Convention compliance. - * - * M4.1: The format designer shall specify and the format producer shall create - * at most one core properties relationship for a package. A format consumer - * shall consider more than one core properties relationship for a package to be - * an error. If present, the relationship shall target the Core Properties part. - * (POI relaxes this on reading, as Office sometimes breaks this) - * - * M4.2: The format designer shall not specify and the format producer shall not - * create Core Properties that use the Markup Compatibility namespace as defined - * in Annex F, "Standard Namespaces and Content Types". A format consumer shall - * consider the use of the Markup Compatibility namespace to be an error. - * - * M4.3: Producers shall not create a document element that contains refinements - * to the Dublin Core elements, except for the two specified in the schema: - * <dcterms:created> and <dcterms:modified> Consumers shall consider a document - * element that violates this constraint to be an error. - * - * M4.4: Producers shall not create a document element that contains the - * xml:lang attribute. Consumers shall consider a document element that violates - * this constraint to be an error. - * - * M4.5: Producers shall not create a document element that contains the - * xsi:type attribute, except for a <dcterms:created> or <dcterms:modified> - * element where the xsi:type attribute shall be present and shall hold the - * value dcterms:W3CDTF, where dcterms is the namespace prefix of the Dublin - * Core namespace. Consumers shall consider a document element that violates - * this constraint to be an error. - */ -public final class TestOPCComplianceCoreProperties { - - @Test - void testCorePropertiesPart() throws IOException { - try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) { - assertDoesNotThrow(() -> OPCPackage.open(is).close()); - } - } - - private static String extractInvalidFormatMessage(String sampleNameSuffix) throws IOException { - try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix)) { - InvalidFormatException e = assertThrows(InvalidFormatException.class, - () -> OPCPackage.open(is).revert(), "expected OPC compliance exception was not thrown"); - return e.getMessage(); - } - } - - /** - * Test M4.1 rule. - */ - @Test - void testOnlyOneCorePropertiesPart() throws Exception { - // We have relaxed this check, so we can read the file anyway - assertDoesNotThrow(() -> { - try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx"); - OPCPackage pkg = OPCPackage.open(is)) { - assertNotNull(pkg); - } - }, "M4.1 should be being relaxed"); - - // We will use the first core properties, and ignore the others - - try (InputStream is = openSampleStream("MultipleCoreProperties.docx"); - OPCPackage pkg = OPCPackage.open(is)) { - - // We can see 2 by type - assertEquals(2, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - // But only the first one by relationship - assertEquals(1, pkg.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size()); - // It should be core.xml not the older core1.xml - assertEquals( - "/docProps/core.xml", - pkg.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).get(0).getPartName().toString() - ); - } - } - - private static URI createURI(String text) { - try { - return new URI(text); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - /** - * Test M4.1 rule. - */ - @Test - void testOnlyOneCorePropertiesPart_AddRelationship() throws IOException, InvalidFormatException { - try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) { - OPCPackage pkg = OPCPackage.open(is); - URI partUri = createURI("/docProps/core2.xml"); - InvalidOperationException e = assertThrows(InvalidOperationException.class, () -> - pkg.addRelationship(PackagingURIHelper.createPartName(partUri), TargetMode.INTERNAL, PackageRelationshipTypes.CORE_PROPERTIES), - "expected OPC compliance exception was not thrown" - ); - assertEquals("OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead.", e.getMessage()); - pkg.revert(); - } - } - - /** - * Test M4.1 rule. - */ - @Test - void testOnlyOneCorePropertiesPart_AddPart() throws InvalidFormatException, IOException { - String sampleFileName = "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx"; - try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) { - - URI partUri = createURI("/docProps/core2.xml"); - InvalidOperationException e = assertThrows(InvalidOperationException.class, () -> - pkg.createPart(PackagingURIHelper.createPartName(partUri), ContentTypes.CORE_PROPERTIES_PART), - "expected OPC compliance exception was not thrown"); - assertEquals("OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !", e.getMessage()); - pkg.revert(); - } - } - - /** - * Test M4.2 rule. - */ - @Test - void testDoNotUseCompatibilityMarkup() throws IOException { - String msg = extractInvalidFormatMessage("DoNotUseCompatibilityMarkupFAIL.docx"); - assertEquals("OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.", msg); - } - - /** - * Test M4.3 rule. - */ - @Test - void testDCTermsNamespaceLimitedUse() throws IOException { - String msg = extractInvalidFormatMessage("DCTermsNamespaceLimitedUseFAIL.docx"); - assertEquals("OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.", msg); - } - - /** - * Test M4.4 rule. - */ - @Test - void testUnauthorizedXMLLangAttribute() throws IOException { - String msg = extractInvalidFormatMessage("UnauthorizedXMLLangAttributeFAIL.docx"); - assertEquals("OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.", msg); - } - - /** - * Test M4.5 rule. - */ - @Test - void testLimitedXSITypeAttribute_NotPresent() throws IOException { - String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_NotPresentFAIL.docx"); - assertEquals("The element 'created' must have the 'xsi:type' attribute present !", msg); - } - - /** - * Test M4.5 rule. - */ - @Test - void testLimitedXSITypeAttribute_PresentWithUnauthorizedValue() throws IOException { - String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx"); - assertEquals("The element 'modified' must have the 'xsi:type' attribute with the value 'dcterms:W3CDTF', but had 'W3CDTF' !", msg); - } - - /** - * Document with no core properties - testing at the OPC level, - * saving into a new stream - */ - @Test - void testNoCoreProperties_saveNew() throws Exception { - String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx"; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) { - // Verify it has empty properties - assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - - // Save and re-load - pkg.save(baos); - pkg.revert(); - } - - try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) { - // An Empty Properties part has been added in the save/load - assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - } - - // Open a new copy of it - try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) { - // Save and re-load, without having touched the properties yet - baos.reset(); - pkg.save(baos); - pkg.revert(); - } - - try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) { - // Check that this too added empty properties without error - assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - } - } - - /** - * Document with no core properties - testing at the OPC level, - * from a temp-file, saving in-place - */ - @Test - void testNoCoreProperties_saveInPlace() throws Exception { - String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx"; - - // Copy this into a temp file, so we can play with it - File tmp = TempFile.createTempFile("poi-test", ".opc"); - try (FileOutputStream out = new FileOutputStream(tmp); - InputStream in = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(sampleFileName)) { - IOUtils.copy(in, out); - } - - // Open it from that temp file - try (OPCPackage pkg = OPCPackage.open(tmp)) { - - // Empty properties - assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - - // Save and close - } - - // Re-open and check - try (OPCPackage pkg = OPCPackage.open(tmp)) { - // An Empty Properties part has been added in the save/load - assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - - // Finish and tidy - pkg.revert(); - } - assertTrue(tmp.delete()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java deleted file mode 100644 index e81605fc26..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.compliance; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.IOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Test Open Packaging Convention package model compliance. - * - * M1.11 : A package implementer shall neither create nor recognize a part with - * a part name derived from another part name by appending segments to it. - */ -class TestOPCCompliancePackageModel { - - private static File TESTFILE; - - @BeforeAll - public static void setup() throws IOException { - TESTFILE = TempFile.createTempFile("TODELETEIFEXIST", ".docx"); - } - - @BeforeEach - void tearDown() { - if (TESTFILE.exists()) { - assertTrue(TESTFILE.delete()); - } - } - - /** - * A package implementer shall neither create nor recognize a part with a - * part name derived from another part name by appending segments to it. - * [M1.11] - */ - @Test - void testPartNameDerivationAdditionFailure() throws InvalidFormatException, IOException { - try (OPCPackage pkg = OPCPackage.create(TESTFILE)) { - PackagePartName name = PackagingURIHelper.createPartName("/word/document.xml"); - PackagePartName nameDerived = PackagingURIHelper.createPartName("/word/document.xml/image1.gif"); - pkg.createPart(name, ContentTypes.XML); - - assertThrows(InvalidOperationException.class, () -> pkg.createPart(nameDerived, ContentTypes.EXTENSION_GIF), - "A package implementer shall neither create nor recognize a part with a part name derived from another " + - "part name by appending segments to it. [M1.11]"); - pkg.revert(); - } - } - - /** - * A package implementer shall neither create nor recognize a part with a - * part name derived from another part name by appending segments to it. - * [M1.11] - */ - @Test - void testPartNameDerivationReadingFailure() { - String filename = "OPCCompliance_DerivedPartNameFAIL.docx"; - assertThrows(InvalidFormatException.class, () -> - OPCPackage.open(POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename)), - "A package implementer shall neither create nor recognize a part with a part name derived from another" + - " part name by appending segments to it. [M1.11]" - ); - } - - /** - * Rule M1.12 : Packages shall not contain equivalent part names and package - * implementers shall neither create nor recognize packages with equivalent - * part names. - */ - @Test - void testAddPackageAlreadyAddFailure() throws Exception { - try (OPCPackage pkg = OPCPackage.create(TESTFILE)) { - PackagePartName name1 = PackagingURIHelper.createPartName("/word/document.xml"); - PackagePartName name2 = PackagingURIHelper.createPartName("/word/document.xml"); - - pkg.createPart(name1, ContentTypes.XML); - assertThrows(PartAlreadyExistsException.class, () -> pkg.createPart(name2, ContentTypes.XML), - "Packages shall not contain equivalent part names and package implementers shall neither create nor " + - "recognize packages with equivalent part names. [M1.12]" - ); - pkg.revert(); - } - } - - /** - * Rule M1.12 : Packages shall not contain equivalent part names and package - * implementers shall neither create nor recognize packages with equivalent - * part names. - */ - @Test - void testAddPackageAlreadyAddFailure2() throws Exception { - try (OPCPackage pkg = OPCPackage.create(TESTFILE)) { - PackagePartName partName = PackagingURIHelper.createPartName("/word/document.xml"); - pkg.createPart(partName, ContentTypes.XML); - assertThrows(InvalidOperationException.class, () -> pkg.createPart(partName, ContentTypes.XML), - "Packages shall not contain equivalent part names and package implementers shall neither create nor " + - "recognize packages with equivalent part names. [M1.12]" - ); - pkg.revert(); - } - } - - /** - * Try to add a relationship to a relationship part. - * <p> - * Check rule M1.25: The Relationships part shall not have relationships to - * any other part. Package implementers shall enforce this requirement upon - * the attempt to create such a relationship and shall treat any such - * relationship as invalid. - */ - @Test - void testAddRelationshipRelationshipsPartFailure() throws IOException, InvalidFormatException { - try (OPCPackage pkg = OPCPackage.create(TESTFILE)) { - PackagePartName name1 = PackagingURIHelper.createPartName("/test/_rels/document.xml.rels"); - - assertThrows(InvalidOperationException.class, - () -> pkg.addRelationship(name1, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT), - "The Relationships part shall not have relationships to any other part [M1.25]" - ); - pkg.revert(); - } - } - - @Test - void testToString() throws IOException { - try (OPCPackage pkg = OPCPackage.create(TESTFILE)) { - assertEquals("OPCPackage{" + - "packageAccess=READ_WRITE, " + - "relationships=null, " + - "packageProperties=Name: /docProps/core.xml - Content Type: application/vnd.openxmlformats-package.core-properties+xml, " + - "isDirty=false}", pkg.toString()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java deleted file mode 100644 index edfe0fea3e..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java +++ /dev/null @@ -1,223 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.compliance; - -import static org.apache.poi.openxml4j.opc.PackagingURIHelper.createPartName; -import static org.apache.poi.openxml4j.opc.PackagingURIHelper.isValidPartName; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.net.URI; -import java.net.URISyntaxException; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.junit.jupiter.api.Test; - -/** - * Test part name Open Packaging Convention compliance. - * - * (Open Packaging Convention 8.1.1 Part names) : - * - * The part name grammar is defined as follows: - * - * part_name = 1*( "/" segment ) - * - * segment = 1*( pchar ) - * - * pchar is defined in RFC 3986. - * - * The part name grammar implies the following constraints. The package - * implementer shall neither create any part that violates these constraints nor - * retrieve any data from a package as a part if the purported part name - * violates these constraints. - * - * A part name shall not be empty. [M1.1] - * - * A part name shall not have empty segments. [M1.3] - * - * A part name shall start with a forward slash ("/") character. [M1.4] - * - * A part name shall not have a forward slash as the last character. [M1.5] - * - * A segment shall not hold any characters other than pchar characters. [M1.6] - * - * Part segments have the following additional constraints. The package - * implementer shall neither create any part with a part name comprised of a - * segment that violates these constraints nor retrieve any data from a package - * as a part if the purported part name contains a segment that violates these - * constraints. - * - * A segment shall not contain percent-encoded forward slash ("/"), or backward - * slash ("\") characters. [M1.7] - * - * A segment shall not contain percent-encoded unreserved characters. [M1.8] - * - * A segment shall not end with a dot (".") character. [M1.9] - * - * A segment shall include at least one non-dot character. [M1.10] - * - * A package implementer shall neither create nor recognize a part with a part - * name derived from another part name by appending segments to it. [M1.11] - * - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. [M1.12] - * - * @author Julien Chable - */ -public final class TestOPCCompliancePartName { - - /** - * Test some common invalid names. - * - * A segment shall not contain percent-encoded unreserved characters. [M1.8] - */ - @Test - void testInvalidPartNames() { - String[] invalidNames = { "/", "/xml./doc.xml", "[Content_Types].xml", "//xml/." }; - for (String s : invalidNames) { - URI uri = null; - try { - uri = new URI(s); - } catch (URISyntaxException e) { - assertEquals("[Content_Types].xml", s); - continue; - } - assertFalse(isValidPartName(uri), "This part name SHOULD NOT be valid: " + s); - } - } - - /** - * Test some common valid names. - */ - @Test - void testValidPartNames() throws URISyntaxException { - String[] validNames = { "/xml/item1.xml", "/document.xml", "/a/%D1%86.xml" }; - for (String s : validNames) { - assertTrue(isValidPartName(new URI(s)), "This part name SHOULD be valid: " + s); - } - } - - /** - * A part name shall not be empty. [M1.1] - */ - @Test - void testEmptyPartNameFailure() { - assertThrows(InvalidFormatException.class, () -> createPartName(new URI("")), - "A part name shall not be empty. [M1.1]"); - } - - /** - * A part name shall not have empty segments. [M1.3] - * - * A segment shall not end with a dot ('.') character. [M1.9] - * - * A segment shall include at least one non-dot character. [M1.10] - */ - @Test - void testPartNameWithInvalidSegmentsFailure() throws URISyntaxException { - String[] invalidNames = { "//document.xml", "//word/document.xml", - "/word//document.rels", "/word//rels//document.rels", - "/xml./doc.xml", "/document.", "/./document.xml", - "/word/./doc.rels", "/%2F/document.xml" }; - for (String s : invalidNames) { - assertFalse(isValidPartName(new URI(s)), "A part name shall not have empty segments. [M1.3]"); - } - } - - /** - * A segment shall not hold any characters other than ipchar (RFC 3987) characters. - * [M1.6]. - */ - @Test - void testPartNameWithNonPCharCharacters() throws URISyntaxException { - String[] validNames = { "/doc&.xml" }; - for (String s : validNames) { - assertTrue(isValidPartName(new URI(s)), - "A segment shall not contain non pchar characters [M1.6] : " + s); - } - } - - /** - * A segment shall not contain percent-encoded unreserved characters [M1.8]. - */ - @Test - void testPartNameWithUnreservedEncodedCharactersFailure() throws URISyntaxException { - String[] invalidNames = { "/a/docum%65nt.xml" }; - for (String s : invalidNames) { - assertFalse(isValidPartName(new URI(s)), "A segment shall not contain percent-encoded unreserved characters [M1.8] : " + s); - } - } - - /** - * A part name shall start with a forward slash ('/') character. [M1.4] - */ - @Test - void testPartNameStartsWithAForwardSlashFailure() { - assertThrows(InvalidFormatException.class, () -> createPartName(new URI("document.xml")), - "A part name shall start with a forward slash ('/') character. [M1.4]"); - } - - /** - * A part name shall not have a forward slash as the last character. [M1.5] - */ - @Test - void testPartNameEndsWithAForwardSlashFailure() { - assertThrows(InvalidFormatException.class, () -> createPartName(new URI("/document.xml/")), - "A part name shall not have a forward slash as the last character. [M1.5]"); - } - - /** - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. [M1.12] - */ - @Test - void testPartNameComparaison() throws Exception { - String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" }; - String[] partName2 = { "/WORD/DocUment.XML", "/docProps/core.xml", "/rels/.rels" }; - for (int i = 0; i < partName1.length || i < partName2.length; ++i) { - PackagePartName p1 = createPartName(partName1[i]); - PackagePartName p2 = createPartName(partName2[i]); - assertEquals(p1, p2); - assertEquals(0, p1.compareTo(p2)); - assertEquals(p1.hashCode(), p2.hashCode()); - } - } - - /** - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. [M1.12]. - * - * All the comparisons MUST FAIL ! - */ - @Test - void testPartNameComparaisonFailure() throws Exception { - String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" }; - String[] partName2 = { "/WORD/DocUment.XML2", "/docProp/core.xml", "/rels/rels" }; - for (int i = 0; i < partName1.length || i < partName2.length; ++i) { - PackagePartName p1 = createPartName(partName1[i]); - PackagePartName p2 = createPartName(partName2[i]); - assertNotEquals(p1, p2); - assertNotEquals(0, p1.compareTo(p2)); - assertNotEquals(p1.hashCode(), p2.hashCode()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java deleted file mode 100644 index aab917ec63..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java +++ /dev/null @@ -1,196 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook; -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.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.ooxml.util.POIXMLUnits; -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -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.Drawing; -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.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFPicture; -import org.apache.poi.xssf.usermodel.XSSFPictureData; -import org.apache.poi.xssf.usermodel.XSSFShape; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor; - -public final class TestContentTypeManager { - - /** - * Test the properties part content parsing. - */ - @Test - void testContentType() throws Exception { - String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); - - // Retrieves core properties part - try (OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ)) { - PackageRelationshipCollection rels = p.getRelationshipsByType(PackageRelationshipTypes.CORE_PROPERTIES); - PackageRelationship corePropertiesRelationship = rels.getRelationship(0); - PackagePart coreDocument = p.getPart(corePropertiesRelationship); - - assertEquals("application/vnd.openxmlformats-package.core-properties+xml", coreDocument.getContentType()); - } - } - - /** - * Test the addition of several default and override content types. - */ - @Test - void testContentTypeAddition() throws Exception { - ContentTypeManager ctm = new ZipContentTypeManager(null, null); - - PackagePartName name1 = PackagingURIHelper.createPartName("/foo/foo.XML"); - PackagePartName name2 = PackagingURIHelper.createPartName("/foo/foo2.xml"); - PackagePartName name3 = PackagingURIHelper.createPartName("/foo/doc.rels"); - PackagePartName name4 = PackagingURIHelper.createPartName("/foo/doc.RELS"); - - // Add content types - ctm.addContentType(name1, "foo-type1"); - ctm.addContentType(name2, "foo-type2"); - 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"); - } - - /** - * Test the addition then removal of content types. - */ - @Test - void testContentTypeRemoval() throws Exception { - ContentTypeManager ctm = new ZipContentTypeManager(null, null); - - PackagePartName name1 = PackagingURIHelper.createPartName("/foo/foo.xml"); - PackagePartName name2 = PackagingURIHelper.createPartName("/foo/foo2.xml"); - PackagePartName name3 = PackagingURIHelper.createPartName("/foo/doc.rels"); - PackagePartName name4 = PackagingURIHelper.createPartName("/foo/doc.RELS"); - - // Add content types - ctm.addContentType(name1, "foo-type1"); - ctm.addContentType(name2, "foo-type2"); - ctm.addContentType(name3, "text/xml+rel"); - ctm.addContentType(name4, "text/xml+rel"); - ctm.removeContentType(name2); - ctm.removeContentType(name3); - - assertEquals(ctm.getContentType(name1), "foo-type1"); - assertEquals(ctm.getContentType(name2), "foo-type1"); - assertNull(ctm.getContentType(name3)); - - ctm.removeContentType(name1); - assertNull(ctm.getContentType(name1)); - assertNull(ctm.getContentType(name2)); - } - - /** - * Test the addition then removal of content types in a package. - */ - @Disabled - void testContentTypeRemovalPackage() { - // TODO - } - - protected byte[] toByteArray(Workbook wb) { - try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { - 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 - // we now handle this broken file more gracefully - try (XSSFWorkbook targetWB = openSampleWorkbook("62629_target.xlsm"); - XSSFWorkbook mergeWB = openSampleWorkbook("62629_toMerge.xlsx")) { - for (Sheet b_sheet : mergeWB) { - XSSFSheet sheet = targetWB.createSheet(b_sheet.getSheetName()); - - XSSFDrawing drawingOld = (XSSFDrawing)b_sheet.createDrawingPatriarch(); - XSSFDrawing drawingNew = sheet.createDrawingPatriarch(); - CreationHelper helper = sheet.getWorkbook().getCreationHelper(); - List<XSSFShape> shapes = drawingOld.getShapes(); - - for (XSSFShape shape : shapes) { - assertTrue(shape instanceof XSSFPicture); - XSSFPicture pic = (XSSFPicture)shape; - XSSFPictureData picData = pic.getPictureData(); - int pictureIndex = targetWB.addPicture(picData.getData(), picData.getPictureType()); - ClientAnchor oldAnchor = pic.getClientAnchor(); - assertNotNull(oldAnchor); - ClientAnchor anchor = helper.createClientAnchor(); - anchor.setAnchorType(oldAnchor.getAnchorType()); - anchor.setDx1(oldAnchor.getDx1()); - anchor.setDx2(oldAnchor.getDx2()); - anchor.setDy1(oldAnchor.getDy1()); - anchor.setDy2(oldAnchor.getDy2()); - anchor.setCol1(oldAnchor.getCol1()); - anchor.setCol2(oldAnchor.getCol2()); - anchor.setRow1(oldAnchor.getRow1()); - anchor.setRow2(oldAnchor.getRow2()); - drawingNew.createPicture(anchor, pictureIndex); - } - } - - try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(targetWB)) { - for (XSSFWorkbook wb : Arrays.asList(targetWB, mergeWB)) { - for (Sheet sheet : wb) { - XSSFSheet backSheet = wbBack.getSheet(sheet.getSheetName()); - assertNotNull(backSheet); - XSSFDrawing origPat = (XSSFDrawing)sheet.createDrawingPatriarch(); - XSSFDrawing backPat = backSheet.createDrawingPatriarch(); - assertEquals(origPat.getShapes().size(), backPat.getShapes().size()); - } - } - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java deleted file mode 100644 index 3b9b03aed4..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal.marshallers; - -import static org.apache.poi.openxml4j.opc.PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.commons.compress.archivers.ArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.openxml4j.opc.internal.PartMarshaller; -import org.junit.jupiter.api.Test; - -class TestZipPackagePropertiesMarshaller { - private final PartMarshaller marshaller = new ZipPackagePropertiesMarshaller(); - - private boolean marshall() throws OpenXML4JException { - return marshall(new ZipArchiveOutputStream(new ByteArrayOutputStream())); - } - - private boolean marshall(OutputStream zos) throws OpenXML4JException { - PackagePartName rootUri = PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI); - PackagePropertiesPart part = new PackagePropertiesPart(null, rootUri); - return marshaller.marshall(part, zos); - } - - - @Test - void nonZipOutputStream() { - OutputStream notAZipOutputStream = new ByteArrayOutputStream(0); - assertThrows(IllegalArgumentException.class, () -> marshall(notAZipOutputStream)); - } - - @Test - void withZipOutputStream() throws Exception { - assertTrue(marshall()); - } - - @Test - void ioException() { - ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new ByteArrayOutputStream()) { - @Override - public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException { - throw new IOException("TestException"); - } - }; - assertThrows(OpenXML4JException.class, () -> marshall(zos)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/util/TestZipSecureFile.java b/src/ooxml/testcases/org/apache/poi/openxml4j/util/TestZipSecureFile.java deleted file mode 100644 index d80a44a1d8..0000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/util/TestZipSecureFile.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.openxml4j.util; - -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipFile; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -import java.io.InputStream; -import java.util.Enumeration; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -class TestZipSecureFile { - @Test - void testThresholdInputStream() throws Exception { - // This fails in Java 10 because our reflection injection of the ThresholdInputStream causes a - // ClassCastException in ZipFile now - // The relevant change in the JDK is http://hg.openjdk.java.net/jdk/jdk10/rev/85ea7e83af30#l5.66 - - try (ZipFile thresholdInputStream = new ZipFile(XSSFTestDataSamples.getSampleFile("template.xlsx"))) { - try (ZipSecureFile secureFile = new ZipSecureFile(XSSFTestDataSamples.getSampleFile("template.xlsx"))) { - Enumeration<? extends ZipArchiveEntry> entries = thresholdInputStream.getEntries(); - while (entries.hasMoreElements()) { - ZipArchiveEntry entry = entries.nextElement(); - - try (InputStream inputStream = secureFile.getInputStream(entry)) { - assertTrue(IOUtils.toByteArray(inputStream).length > 0); - } - } - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureConfig.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureConfig.java deleted file mode 100644 index 61eddc0d6e..0000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureConfig.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt.dsig; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; -import java.util.Base64; - -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -class TestSignatureConfig { - - @Test - @Disabled("failing in automated builds, due to issues loading security classes") - void testDigestAlgo() throws Exception { - SignatureConfig sc = new SignatureConfig(); - assertEquals(HashAlgorithm.sha256, sc.getDigestAlgo()); - sc.setDigestAlgo(HashAlgorithm.sha1); - assertEquals(HashAlgorithm.sha1, sc.getDigestAlgo()); - } - - @Test - void testHashOids() throws IOException { - final String[][] checks = { - { "sha1", "MCEwCQYFKw4DAhoFAAQU" }, - { "sha224", "MC0wDQYJYIZIAWUDBAIEBQAEHA==" }, - { "sha256", "MDEwDQYJYIZIAWUDBAIBBQAEIA==" }, - { "sha384", "MEEwDQYJYIZIAWUDBAICBQAEMA==" }, - { "sha512", "MFEwDQYJYIZIAWUDBAIDBQAEQA==" }, - { "ripemd128", "MB0wCQYFKyQDAgIFAAQQ" }, - { "ripemd160", "MCEwCQYFKyQDAgEFAAQU" }, - { "ripemd256", "MC0wCQYFKyQDAgMFAAQg" }, - }; - - for (final String[] check : checks) { - final HashAlgorithm ha = HashAlgorithm.valueOf(check[0]); - try (final DigestOutputStream dos = new DigestOutputStream(ha, null)) { - final String magic = Base64.getEncoder().encodeToString(dos.getHashMagic()); - assertEquals(check[1], magic, "hash digest magic mismatches"); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java deleted file mode 100644 index d7fc0b4471..0000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java +++ /dev/null @@ -1,1245 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ -package org.apache.poi.poifs.crypt.dsig; - -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.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.math.BigInteger; -import java.net.ConnectException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.SocketTimeoutException; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.security.Key; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.cert.CRLException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.RSAKeyGenParameterSpec; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.function.BiFunction; -import java.util.function.Supplier; - -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.dsig.CanonicalizationMethod; -import javax.xml.crypto.dsig.XMLSignatureException; -import javax.xml.crypto.dsig.dom.DOMSignContext; - -import org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; -import org.apache.poi.ooxml.POIXMLDocument; -import org.apache.poi.ooxml.util.DocumentHelper; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.crypt.dsig.facets.EnvelopedSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.facets.KeyInfoSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.facets.OOXMLSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.facets.XAdESXLSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.services.RevocationData; -import org.apache.poi.poifs.crypt.dsig.services.RevocationDataService; -import org.apache.poi.poifs.crypt.dsig.services.TimeStampService; -import org.apache.poi.poifs.crypt.dsig.services.TimeStampServiceValidator; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFSignatureLine; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFSignatureLine; -import org.apache.xmlbeans.SystemProperties; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers; -import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; -import org.bouncycastle.asn1.x509.BasicConstraints; -import org.bouncycastle.asn1.x509.CRLNumber; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.Extensions; -import org.bouncycastle.asn1.x509.KeyUsage; -import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.cert.X509CRLHolder; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.cert.X509ExtensionUtils; -import org.bouncycastle.cert.X509v2CRLBuilder; -import org.bouncycastle.cert.X509v3CertificateBuilder; -import org.bouncycastle.cert.jcajce.JcaX509CRLConverter; -import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; -import org.bouncycastle.cert.ocsp.BasicOCSPResp; -import org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder; -import org.bouncycastle.cert.ocsp.CertificateID; -import org.bouncycastle.cert.ocsp.CertificateStatus; -import org.bouncycastle.cert.ocsp.OCSPReq; -import org.bouncycastle.cert.ocsp.OCSPReqBuilder; -import org.bouncycastle.cert.ocsp.OCSPResp; -import org.bouncycastle.cert.ocsp.OCSPRespBuilder; -import org.bouncycastle.cert.ocsp.Req; -import org.bouncycastle.crypto.params.RSAKeyParameters; -import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory; -import org.bouncycastle.openssl.PEMParser; -import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; -import org.bouncycastle.operator.ContentSigner; -import org.bouncycastle.operator.DigestCalculator; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; -import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; -import org.etsi.uri.x01903.v13.DigestAlgAndValueType; -import org.etsi.uri.x01903.v13.QualifyingPropertiesType; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.w3.x2000.x09.xmldsig.ReferenceType; -import org.w3.x2000.x09.xmldsig.SignatureDocument; -import org.w3c.dom.Document; - -class TestSignatureInfo { - private static final Logger LOG = LogManager.getLogger(TestSignatureInfo.class); - private static final POIDataSamples testdata = POIDataSamples.getXmlDSignInstance(); - - private static Calendar cal; - private KeyPair keyPair; - private X509Certificate x509; - - @AfterAll - public static void removeUserLocale() { - LocaleUtil.resetUserLocale(); - } - - @BeforeAll - public static void initBouncy() { - CryptoFunctions.registerBouncyCastle(); - - // Set cal to now ... only set to fixed date for debugging ... - LocaleUtil.resetUserLocale(); - LocaleUtil.resetUserTimeZone(); - - cal = LocaleUtil.getLocaleCalendar(LocaleUtil.TIMEZONE_UTC); - assertNotNull(cal); - - // don't run this test when we are using older Xerces as it triggers an XML Parser backwards compatibility issue - // in the xmlsec jar file - String additionalJar = System.getProperty("additionaljar"); - //System.out.println("Having: " + additionalJar); - assumeTrue(additionalJar == null || additionalJar.trim().length() == 0, - "Not running TestSignatureInfo because we are testing with additionaljar set to " + additionalJar); - - System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true"); - - // Set line.separator for bug61182 - // System.setProperty("line.separator", "\n"); - } - - @Disabled("This test is very sensitive, it breaks with every little change to the produced XML") - @Test - void bug61182() throws Exception { - final String pfxInput = - "H4sIAAAAAAAAAFXTfzzTeRwH8P2uGRmG6hKSmJh9a2HsuPy60VnHCEU6v86sieZH2Jr2qFl+s+ZHJ5tfUcfKb4uho/OjiFq1qTv5ceFyp0PqEK"+ - "fH4+66++Pz+Dwer9fj8f7r9cRzEd4QMBTPRWxDIM14ZN47NfAWsJgL34Bx4at4Lvwdngvd9b8KqgbjQpGbMXzzgRGovytVFTBEzIXU47kQCd4U"+ - "ofJPvHl8JwyTjRS55hbKoor3UJLDE1i/PcPKCBAIDATjQlKiK67XjVYdcnkZgD2txroiAUb8W9dtn57DvTsbM+3wIsdocXDEN7TdPKgaSl+tU1"+ - "xq9oqiB5yMaZCPho8uUEbFU9U6u3N7lEMLTJGeA0RfX+5FMRrpXPFrbrlJ8uNUCE2H247P28Ckyfqlsy32yeKg/HTbH5JpqUDNw2B32+SaiRw7"+ - "ofRMePUpaAoK7KYgmd5ZIc0rLLYjJBfOWCb28xlrGhbpJvdToFdqt5PXVjEz5YOJ6g7W0fskuKW9/iZP0yLEVpR9XkkHmb6tfpcE8YwCdWNCan"+ - "LvAsco25JdF1j2/FLAMVU79HdOex07main90dy40511OZtTGZ+TdVd3lKZ7D3clEg9hLESHwSNnZ6239X4yLM4xYSElQ/hqSbwdmiozYG9PhF2"+ - "Zf0XaZnxzTK0Iot+rJ3kYoxWTLE8DR9leV62Ywbtlg4mapYOxb3lT7fQ1x4EQ44flh2oFWSPLR8LMbsc6jzJsV6OZ3TrODjHEdw9W+8OD32vd8"+ - "XQ6iCaIHcrSOn6qS0TKLr786234eeSAhvAQbEsVn7vrvc/487Be/O2e/+5Y5zRq2zAtz6pfcNyraJNDqMW1inNkgJ3t3VESbZ3pNzyl3KHILs0"+ - "51dY6msDYSlWhw40TglXxj9rw95O6gFWIuN012W/vhS50jpKXcao4gc1aLaXtJXxirbRkpZ/0e7a0pD6TDa7+GxEdEEML3VGo9udD5YUKhU3y7"+ - "SzWAgN6WIEIglq7LilvCjqIVLIfg8CvVGL9f5iSsCDf5hef4vMxbyvcjINuy06gZu+iPYOWNxjfrwKGYzoqqotK2aywgYVrPMh0JovfkDuN95n"+ - "MdVlYHbN1Mnn4TxAwuv+u3AkBlDZvRUUCwoDMUGxeMNPhTaAgWl60xhhBgCBaEMgAACReMAav7n3x598IDYJ9GxGXRAwaPOT/kfO/1AgPqLQkp"+ - "MiIVaHthnUS4v2y32e2BjdMPyIImUTBW3cV3R5tjVQm0MOm+D2C5+bBW9vHLjLR4lun4toQiY3Ls/v4bES/OJ4EmpZk5xhL9i5ClofYZNEsxFn"+ - "An/q821Tg+Cq9Er4XYGQe8ogjjLJ2b7dUsJ3auFQFNUJF7Ke7yUL2EeYYxl6vz5l4q5u8704mRbFts1E1eWMp6WIy91GPrsVlRGvtuNERfrjfE"+ - "YtzUI3Flcv65zJUbUBEzUnTS0fEYso2XyToAl8kb251mUY2o2lJzv5dp/1htmcjeeP2MjxC+3S45ljx7jd52Pv9XAat+ryiauFOF7YgztkoWWD"+ - "h62tplPH1bzDV+d0NLdaE5AfVJ09HuUYTFS+iggtvT5Euyk+unj4N2XvzW91n+GNjtgWfKOHmkinUPvYRh70Jv+wlPJrVaT8mL7GxJLqDC9jbv"+ - "Gznoiae6es+wQejnk3XjU366MrK/zXxngBYj9J6NnXc9mMiTFLX8WqQ8iTelTAFs2NJzPoDzrBUz4JFIEOa6Dja6dULc68g1jFDTeEHZyra7RZ"+ - "2ElqGDEqcNRo3SNX6feMy9EF1GOyZK0Sa87KwjKw8aM68dpsIYjfLcTXaZ6atg0BKfMnl6axeUGEaIFSP7rzj9wjzumRbG3jgUVp2lX5AK/tsO"+ - "7R4TQX/9/H6RiN34c9KldmPZZGANXzzTajZS9mR2OSvlJ+F4AgSko4htrMAKFTBu51/5SWNsO1vlRaaG48ZRJ+8PzuHQMdvS36gNpRPi7jhF1S"+ - "H3B2ycI4y0VURv6SrqJNUY/X645ZFJQ+eBO+ptG7o8axf1dcqh2beiQk+GRTeZ37LVeUlaeo9vl1/+8tyBfyT2v5lFC5E19WdKIyCuZe7r99Px"+ - "D/Od4Qj0TA92+DQnbCQTCMy/wwse9O4gsEebkkpPIP5GBV3Q0YBsj75XE0uSFQ1tCZSW8bNa9MUJZ/nPBfExohHlgGAAA="; - - // Unix - final String unixSignExp = - "QkqTFQZjXagjRAoOWKpAGa8AR0rKqkSfBtfSWqtjBmTgyjarn+t2POHkpySIpheHAbg+90GKSH88ACMtPHbG7q" + - "FL4gtgAD9Kjew6j16j0IRBwy145UlPrSLFMfF7YF7UlU1k1LBkIlRJ6Fv4MAJl6XspuzZOZIUmHZrWrdxycUQ="; - - // Windows - final String winSignExp = - "GmAlL7+bT1r3FsMHJOp3pKg8betblYieZTjhMIrPZPRBbSzjO7KsYRGNtr0aOE3qr8xzyYJN6/8QdF5X7pUEUc" + - "2m8ctrm7s5o2vZTkAqk9ENJGDjBPXX7TnuVOiVeL1cJdtjHC2QpjtRwkFR+B54G6b1OXLOFuQpP3vqR3+/XXE="; - - // Mac - final String macSignExp = - "NZedY/LNTYU4nAUEUhIOg5+fKdgVtzRXKmdD3v+47E7Mb84oeiUGv9cCEE91DU3StF/JFIhjOJqavOzKnCsNcz" + - "NJ4j/inggUl1OJUsicqIGQnA7E8vzWnN1kf5lINgJLv+0PyrrX9sQZbItzxUpgqyOFYcD0trid+31nRt4wtaA="; - - - - Calendar cal = LocaleUtil.getLocaleCalendar(LocaleUtil.TIMEZONE_UTC); - cal.clear(); - cal.setTimeZone(LocaleUtil.TIMEZONE_UTC); - cal.set(2017, Calendar.JULY, 1); - - SignatureConfig signatureConfig = prepareConfig(pfxInput); - signatureConfig.setExecutionTime(cal.getTime()); - - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(signatureConfig); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(100000); - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - wb1.createSheet().createRow(1).createCell(1).setCellValue("Test"); - wb1.write(bos); - } - - try (OPCPackage pkg1 = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()))) { - si.setOpcPackage(pkg1); - si.confirmSignature(); - assertTrue(si.verifySignature()); - bos.reset(); - pkg1.save(bos); - } - - try (XSSFWorkbook wb2 = new XSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { - assertEquals("Test", wb2.getSheetAt(0).getRow(1).getCell(1).getStringCellValue()); - OPCPackage pkg2 = wb2.getPackage(); - si.setOpcPackage(pkg2); - assertTrue(si.verifySignature()); - - // xmlbeans adds line-breaks depending on the system setting, so we get different - // test results on Unix/Mac/Windows - // if the xml documents eventually change, this test needs to be run with the - // separator set to the various system configurations - String sep = SystemProperties.getProperty("line.separator"); - String signExp; - assumeTrue(sep == null || "\n".equals(sep) || "\r\n".equals(sep) || "\r".equals(sep), "Hashes only known for Windows/Unix/Mac"); - signExp = (sep == null || "\n".equals(sep)) ? unixSignExp : ("\r\n".equals(sep)) ? winSignExp : macSignExp; - - String signAct = si.getSignatureParts().iterator().next(). - getSignatureDocument().getSignature().getSignatureValue().getStringValue(); - assertEquals(signExp, signAct); - } - } - - @Test - void office2007prettyPrintedRels() throws Exception { - try (OPCPackage pkg = OPCPackage.open(testdata.getFile("office2007prettyPrintedRels.docx"), PackageAccess.READ)) { - SignatureConfig sic = new SignatureConfig(); - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(sic); - boolean isValid = si.verifySignature(); - assertTrue(isValid); - } - } - - @Test - void getSignerUnsigned() throws Exception { - String[] testFiles = { - "hello-world-unsigned.docx", - "hello-world-unsigned.pptx", - "hello-world-unsigned.xlsx", - "hello-world-office-2010-technical-preview-unsigned.docx" - }; - - for (String testFile : testFiles) { - List<X509Certificate> result = new ArrayList<>(); - try (OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ)) { - SignatureConfig sic = new SignatureConfig(); - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(sic); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } - } - pkg.revert(); - } - assertNotNull(result); - assertTrue(result.isEmpty()); - } - } - - @Test - void getSigner() throws Exception { - String[] testFiles = { - "hyperlink-example-signed.docx", - "hello-world-signed.docx", - "hello-world-signed.pptx", - "hello-world-signed.xlsx", - "hello-world-office-2010-technical-preview.docx", - "ms-office-2010-signed.docx", - "ms-office-2010-signed.pptx", - "ms-office-2010-signed.xlsx", - "Office2010-SP1-XAdES-X-L.docx", - "signed.docx" - }; - - for (String testFile : testFiles) { - try (OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ)) { - SignatureConfig sic = new SignatureConfig(); - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(sic); - List<X509Certificate> result = new ArrayList<>(); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } - } - - assertNotNull(result); - assertEquals(1, result.size(), "test-file: " + testFile); - X509Certificate signer = result.get(0); - LOG.atDebug().log("signer: {}", signer.getSubjectX500Principal()); - - boolean b = si.verifySignature(); - assertTrue(b, "test-file: " + testFile); - pkg.revert(); - } - } - } - - @Test - void getMultiSigners() throws Exception { - String testFile = "hello-world-signed-twice.docx"; - try (OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ)) { - SignatureConfig sic = new SignatureConfig(); - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(sic); - List<X509Certificate> result = new ArrayList<>(); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } - } - - assertNotNull(result); - assertEquals(2, result.size(), "test-file: " + testFile); - X509Certificate signer1 = result.get(0); - X509Certificate signer2 = result.get(1); - LOG.atDebug().log("signer 1: {}", signer1.getSubjectX500Principal()); - LOG.atDebug().log("signer 2: {}", signer2.getSubjectX500Principal()); - - boolean b = si.verifySignature(); - assertTrue(b, "test-file: " + testFile); - pkg.revert(); - } - } - - @Test - void testSignSpreadsheet() throws Exception { - String testFile = "hello-world-unsigned.xlsx"; - try (OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE)) { - sign(pkg); - } - } - - private static class CommitableWorkbook extends XSSFWorkbook { - CommitableWorkbook(OPCPackage pkg) throws IOException { - super(pkg); - } - public void commit() throws IOException { - super.commit(); - } - } - - @Test - void testManipulation() throws Exception { - // sign & validate - String testFile = "hello-world-unsigned.xlsx"; - try (OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE)) { - sign(pkg); - - // manipulate - try (CommitableWorkbook wb = new CommitableWorkbook(pkg)) { - wb.setSheetName(0, "manipulated"); - // ... I don't know, why commit is protected ... - wb.commit(); - - // todo: test a manipulation on a package part, which is not signed - // ... maybe in combination with #56164 - - // validate - SignatureConfig sic = new SignatureConfig(); - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(sic); - boolean b = si.verifySignature(); - assertFalse(b, "signature should be broken"); - } - } - } - - @Test - void testSignSpreadsheetWithSignatureInfo() throws Exception { - initKeyPair(); - String testFile = "hello-world-unsigned.xlsx"; - try (OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE)) { - SignatureConfig sic = new SignatureConfig(); - sic.setKey(keyPair.getPrivate()); - sic.setSigningCertificateChain(Collections.singletonList(x509)); - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(sic); - // hash > sha1 doesn't work in excel viewer ... - si.confirmSignature(); - List<X509Certificate> result = new ArrayList<>(); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } - } - assertEquals(1, result.size()); - } - } - - @Test - void testSignEnvelopingDocument() throws Exception { - String testFile = "hello-world-unsigned.xlsx"; - File sigCopy = testdata.getFile(testFile); - ByteArrayOutputStream bos = new ByteArrayOutputStream(50000); - - final String execTimestr; - - - try (OPCPackage pkg = OPCPackage.open(copy(sigCopy), PackageAccess.READ_WRITE)) { - - initKeyPair(); - final X509CRL crl = generateCrl(x509, keyPair.getPrivate()); - - // setup - SignatureConfig signatureConfig = new SignatureConfig(); - signatureConfig.setKey(keyPair.getPrivate()); - - /* - * We need at least 2 certificates for the XAdES-C complete certificate - * refs construction. - */ - List<X509Certificate> certificateChain = new ArrayList<>(); - certificateChain.add(x509); - certificateChain.add(x509); - signatureConfig.setSigningCertificateChain(certificateChain); - - signatureConfig.addSignatureFacet(new OOXMLSignatureFacet()); - signatureConfig.addSignatureFacet(new EnvelopedSignatureFacet()); - signatureConfig.addSignatureFacet(new KeyInfoSignatureFacet()); - signatureConfig.addSignatureFacet(new XAdESSignatureFacet()); - signatureConfig.addSignatureFacet(new XAdESXLSignatureFacet()); - - // check for internet, no error means it works - boolean mockTsp = (getAccessError("http://timestamp.comodoca.com/rfc3161", true, 10000) != null); - - // http://timestamping.edelweb.fr/service/tsp - // http://tsa.belgium.be/connect - // http://timestamp.comodoca.com/authenticode - // http://timestamp.comodoca.com/rfc3161 - // http://services.globaltrustfinder.com/adss/tsa - signatureConfig.setTspUrl("http://timestamp.comodoca.com/rfc3161"); - signatureConfig.setTspRequestPolicy(null); // comodoca request fails, if default policy is set ... - signatureConfig.setTspOldProtocol(false); - - signatureConfig.setXadesDigestAlgo(HashAlgorithm.sha512); - signatureConfig.setXadesRole("Xades Reviewer"); - signatureConfig.setSignatureDescription("test xades signature"); - - execTimestr = signatureConfig.formatExecutionTime(); - - //set proxy info if any - String proxy = System.getProperty("http_proxy"); - if (proxy != null && proxy.trim().length() > 0) { - signatureConfig.setProxyUrl(proxy); - } - - if (mockTsp) { - TimeStampService tspService = (signatureInfo, data, revocationData) -> { - revocationData.addCRL(crl); - return "time-stamp-token".getBytes(LocaleUtil.CHARSET_1252); - }; - signatureConfig.setTspService(tspService); - } else { - TimeStampServiceValidator tspValidator = (validateChain, revocationData) -> { - for (X509Certificate certificate : validateChain) { - LOG.atDebug().log("certificate: {}", certificate.getSubjectX500Principal()); - LOG.atDebug().log("validity: {} - {}", certificate.getNotBefore(), certificate.getNotAfter()); - } - }; - signatureConfig.setTspValidator(tspValidator); - signatureConfig.setTspOldProtocol(signatureConfig.getTspUrl().contains("edelweb")); - } - - final RevocationData revocationData = new RevocationData(); - revocationData.addCRL(crl); - OCSPResp ocspResp = createOcspResp(x509, x509, x509, keyPair.getPrivate(), cal.getTimeInMillis()); - revocationData.addOCSP(ocspResp.getEncoded()); - - RevocationDataService revocationDataService = revocationChain -> revocationData; - signatureConfig.setRevocationDataService(revocationDataService); - - // operate - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(signatureConfig); - try { - si.confirmSignature(); - } catch (RuntimeException e) { - // only allow a ConnectException because of timeout, we see this in Jenkins from time to time... - if (e.getCause() == null) { - throw e; - } - if ((e.getCause() instanceof ConnectException) || (e.getCause() instanceof SocketTimeoutException)) { - assumeFalse(e.getCause().getMessage().contains("timed out"), - "Only allowing ConnectException with 'timed out' as message here, but had: " + e); - } else if (e.getCause() instanceof IOException) { - assumeFalse(e.getCause().getMessage().contains("Error contacting TSP server"), - "Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e); - } else if (e.getCause() instanceof RuntimeException) { - assumeFalse(e.getCause().getMessage().contains("This site is cur"), - "Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e); - } - throw e; - } - - // verify - Iterator<SignaturePart> spIter = si.getSignatureParts().iterator(); - assertTrue(spIter.hasNext(), "Had: " + pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN)); - SignaturePart sp = spIter.next(); - boolean valid = sp.validate(); - assertTrue(valid); - - SignatureDocument sigDoc = sp.getSignatureDocument(); - String declareNS = - "declare namespace xades='http://uri.etsi.org/01903/v1.3.2#'; " - + "declare namespace ds='http://www.w3.org/2000/09/xmldsig#'; "; - - String digestValXQuery = declareNS + - "$this/ds:Signature/ds:SignedInfo/ds:Reference"; - for (ReferenceType rt : (ReferenceType[]) sigDoc.selectPath(digestValXQuery)) { - assertNotNull(rt.getDigestValue()); - assertEquals(signatureConfig.getDigestMethodUri(), rt.getDigestMethod().getAlgorithm()); - } - - String certDigestXQuery = declareNS + - "$this//xades:SigningCertificate/xades:Cert/xades:CertDigest"; - XmlObject[] xoList = sigDoc.selectPath(certDigestXQuery); - assertEquals(xoList.length, 1); - 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); - QualifyingPropertiesType qualProp = (QualifyingPropertiesType) xoList[0]; - boolean qualPropXsdOk = qualProp.validate(); - assertTrue(qualPropXsdOk); - - pkg.save(bos); - } - - try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()))) { - SignatureConfig signatureConfig = new SignatureConfig(); - signatureConfig.setUpdateConfigOnValidate(true); - - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(signatureConfig); - - assertTrue(si.verifySignature()); - - assertEquals(HashAlgorithm.sha512, signatureConfig.getXadesDigestAlgo()); - assertEquals("Xades Reviewer", signatureConfig.getXadesRole()); - assertEquals("test xades signature", signatureConfig.getSignatureDescription()); - assertEquals(execTimestr, signatureConfig.formatExecutionTime()); - } - } - - public static String getAccessError(String destinationUrl, boolean fireRequest, int timeout) { - URL url; - try { - url = new URL(destinationUrl); - } catch (MalformedURLException e) { - throw new IllegalArgumentException("Invalid destination URL", e); - } - - HttpURLConnection conn = null; - try { - conn = (HttpURLConnection) url.openConnection(); - - // set specified timeout if non-zero - if(timeout != 0) { - conn.setConnectTimeout(timeout); - conn.setReadTimeout(timeout); - } - - conn.setDoOutput(false); - conn.setDoInput(true); - - /* if connecting is not possible this will throw a connection refused exception */ - conn.connect(); - - if (fireRequest) { - conn.getInputStream().close(); - } - /* if connecting is possible we return true here */ - return null; - - } catch (IOException e) { - /* exception is thrown -> server not available */ - return e.getClass().getName() + ": " + e.getMessage(); - } finally { - if (conn != null) { - conn.disconnect(); - } - } - } - - @Test - void testCertChain() throws Exception { - final boolean isIBM = System.getProperty("java.vendor").contains("IBM"); - - KeyStore keystore = KeyStore.getInstance("PKCS12"); - String password = "test"; - try (InputStream is = testdata.openResourceAsStream("chaintest.pfx")) { - keystore.load(is, password.toCharArray()); - } - - Key key = keystore.getKey("poitest", password.toCharArray()); - Certificate[] chainList = keystore.getCertificateChain("poitest"); - List<X509Certificate> certChain = new ArrayList<>(); - for (Certificate c : chainList) { - certChain.add((X509Certificate)c); - } - x509 = certChain.get(0); - keyPair = new KeyPair(x509.getPublicKey(), (PrivateKey)key); - - String testFile = "hello-world-unsigned.xlsx"; - try (OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE)) { - - SignatureConfig signatureConfig = new SignatureConfig(); - signatureConfig.setKey(keyPair.getPrivate()); - signatureConfig.setSigningCertificateChain(certChain); - Calendar oldCal = LocaleUtil.getLocaleCalendar(2007, 7, 1); - signatureConfig.setExecutionTime(oldCal.getTime()); - signatureConfig.setDigestAlgo(HashAlgorithm.sha1); - - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(signatureConfig); - - si.confirmSignature(); - - for (SignaturePart sp : si.getSignatureParts()) { - assertTrue(sp.validate(), "Could not validate"); - X509Certificate signer = sp.getSigner(); - assertNotNull(signer, "signer undefined?!"); - List<X509Certificate> certChainRes = sp.getCertChain(); - - // IBM JDK is still buggy, even after fix for APAR IJ21985 - int exp = isIBM ? 1 : 3; - assertEquals(exp, certChainRes.size()); - } - - } - } - - @Test - void testNonSha1() throws Exception { - String testFile = "hello-world-unsigned.xlsx"; - initKeyPair(); - - SignatureConfig signatureConfig = new SignatureConfig(); - signatureConfig.setKey(keyPair.getPrivate()); - signatureConfig.setSigningCertificateChain(Collections.singletonList(x509)); - - HashAlgorithm[] testAlgo = {HashAlgorithm.sha224, HashAlgorithm.sha256 - , HashAlgorithm.sha384, HashAlgorithm.sha512, HashAlgorithm.ripemd160}; - - for (HashAlgorithm ha : testAlgo) { - signatureConfig.setDigestAlgo(ha); - try (OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE)) { - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(signatureConfig); - - si.confirmSignature(); - boolean b = si.verifySignature(); - assertTrue(b, "Signature not correctly calculated for " + ha); - } catch (EncryptedDocumentException e) { - assumeTrue(e.getMessage().startsWith("Export Restrictions")); - } - } - } - - @Test - void bug58630() throws Exception { - // test deletion of sheet 0 and signing - File tpl = copy(testdata.getFile("bug58630.xlsx")); - try (SXSSFWorkbook wb1 = new SXSSFWorkbook((XSSFWorkbook)WorkbookFactory.create(tpl), 10)) { - wb1.setCompressTempFiles(true); - wb1.removeSheetAt(0); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - wb1.write(os); - - try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(os.toByteArray()))) { - initKeyPair(); - SignatureConfig signatureConfig = new SignatureConfig(); - signatureConfig.setKey(keyPair.getPrivate()); - signatureConfig.setSigningCertificateChain(Collections.singletonList(x509)); - - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(signatureConfig); - si.confirmSignature(); - assertTrue(si.verifySignature(), "invalid signature"); - } - } - } - - @Test - void testMultiSign() throws Exception { - cal = LocaleUtil.getLocaleCalendar(LocaleUtil.TIMEZONE_UTC); - cal.clear(); - cal.setTimeZone(LocaleUtil.TIMEZONE_UTC); - cal.set(2018, Calendar.DECEMBER, 14); - - // test signing with separate opened packages - File tpl = copy(testdata.getFile("hello-world-unsigned.xlsx")); - try (OPCPackage pkg = OPCPackage.open(tpl)) { - signPkg63011(pkg, "bug63011_key1.pem", true); - } - - try (OPCPackage pkg = OPCPackage.open(tpl)) { - signPkg63011(pkg, "bug63011_key2.pem", true); - } - - verifyPkg63011(tpl, true); - - // test signing with single opened package - tpl = copy(testdata.getFile("hello-world-unsigned.xlsx")); - try (OPCPackage pkg = OPCPackage.open(tpl)) { - signPkg63011(pkg, "bug63011_key1.pem", true); - signPkg63011(pkg, "bug63011_key2.pem", true); - } - - verifyPkg63011(tpl, true); - - try (OPCPackage pkg = OPCPackage.open(tpl)) { - signPkg63011(pkg, "bug63011_key1.pem", true); - signPkg63011(pkg, "bug63011_key2.pem", false); - } - - verifyPkg63011(tpl, false); - } - - private void verifyPkg63011(File tpl, boolean multi) throws InvalidFormatException, IOException { - try (OPCPackage pkg = OPCPackage.open(tpl, PackageAccess.READ)) { - SignatureConfig sic = new SignatureConfig(); - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(sic); - List<X509Certificate> result = new ArrayList<>(); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } - } - - assertNotNull(result); - - if (multi) { - assertEquals(2, result.size()); - assertEquals("CN=Muj Klic", result.get(0).getSubjectDN().toString()); - assertEquals("CN=My Second key", result.get(1).getSubjectDN().toString()); - } else { - assertEquals(1, result.size()); - assertEquals("CN=My Second key", result.get(0).getSubjectDN().toString()); - } - - assertTrue(si.verifySignature()); - pkg.revert(); - } - } - - private void signPkg63011(OPCPackage pkg, String pemFile, boolean multi) - throws IOException, CertificateException, XMLSignatureException, MarshalException { - assertNotNull(pkg); - initKeyFromPEM(testdata.getFile(pemFile)); - - SignatureConfig config = new SignatureConfig(); - config.setKey(keyPair.getPrivate()); - config.setSigningCertificateChain(Collections.singletonList(x509)); - config.setExecutionTime(cal.getTime()); - config.setAllowMultipleSignatures(multi); - - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(config); - si.confirmSignature(); - } - - @Test - void testRetrieveCertificate() throws InvalidFormatException, IOException { - SignatureConfig sic = new SignatureConfig(); - final File file = testdata.getFile("PPT2016withComment.pptx"); - try (final OPCPackage pkg = OPCPackage.open(file, PackageAccess.READ)) { - sic.setUpdateConfigOnValidate(true); - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(sic); - assertTrue(si.verifySignature()); - } - - final List<X509Certificate> certs = sic.getSigningCertificateChain(); - assertEquals(1, certs.size()); - assertEquals("CN=Test", certs.get(0).getSubjectDN().getName()); - assertEquals("SuperDuper-Reviewer", sic.getXadesRole()); - assertEquals("Purpose for signing", sic.getSignatureDescription()); - assertEquals("2018-06-10T09:00:54Z", sic.formatExecutionTime()); - assertEquals(CanonicalizationMethod.INCLUSIVE, sic.getCanonicalizationMethod()); - } - - private interface XmlDocumentPackageInit { - POIXMLDocument init(SignatureLine line, OPCPackage pkg) throws IOException, XmlException; - } - - @Test - void testSignatureImage() throws Exception { - initKeyPair(); - - List<Supplier<SignatureLine>> lines = Arrays.asList(XSSFSignatureLine::new, XWPFSignatureLine::new); - for (Supplier<SignatureLine> sup : lines) { - SignatureLine line = sup.get(); - line.setSuggestedSigner("Jack Sparrow"); - line.setSuggestedSigner2("Captain"); - line.setSuggestedSignerEmail("jack.bl@ck.perl"); - line.setInvalidStamp("Bungling!"); - line.setPlainSignature(testdata.readFile("jack-sign.emf")); - - String[] ext = { "" }; - BiFunction<SignatureLine,String[],POIXMLDocument> init = - (line instanceof XSSFSignatureLine) - ? this::initSignatureImageXSSF - : this::initSignatureImageXWPF; - - File signDoc; - try (POIXMLDocument xmlDoc = init.apply(line,ext)) { - signDoc = TempFile.createTempFile("visual-signature", ext[0]); - try (FileOutputStream fos = new FileOutputStream(signDoc)) { - xmlDoc.write(fos); - } - } - - try (OPCPackage pkg = OPCPackage.open(signDoc, PackageAccess.READ_WRITE)) { - SignatureConfig sic = new SignatureConfig(); - sic.setKey(keyPair.getPrivate()); - sic.setSigningCertificateChain(Collections.singletonList(x509)); - - line.updateSignatureConfig(sic); - - sic.setDigestAlgo(HashAlgorithm.sha1); - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(sic); - // hash > sha1 doesn't work in excel viewer ... - si.confirmSignature(); - } catch (java.util.ServiceConfigurationError e) { - assumeFalse(true, "running on module-path / JPMS and batik is \"kaputt\" WRT JPMS"); - } - - XmlDocumentPackageInit reinit = - (line instanceof XSSFSignatureLine) - ? this::initSignatureImageXSSF - : this::initSignatureImageXWPF; - - try (OPCPackage pkg = OPCPackage.open(signDoc, PackageAccess.READ)) { - SignatureLine line2 = sup.get(); - try (POIXMLDocument doc = reinit.init(line2, pkg)) { - line2.parse(); - assertEquals(line.getSuggestedSigner(), line2.getSuggestedSigner()); - assertEquals(line.getSuggestedSigner2(), line2.getSuggestedSigner2()); - assertEquals(line.getSuggestedSignerEmail(), line2.getSuggestedSignerEmail()); - } - - pkg.revert(); - } - } - } - - private XWPFDocument initSignatureImageXWPF(SignatureLine line, String[] ext) { - XWPFDocument doc = new XWPFDocument(); - ((XWPFSignatureLine)line).add(doc.createParagraph()); - ext[0] = ".docx"; - return doc; - } - - private XWPFDocument initSignatureImageXWPF(SignatureLine line, OPCPackage pkg) throws IOException, XmlException { - XWPFDocument doc = new XWPFDocument(pkg); - ((XWPFSignatureLine)line).parse(doc); - return doc; - } - - private XSSFWorkbook initSignatureImageXSSF(SignatureLine line, String[] ext) { - XSSFWorkbook xls = new XSSFWorkbook(); - XSSFSheet sheet = xls.createSheet(); - XSSFClientAnchor anchor = new XSSFClientAnchor(0,0,0,0,3,3,8,13); - ((XSSFSignatureLine)line).add(sheet, anchor); - ext[0] = ".xlsx"; - return xls; - } - - private XSSFWorkbook initSignatureImageXSSF(SignatureLine line, OPCPackage pkg) throws IOException, XmlException { - XSSFWorkbook xls = new XSSFWorkbook(pkg); - ((XSSFSignatureLine)line).parse(xls.getSheetAt(0)); - return xls; - } - - - private SignatureConfig prepareConfig(String pfxInput) throws Exception { - initKeyPair(pfxInput); - - SignatureConfig signatureConfig = new SignatureConfig(); - signatureConfig.setKey(keyPair.getPrivate()); - signatureConfig.setSigningCertificateChain(Collections.singletonList(x509)); - signatureConfig.setExecutionTime(cal.getTime()); - signatureConfig.setDigestAlgo(HashAlgorithm.sha1); - - return signatureConfig; - } - - private void sign(OPCPackage pkgCopy) throws Exception { - int signerCount = 1; - - SignatureConfig signatureConfig = prepareConfig(null); - - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkgCopy); - si.setSignatureConfig(signatureConfig); - - final Document document = DocumentHelper.createDocument(); - final DOMSignContext xmlSignContext = si.createXMLSignContext(document); - - // operate - final DOMSignedInfo signedInfo = si.preSign(xmlSignContext); - - // verify - assertNotNull(signedInfo); - assertEquals("Office OpenXML Document", signatureConfig.getSignatureDescription()); - - // setup: key material, signature value - final String signatureValue = si.signDigest(xmlSignContext, signedInfo); - - // operate: postSign - si.postSign(xmlSignContext, signatureValue); - - // verify: signature - si.setOpcPackage(pkgCopy); - List<X509Certificate> result = new ArrayList<>(); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } - } - assertEquals(signerCount, result.size()); - } - - private void initKeyPair() throws Exception { - initKeyPair(null); - } - - private void initKeyPair(String pfxInput) throws Exception { - final String alias = "Test"; - final char[] password = "test".toCharArray(); - File file = new File("build/test.pfx"); - file.getParentFile().mkdir(); - - KeyStore keystore = KeyStore.getInstance("PKCS12"); - - if (pfxInput != null) { - try (InputStream fis = new ByteArrayInputStream(RawDataUtil.decompress(pfxInput))) { - keystore.load(fis, password); - } - } else if (file.exists()) { - try (InputStream fis = new FileInputStream(file)) { - keystore.load(fis, password); - } - } else { - keystore.load(null, password); - } - - if (keystore.isKeyEntry(alias)) { - Key key = keystore.getKey(alias, password); - x509 = (X509Certificate)keystore.getCertificate(alias); - keyPair = new KeyPair(x509.getPublicKey(), (PrivateKey)key); - } else { - keyPair = generateKeyPair(); - Date notBefore = cal.getTime(); - Calendar cal2 = (Calendar)cal.clone(); - cal2.add(Calendar.YEAR, 1); - Date notAfter = cal2.getTime(); - KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature); - - x509 = generateCertificate(keyPair.getPublic(), notBefore, notAfter, keyPair.getPrivate(), keyUsage); - - keystore.setKeyEntry(alias, keyPair.getPrivate(), password, new Certificate[]{x509}); - - if (pfxInput == null) { - try (FileOutputStream fos = new FileOutputStream(file)) { - keystore.store(fos, password); - } - } - } - } - - private void initKeyFromPEM(File pemFile) throws IOException, CertificateException { - // see https://stackoverflow.com/questions/11787571/how-to-read-pem-file-to-get-private-and-public-key - PrivateKey key = null; - x509 = null; - - try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(pemFile), StandardCharsets.ISO_8859_1))) { - PEMParser parser = new PEMParser(br); - for (Object obj; (obj = parser.readObject()) != null; ) { - if (obj instanceof PrivateKeyInfo) { - key = new JcaPEMKeyConverter().setProvider("BC").getPrivateKey((PrivateKeyInfo)obj); - } else if (obj instanceof X509CertificateHolder) { - x509 = new JcaX509CertificateConverter().setProvider("BC").getCertificate((X509CertificateHolder)obj); - } - } - } - - if (key != null && x509 != null) { - keyPair = new KeyPair(x509.getPublicKey(), key); - } - } - - private static File copy(File input) throws IOException { - String extension = input.getName().replaceAll(".*?(\\.[^.]+)?$", "$1"); - if (extension.isEmpty()) { - extension = ".zip"; - } - - // ensure that we create the "build" directory as it might not be existing - // in the Sonar Maven runs where we are at a different source directory - File buildDir = new File("build"); - if(!buildDir.exists()) { - assertTrue(buildDir.mkdirs(), "Failed to create " + buildDir.getAbsolutePath()); - } - File tmpFile = new File(buildDir, "sigtest"+extension); - - try (OutputStream fos = new FileOutputStream(tmpFile)) { - try (InputStream fis = new FileInputStream(input)) { - IOUtils.copy(fis, fos); - } - } - - return tmpFile; - } - - private static KeyPair generateKeyPair() throws Exception { - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - SecureRandom random = new SecureRandom(); - keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, - RSAKeyGenParameterSpec.F4), random); - return keyPairGenerator.generateKeyPair(); - } - - private static X509Certificate generateCertificate(PublicKey subjectPublicKey, - Date notBefore, Date notAfter, - PrivateKey issuerPrivateKey, - KeyUsage keyUsage) - throws IOException, OperatorCreationException, CertificateException { - final String signatureAlgorithm = "SHA1withRSA"; - final String subjectDn = "CN=Test"; - X500Name issuerName = new X500Name(subjectDn); - - RSAPublicKey rsaPubKey = (RSAPublicKey)subjectPublicKey; - RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(), rsaPubKey.getPublicExponent()); - - SubjectPublicKeyInfo subjectPublicKeyInfo = - SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec); - - DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder() - .setProvider("BC").build().get(CertificateID.HASH_SHA1); - - X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder( - issuerName - , new BigInteger(128, new SecureRandom()) - , notBefore - , notAfter - , new X500Name(subjectDn) - , subjectPublicKeyInfo - ); - - X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc); - SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo); - AuthorityKeyIdentifier autKeyId = exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo); - - certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId); - certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId); - - BasicConstraints bc = new BasicConstraints(0); - certificateGenerator.addExtension(Extension.basicConstraints, false, bc); - - if (null != keyUsage) { - certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage); - } - - JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm); - signerBuilder.setProvider("BC"); - - X509CertificateHolder certHolder = - certificateGenerator.build(signerBuilder.build(issuerPrivateKey)); - - /* - * Next certificate factory trick is needed to make sure that the - * certificate delivered to the caller is provided by the default - * security provider instead of BouncyCastle. If we don't do this trick - * we might run into trouble when trying to use the CertPath validator. - */ -// CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); -// certificate = (X509Certificate) certificateFactory -// .generateCertificate(new ByteArrayInputStream(certificate -// .getEncoded())); - return new JcaX509CertificateConverter().getCertificate(certHolder); - } - - private static X509CRL generateCrl(X509Certificate issuer, PrivateKey issuerPrivateKey) - throws CertificateEncodingException, IOException, CRLException, OperatorCreationException { - - X509CertificateHolder holder = new X509CertificateHolder(issuer.getEncoded()); - X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(holder.getIssuer(), new Date()); - crlBuilder.setNextUpdate(new Date(new Date().getTime() + 100000)); - JcaContentSignerBuilder contentBuilder = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC"); - - CRLNumber crlNumber = new CRLNumber(new BigInteger("1234")); - - crlBuilder.addExtension(Extension.cRLNumber, false, crlNumber); - X509CRLHolder x509Crl = crlBuilder.build(contentBuilder.build(issuerPrivateKey)); - return new JcaX509CRLConverter().setProvider("BC").getCRL(x509Crl); - } - - private static OCSPResp createOcspResp(X509Certificate certificate, - X509Certificate issuerCertificate, - X509Certificate ocspResponderCertificate, - PrivateKey ocspResponderPrivateKey, - long nonceTimeinMillis) - throws Exception { - DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder() - .setProvider("BC").build().get(CertificateID.HASH_SHA1); - X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded()); - CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber()); - - // request - //create a nonce to avoid replay attack - BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis); - DEROctetString nonceDer = new DEROctetString(nonce.toByteArray()); - Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer); - Extensions exts = new Extensions(ext); - - OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder(); - ocspReqBuilder.addRequest(certId); - ocspReqBuilder.setRequestExtensions(exts); - OCSPReq ocspReq = ocspReqBuilder.build(); - - - SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo - (CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded()); - - BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc); - basicOCSPRespBuilder.setResponseExtensions(exts); - - // request processing - Req[] requestList = ocspReq.getRequestList(); - for (Req ocspRequest : requestList) { - CertificateID certificateID = ocspRequest.getCertID(); - CertificateStatus certificateStatus = CertificateStatus.GOOD; - basicOCSPRespBuilder.addResponse(certificateID, certificateStatus); - } - - // basic response generation - X509CertificateHolder[] chain = null; - if (!ocspResponderCertificate.equals(issuerCertificate)) { - // TODO: HorribleProxy can't convert array input params yet - chain = new X509CertificateHolder[] { - new X509CertificateHolder(ocspResponderCertificate.getEncoded()), - issuerHolder - }; - } - - ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA") - .setProvider("BC").build(ocspResponderPrivateKey); - BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis)); - - - OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder(); - - return ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java deleted file mode 100644 index 14e6debbf4..0000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt.tests; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Stream; - -import javax.crypto.Cipher; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.crypt.ChainingMode; -import org.apache.poi.poifs.crypt.CipherAlgorithm; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.Encryptor; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -class TestAgileEncryptionParameters { - - static byte[] testData; - - public static Stream<Arguments> data() { - CipherAlgorithm[] caList = {CipherAlgorithm.aes128, CipherAlgorithm.aes192, CipherAlgorithm.aes256, CipherAlgorithm.rc2, CipherAlgorithm.des, CipherAlgorithm.des3}; - HashAlgorithm[] haList = {HashAlgorithm.sha1, HashAlgorithm.sha256, HashAlgorithm.sha384, HashAlgorithm.sha512, HashAlgorithm.md5}; - ChainingMode[] cmList = {ChainingMode.cbc, ChainingMode.cfb}; - - List<Arguments> data = new ArrayList<>(); - for (CipherAlgorithm ca : caList) { - for (HashAlgorithm ha : haList) { - for (ChainingMode cm : cmList) { - data.add(Arguments.of(ca,ha,cm)); - } - } - } - - return data.stream(); - } - - @BeforeAll - public static void initTestData() throws Exception { - InputStream testFile = POIDataSamples.getDocumentInstance().openResourceAsStream("SampleDoc.docx"); - testData = IOUtils.toByteArray(testFile); - testFile.close(); - } - - @ParameterizedTest - @MethodSource("data") - void testAgileEncryptionModes(CipherAlgorithm ca, HashAlgorithm ha, ChainingMode cm) throws Exception { - int maxKeyLen = Cipher.getMaxAllowedKeyLength(ca.jceId); - assumeTrue(maxKeyLen >= ca.defaultKeySize, "Please install JCE Unlimited Strength Jurisdiction Policy files"); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - POIFSFileSystem fsEnc = new POIFSFileSystem(); - EncryptionInfo infoEnc = new EncryptionInfo(EncryptionMode.agile, ca, ha, -1, -1, cm); - Encryptor enc = infoEnc.getEncryptor(); - enc.confirmPassword("foobaa"); - OutputStream os = enc.getDataStream(fsEnc); - os.write(testData); - os.close(); - bos.reset(); - fsEnc.writeFilesystem(bos); - fsEnc.close(); - - POIFSFileSystem fsDec = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - EncryptionInfo infoDec = new EncryptionInfo(fsDec); - Decryptor dec = infoDec.getDecryptor(); - boolean passed = dec.verifyPassword("foobaa"); - assertTrue(passed); - InputStream is = dec.getDataStream(fsDec); - byte[] actualData = IOUtils.toByteArray(is); - is.close(); - fsDec.close(); - assertArrayEquals(testData, actualData, "Failed roundtrip - "+ca+"-"+ha+"-"+cm); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestDecryptor.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestDecryptor.java deleted file mode 100644 index fed15e2f3c..0000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestDecryptor.java +++ /dev/null @@ -1,186 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt.tests; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; - -import javax.crypto.Cipher; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.junit.jupiter.api.Test; - -class TestDecryptor { - private static final POIDataSamples samples = POIDataSamples.getPOIFSInstance(); - - @Test - void passwordVerification() throws IOException, GeneralSecurityException { - try (InputStream is = samples.openResourceAsStream("protect.xlsx"); - POIFSFileSystem fs = new POIFSFileSystem(is)) { - EncryptionInfo info = new EncryptionInfo(fs); - Decryptor d = Decryptor.getInstance(info); - assertTrue(d.verifyPassword(Decryptor.DEFAULT_PASSWORD)); - } - } - - @Test - void decrypt() throws IOException, GeneralSecurityException { - try (InputStream is = samples.openResourceAsStream("protect.xlsx"); - POIFSFileSystem fs = new POIFSFileSystem(is)) { - EncryptionInfo info = new EncryptionInfo(fs); - Decryptor d = Decryptor.getInstance(info); - d.verifyPassword(Decryptor.DEFAULT_PASSWORD); - zipOk(fs.getRoot(), d); - } - } - - @Test - void agile() throws IOException, GeneralSecurityException { - try (InputStream is = samples.openResourceAsStream("protected_agile.docx"); - POIFSFileSystem fs = new POIFSFileSystem(is)) { - EncryptionInfo info = new EncryptionInfo(fs); - assertTrue(info.getVersionMajor() == 4 && info.getVersionMinor() == 4); - Decryptor d = Decryptor.getInstance(info); - assertTrue(d.verifyPassword(Decryptor.DEFAULT_PASSWORD)); - zipOk(fs.getRoot(), d); - } - } - - private void zipOk(DirectoryNode root, Decryptor d) throws IOException, GeneralSecurityException { - try (ZipArchiveInputStream zin = new ZipArchiveInputStream(d.getDataStream(root))) { - - while (true) { - ZipArchiveEntry entry = zin.getNextZipEntry(); - if (entry == null) { - break; - } - // crc32 is checked within zip-stream - if (entry.isDirectory()) { - continue; - } - assertEquals(entry.getSize() - 1, zin.skip(entry.getSize() - 1)); - byte[] buf = new byte[10]; - int readBytes = zin.read(buf); - // zin.available() doesn't work for entries - assertEquals(1, readBytes, "size failed for " + entry.getName()); - } - } - } - - @Test - void dataLength() throws Exception { - try (InputStream fsIs = samples.openResourceAsStream("protected_agile.docx"); - POIFSFileSystem fs = new POIFSFileSystem(fsIs)) { - EncryptionInfo info = new EncryptionInfo(fs); - Decryptor d = Decryptor.getInstance(info); - d.verifyPassword(Decryptor.DEFAULT_PASSWORD); - - try (InputStream is = d.getDataStream(fs)) { - - long len = d.getLength(); - assertEquals(12810, len); - - byte[] buf = new byte[(int) len]; - assertEquals(12810, is.read(buf)); - - ZipArchiveInputStream zin = new ZipArchiveInputStream(new ByteArrayInputStream(buf)); - - while (true) { - ZipArchiveEntry entry = zin.getNextZipEntry(); - if (entry==null) { - break; - } - - IOUtils.toByteArray(zin); - } - } - } - } - - @Test - void bug57080() throws Exception { - // the test file contains a wrong ole entry size, produced by extenxls - // the fix limits the available size and tries to read all entries - File f = samples.getFile("extenxls_pwd123.xlsx"); - - try (POIFSFileSystem fs = new POIFSFileSystem(f, true)) { - EncryptionInfo info = new EncryptionInfo(fs); - Decryptor d = Decryptor.getInstance(info); - d.verifyPassword("pwd123"); - - final ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); - try (final ZipArchiveInputStream zis = new ZipArchiveInputStream(d.getDataStream(fs))) { - int[] sizes = { 3711, 1155, 445, 9376, 450, 588, 1337, 2593, 304, 7910 }; - for (int size : sizes) { - final ZipArchiveEntry ze = zis.getNextZipEntry(); - assertNotNull(ze); - IOUtils.copy(zis, bos); - assertEquals(size, bos.size()); - bos.reset(); - } - } - } - } - - @Test - void test58616() throws IOException, GeneralSecurityException { - try (InputStream is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("58616.xlsx"); - POIFSFileSystem pfs = new POIFSFileSystem(is)) { - EncryptionInfo info = new EncryptionInfo(pfs); - Decryptor dec = Decryptor.getInstance(info); - MessageDigest md = CryptoFunctions.getMessageDigest(HashAlgorithm.sha256); - try (InputStream is2 = dec.getDataStream(pfs)) { - md.update(IOUtils.toByteArray(is2)); - } - assertEquals("L1vDQq2EuMSfU/FBfVQfM2zfOY5Jx9ZyVgIQhXPPVgs=", Base64.encodeBase64String(md.digest())); - } - } - - @Test - void bug60320() throws IOException, GeneralSecurityException { - int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256"); - - try (InputStream is = samples.openResourceAsStream("60320-protected.xlsx"); - POIFSFileSystem fs = new POIFSFileSystem(is)) { - EncryptionInfo info = new EncryptionInfo(fs); - Decryptor d = Decryptor.getInstance(info); - assertTrue(d.verifyPassword("Test001!!")); - zipOk(fs.getRoot(), d); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptionInfo.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptionInfo.java deleted file mode 100644 index 879bf2d2a6..0000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptionInfo.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt.tests; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.crypt.CipherAlgorithm; -import org.apache.poi.poifs.crypt.CipherProvider; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.Test; - -class TestEncryptionInfo { - @Test - void testEncryptionInfo() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); - - EncryptionInfo info = new EncryptionInfo(fs); - - assertEquals(3, info.getVersionMajor()); - assertEquals(2, info.getVersionMinor()); - - assertEquals(CipherAlgorithm.aes128, info.getHeader().getCipherAlgorithm()); - assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithm()); - assertEquals(128, info.getHeader().getKeySize()); - assertEquals(32, info.getVerifier().getEncryptedVerifierHash().length); - assertEquals(CipherProvider.aes, info.getHeader().getCipherProvider()); - assertEquals("Microsoft Enhanced RSA and AES Cryptographic Provider", info.getHeader().getCspName()); - - fs.close(); - } - - @Test - void testEncryptionInfoSHA512() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_sha512.xlsx")); - - EncryptionInfo info = new EncryptionInfo(fs); - - assertEquals(4, info.getVersionMajor()); - assertEquals(4, info.getVersionMinor()); - - assertEquals(CipherAlgorithm.aes256, info.getHeader().getCipherAlgorithm()); - assertEquals(HashAlgorithm.sha512, info.getHeader().getHashAlgorithm()); - assertEquals(256, info.getHeader().getKeySize()); - assertEquals(64, info.getVerifier().getEncryptedVerifierHash().length); - assertEquals(CipherProvider.aes, info.getHeader().getCipherProvider()); -// assertEquals("Microsoft Enhanced RSA and AES Cryptographic Provider", info.getHeader().getCspName()); - - fs.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptor.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptor.java deleted file mode 100644 index ed2ee87e02..0000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestEncryptor.java +++ /dev/null @@ -1,677 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt.tests; - -import static org.apache.poi.poifs.crypt.CryptoFunctions.getMessageDigest; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -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.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.DigestInputStream; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.util.Iterator; -import java.util.Random; - -import javax.crypto.Cipher; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.crypt.CipherAlgorithm; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.EncryptionVerifier; -import org.apache.poi.poifs.crypt.Encryptor; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.crypt.agile.AgileDecryptor; -import org.apache.poi.poifs.crypt.agile.AgileEncryptionHeader; -import org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.DocumentNode; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.poifs.filesystem.TempFilePOIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NullOutputStream; -import org.apache.poi.util.TempFile; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -class TestEncryptor { - @Test - void binaryRC4Encryption() throws Exception { - // please contribute a real sample file, which is binary rc4 encrypted - // ... at least the output can be opened in Excel Viewer - String password = "pass"; - - final byte[] payloadExpected; - try (InputStream is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SimpleMultiCell.xlsx")) { - payloadExpected = IOUtils.toByteArray(is); - } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (POIFSFileSystem fs = new POIFSFileSystem()) { - EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4); - Encryptor enc = ei.getEncryptor(); - enc.confirmPassword(password); - - try (OutputStream os = enc.getDataStream(fs.getRoot())) { - os.write(payloadExpected); - } - - fs.writeFilesystem(bos); - } - - final byte[] payloadActual; - try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) { - EncryptionInfo ei = new EncryptionInfo(fs); - Decryptor dec = ei.getDecryptor(); - boolean b = dec.verifyPassword(password); - assertTrue(b); - - try (InputStream is = dec.getDataStream(fs.getRoot())) { - payloadActual = IOUtils.toByteArray(is); - } - } - - assertArrayEquals(payloadExpected, payloadActual); - } - - @Test - void tempFileAgileEncryption() throws Exception { - String password = "pass"; - - final byte[] payloadExpected; - try (InputStream is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SimpleMultiCell.xlsx")) { - payloadExpected = IOUtils.toByteArray(is); - } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (POIFSFileSystem fs = new TempFilePOIFSFileSystem()) { - EncryptionInfo ei = new EncryptionInfo(EncryptionMode.agile); - Encryptor enc = ei.getEncryptor(); - enc.confirmPassword(password); - - try (OutputStream os = enc.getDataStream(fs.getRoot())) { - os.write(payloadExpected); - } - - fs.writeFilesystem(bos); - } - - final byte[] payloadActual; - try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) { - EncryptionInfo ei = new EncryptionInfo(fs); - Decryptor dec = ei.getDecryptor(); - boolean b = dec.verifyPassword(password); - assertTrue(b); - - try (InputStream is = dec.getDataStream(fs.getRoot())) { - payloadActual = IOUtils.toByteArray(is); - } - } - - assertArrayEquals(payloadExpected, payloadActual); - } - - @Test - void agileEncryption() throws Exception { - int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256"); - - File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-pass.docx"); - String pass = "pass"; - - final byte[] payloadExpected, encPackExpected; - final long decPackLenExpected; - final EncryptionInfo infoExpected; - final Decryptor decExpected; - - try (POIFSFileSystem nfs = new POIFSFileSystem(file, true)) { - - // Check the encryption details - infoExpected = new EncryptionInfo(nfs); - decExpected = Decryptor.getInstance(infoExpected); - boolean passed = decExpected.verifyPassword(pass); - assertTrue(passed, "Unable to process: document is encrypted"); - - // extract the payload - try (InputStream is = decExpected.getDataStream(nfs)) { - payloadExpected = IOUtils.toByteArray(is); - } - - decPackLenExpected = decExpected.getLength(); - assertEquals(decPackLenExpected, payloadExpected.length); - - final DirectoryNode root = nfs.getRoot(); - final DocumentEntry entry = (DocumentEntry)root.getEntry(Decryptor.DEFAULT_POIFS_ENTRY); - try (InputStream is = root.createDocumentInputStream(entry)) { - // ignore padding block - encPackExpected = IOUtils.toByteArray(is, entry.getSize()-16); - } - } - - // check that same verifier/salt lead to same hashes - final byte[] verifierSaltExpected = infoExpected.getVerifier().getSalt(); - final byte[] verifierExpected = decExpected.getVerifier(); - final byte[] keySalt = infoExpected.getHeader().getKeySalt(); - final byte[] keySpec = decExpected.getSecretKey().getEncoded(); - final byte[] integritySalt = decExpected.getIntegrityHmacKey(); - // the hmacs of the file always differ, as we use PKCS5-padding to pad the bytes - // whereas office just uses random bytes - // byte integrityHash[] = d.getIntegrityHmacValue(); - - final EncryptionInfo infoActual = new EncryptionInfo( - EncryptionMode.agile - , infoExpected.getVerifier().getCipherAlgorithm() - , infoExpected.getVerifier().getHashAlgorithm() - , infoExpected.getHeader().getKeySize() - , infoExpected.getHeader().getBlockSize() - , infoExpected.getVerifier().getChainingMode() - ); - - Encryptor e = Encryptor.getInstance(infoActual); - e.confirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, integritySalt); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (POIFSFileSystem fs = new POIFSFileSystem()) { - try (OutputStream os = e.getDataStream(fs)) { - os.write(payloadExpected); - } - fs.writeFilesystem(bos); - } - - final EncryptionInfo infoActual2; - final byte[] payloadActual, encPackActual; - final long decPackLenActual; - try (POIFSFileSystem nfs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) { - infoActual2 = new EncryptionInfo(nfs.getRoot()); - Decryptor decActual = Decryptor.getInstance(infoActual2); - boolean passed = decActual.verifyPassword(pass); - assertTrue(passed, "Unable to process: document is encrypted"); - - // extract the payload - try (InputStream is = decActual.getDataStream(nfs)) { - payloadActual = IOUtils.toByteArray(is); - } - - decPackLenActual = decActual.getLength(); - - final DirectoryNode root = nfs.getRoot(); - final DocumentEntry entry = (DocumentEntry)root.getEntry(Decryptor.DEFAULT_POIFS_ENTRY); - try (InputStream is = root.createDocumentInputStream(entry)) { - // ignore padding block - encPackActual = IOUtils.toByteArray(is, entry.getSize()-16); - } - } - - AgileEncryptionHeader aehExpected = (AgileEncryptionHeader)infoExpected.getHeader(); - AgileEncryptionHeader aehActual = (AgileEncryptionHeader)infoActual.getHeader(); - assertArrayEquals(aehExpected.getEncryptedHmacKey(), aehActual.getEncryptedHmacKey()); - assertEquals(decPackLenExpected, decPackLenActual); - assertArrayEquals(payloadExpected, payloadActual); - assertArrayEquals(encPackExpected, encPackActual); - } - - @Test - void standardEncryption() throws Exception { - File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-solrcell.docx"); - final String pass = "solrcell"; - - final byte[] payloadExpected; - final EncryptionInfo infoExpected; - final Decryptor d; - try (POIFSFileSystem nfs = new POIFSFileSystem(file, true)) { - - // Check the encryption details - infoExpected = new EncryptionInfo(nfs); - d = Decryptor.getInstance(infoExpected); - boolean passed = d.verifyPassword(pass); - assertTrue(passed, "Unable to process: document is encrypted"); - - // extract the payload - try (InputStream is = d.getDataStream(nfs)) { - payloadExpected = IOUtils.toByteArray(is); - } - } - - // check that same verifier/salt lead to same hashes - final byte[] verifierSaltExpected = infoExpected.getVerifier().getSalt(); - final byte[] verifierExpected = d.getVerifier(); - final byte[] keySpec = d.getSecretKey().getEncoded(); - final byte[] keySalt = infoExpected.getHeader().getKeySalt(); - - - final EncryptionInfo infoActual = new EncryptionInfo( - EncryptionMode.standard - , infoExpected.getVerifier().getCipherAlgorithm() - , infoExpected.getVerifier().getHashAlgorithm() - , infoExpected.getHeader().getKeySize() - , infoExpected.getHeader().getBlockSize() - , infoExpected.getVerifier().getChainingMode() - ); - - final Encryptor e = Encryptor.getInstance(infoActual); - e.confirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, null); - - assertArrayEquals(infoExpected.getVerifier().getEncryptedVerifier(), infoActual.getVerifier().getEncryptedVerifier()); - assertArrayEquals(infoExpected.getVerifier().getEncryptedVerifierHash(), infoActual.getVerifier().getEncryptedVerifierHash()); - - // now we use a newly generated salt/verifier and check - // if the file content is still the same - - final byte[] encBytes; - try (POIFSFileSystem fs = new POIFSFileSystem()) { - - final EncryptionInfo infoActual2 = new EncryptionInfo( - EncryptionMode.standard - , infoExpected.getVerifier().getCipherAlgorithm() - , infoExpected.getVerifier().getHashAlgorithm() - , infoExpected.getHeader().getKeySize() - , infoExpected.getHeader().getBlockSize() - , infoExpected.getVerifier().getChainingMode() - ); - - final Encryptor e2 = Encryptor.getInstance(infoActual2); - e2.confirmPassword(pass); - - try (OutputStream os = e2.getDataStream(fs)) { - os.write(payloadExpected); - } - - final ByteArrayOutputStream bos = new ByteArrayOutputStream(50000); - fs.writeFilesystem(bos); - encBytes = bos.toByteArray(); - } - - final byte[] payloadActual; - try (POIFSFileSystem nfs = new POIFSFileSystem(new ByteArrayInputStream(encBytes))) { - final EncryptionInfo ei = new EncryptionInfo(nfs); - Decryptor d2 = Decryptor.getInstance(ei); - assertTrue(d2.verifyPassword(pass), "Unable to process: document is encrypted"); - - try (InputStream is = d2.getDataStream(nfs)) { - payloadActual = IOUtils.toByteArray(is); - } - } - - assertArrayEquals(payloadExpected, payloadActual); - } - - /** - * Ensure we can encrypt a package that is missing the Core - * Properties, eg one from dodgy versions of Jasper Reports - * See https://github.com/nestoru/xlsxenc/ and - * http://stackoverflow.com/questions/28593223 - */ - @Test - void encryptPackageWithoutCoreProperties() throws Exception { - // Open our file without core properties - final byte[] encBytes; - try (InputStream is = POIDataSamples.getOpenXML4JInstance().openResourceAsStream("OPCCompliance_NoCoreProperties.xlsx"); - OPCPackage pkg = OPCPackage.open(is)) { - - // It doesn't have any core properties yet - assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertFalse(pkg.getPackageProperties().getLanguageProperty().isPresent()); - - // Encrypt it - EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); - Encryptor enc = info.getEncryptor(); - enc.confirmPassword("password"); - - try (POIFSFileSystem fs = new POIFSFileSystem()) { - - try (OutputStream os = enc.getDataStream(fs)) { - pkg.save(os); - } - - // Save the resulting OLE2 document, and re-open it - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - fs.writeFilesystem(baos); - encBytes = baos.toByteArray(); - } - } - - - try (POIFSFileSystem inpFS = new POIFSFileSystem(new ByteArrayInputStream(encBytes))) { - // Check we can decrypt it - EncryptionInfo info = new EncryptionInfo(inpFS); - Decryptor d = Decryptor.getInstance(info); - assertTrue(d.verifyPassword("password")); - - try (OPCPackage inpPkg = OPCPackage.open(d.getDataStream(inpFS))) { - // Check it now has empty core properties - assertEquals(1, inpPkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(inpPkg.getPackageProperties()); - assertNotNull(inpPkg.getPackageProperties().getLanguageProperty()); - assertFalse(inpPkg.getPackageProperties().getLanguageProperty().isPresent()); - - } - } - } - - @Test - @Disabled - void inPlaceRewrite() throws Exception { - File f = TempFile.createTempFile("protected_agile", ".docx"); - - try (FileOutputStream fos = new FileOutputStream(f); - InputStream fis = POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_agile.docx")) { - IOUtils.copy(fis, fos); - } - - try (POIFSFileSystem fs = new POIFSFileSystem(f, false)) { - - // decrypt the protected file - in this case it was encrypted with the default password - EncryptionInfo encInfo = new EncryptionInfo(fs); - Decryptor d = encInfo.getDecryptor(); - boolean b = d.verifyPassword(Decryptor.DEFAULT_PASSWORD); - assertTrue(b); - - try (InputStream docIS = d.getDataStream(fs); - XWPFDocument docx = new XWPFDocument(docIS)) { - - // do some strange things with it ;) - XWPFParagraph p = docx.getParagraphArray(0); - p.insertNewRun(0).setText("POI was here! All your base are belong to us!"); - p.insertNewRun(1).addBreak(); - - // and encrypt it again - Encryptor e = encInfo.getEncryptor(); - e.confirmPassword("AYBABTU"); - - try (OutputStream os = e.getDataStream(fs)) { - docx.write(os); - } - } - } - } - - - private void listEntry(DocumentNode de, String ext, String path) throws IOException { - path += "\\" + de.getName().replaceAll("[\\p{Cntrl}]", "_"); - System.out.println(ext+": "+path+" ("+de.getSize()+" bytes)"); - - String name = de.getName().replaceAll("[\\p{Cntrl}]", "_"); - - InputStream is = ((DirectoryNode)de.getParent()).createDocumentInputStream(de); - FileOutputStream fos = new FileOutputStream("solr."+name+"."+ext); - IOUtils.copy(is, fos); - fos.close(); - is.close(); - } - - @SuppressWarnings("unused") - private void listDir(DirectoryNode dn, String ext, String path) throws IOException { - path += "\\" + dn.getName().replace('\u0006', '_'); - System.out.println(ext+": "+path+" ("+dn.getStorageClsid()+")"); - - Iterator<Entry> iter = dn.getEntries(); - while (iter.hasNext()) { - Entry ent = iter.next(); - if (ent instanceof DirectoryNode) { - listDir((DirectoryNode)ent, ext, path); - } else { - listEntry((DocumentNode)ent, ext, path); - } - } - } - - /* - * this test simulates the generation of bugs 60320 sample file - * as the padding bytes of the EncryptedPackage stream are random or in POIs case PKCS5-padded - * one would need to mock those bytes to get the same hmacValues - see diff below - * - * this use-case is experimental - for the time being the setters of the encryption classes - * are spreaded between two packages and are protected - so you would need to violate - * the packages rules and provide a helper class in the *poifs.crypt package-namespace. - * the default way of defining the encryption settings is via the EncryptionInfo class - */ - @Test - void bug60320CustomEncrypt() throws Exception { - int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256"); - - // --- src/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java (revision 1766745) - // +++ src/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java (working copy) - // @@ -208,6 +208,13 @@ - // protected int invokeCipher(int posInChunk, boolean doFinal) throws GeneralSecurityException { - // byte plain[] = (_plainByteFlags.isEmpty()) ? null : _chunk.clone(); - // - // + if (posInChunk < 4096) { - // + _cipher.update(_chunk, 0, posInChunk, _chunk); - // + byte bla[] = { (byte)0x7A,(byte)0x0F,(byte)0x27,(byte)0xF0,(byte)0x17,(byte)0x6E,(byte)0x77,(byte)0x05,(byte)0xB9,(byte)0xDA,(byte)0x49,(byte)0xF9,(byte)0xD7,(byte)0x8E,(byte)0x03,(byte)0x1D }; - // + System.arraycopy(bla, 0, _chunk, posInChunk-2, bla.length); - // + return posInChunk-2+bla.length; - // + } - // + - // int ciLen = (doFinal) - // ? _cipher.doFinal(_chunk, 0, posInChunk, _chunk) - // : _cipher.update(_chunk, 0, posInChunk, _chunk); - // - // --- src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java (revision 1766745) - // +++ src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java (working copy) - // - // @@ -300,7 +297,7 @@ - // protected static Cipher initCipherForBlock(Cipher existing, int block, boolean lastChunk, EncryptionInfo encryptionInfo, SecretKey skey, int encryptionMode) - // throws GeneralSecurityException { - // EncryptionHeader header = encryptionInfo.getHeader(); - // - String padding = (lastChunk ? "PKCS5Padding" : "NoPadding"); - // + String padding = "NoPadding"; // (lastChunk ? "PKCS5Padding" : "NoPadding"); - // if (existing == null || !existing.getAlgorithm().endsWith(padding)) { - // existing = getCipher(skey, header.getCipherAlgorithm(), header.getChainingMode(), header.getKeySalt(), encryptionMode, padding); - // } - - final EncryptionInfo infoOrig; - final byte[] zipInput, epOrigBytes; - try (InputStream is = POIDataSamples.getPOIFSInstance().openResourceAsStream("60320-protected.xlsx"); - POIFSFileSystem fsOrig = new POIFSFileSystem(is)) { - infoOrig = new EncryptionInfo(fsOrig); - Decryptor decOrig = infoOrig.getDecryptor(); - boolean b = decOrig.verifyPassword("Test001!!"); - assertTrue(b); - try (InputStream decIn = decOrig.getDataStream(fsOrig)) { - zipInput = IOUtils.toByteArray(decIn); - } - - try (InputStream epOrig = fsOrig.getRoot().createDocumentInputStream("EncryptedPackage")) { - // ignore the 16 padding bytes - epOrigBytes = IOUtils.toByteArray(epOrig, 9400); - } - } - - EncryptionInfo eiNew = new EncryptionInfo(EncryptionMode.agile); - AgileEncryptionHeader aehHeader = (AgileEncryptionHeader)eiNew.getHeader(); - aehHeader.setCipherAlgorithm(CipherAlgorithm.aes128); - aehHeader.setHashAlgorithm(HashAlgorithm.sha1); - AgileEncryptionVerifier aehVerifier = (AgileEncryptionVerifier)eiNew.getVerifier(); - - // this cast might look strange - if the setters would be public, it will become obsolete - // see http://stackoverflow.com/questions/5637650/overriding-protected-methods-in-java - ((EncryptionVerifier)aehVerifier).setCipherAlgorithm(CipherAlgorithm.aes256); - aehVerifier.setHashAlgorithm(HashAlgorithm.sha512); - - Encryptor enc = eiNew.getEncryptor(); - enc.confirmPassword("Test001!!", - infoOrig.getDecryptor().getSecretKey().getEncoded(), - infoOrig.getHeader().getKeySalt(), - infoOrig.getDecryptor().getVerifier(), - infoOrig.getVerifier().getSalt(), - infoOrig.getDecryptor().getIntegrityHmacKey() - ); - - final byte[] epNewBytes; - final EncryptionInfo infoReload; - try (POIFSFileSystem fsNew = new POIFSFileSystem()) { - try (OutputStream os = enc.getDataStream(fsNew)) { - os.write(zipInput); - } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - fsNew.writeFilesystem(bos); - - try (POIFSFileSystem fsReload = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) { - infoReload = new EncryptionInfo(fsReload); - try (InputStream epReload = fsReload.getRoot().createDocumentInputStream("EncryptedPackage")) { - epNewBytes = IOUtils.toByteArray(epReload, 9400); - } - } - } - - assertArrayEquals(epOrigBytes, epNewBytes); - - Decryptor decReload = infoReload.getDecryptor(); - assertTrue(decReload.verifyPassword("Test001!!")); - - AgileEncryptionHeader aehOrig = (AgileEncryptionHeader)infoOrig.getHeader(); - AgileEncryptionHeader aehReload = (AgileEncryptionHeader)infoReload.getHeader(); - assertEquals(aehOrig.getBlockSize(), aehReload.getBlockSize()); - assertEquals(aehOrig.getChainingMode(), aehReload.getChainingMode()); - assertEquals(aehOrig.getCipherAlgorithm(), aehReload.getCipherAlgorithm()); - assertEquals(aehOrig.getCipherProvider(), aehReload.getCipherProvider()); - assertEquals(aehOrig.getCspName(), aehReload.getCspName()); - assertArrayEquals(aehOrig.getEncryptedHmacKey(), aehReload.getEncryptedHmacKey()); - // this only works, when the paddings are mocked to be the same ... - // assertArrayEquals(aehOrig.getEncryptedHmacValue(), aehReload.getEncryptedHmacValue()); - assertEquals(aehOrig.getFlags(), aehReload.getFlags()); - assertEquals(aehOrig.getHashAlgorithm(), aehReload.getHashAlgorithm()); - assertArrayEquals(aehOrig.getKeySalt(), aehReload.getKeySalt()); - assertEquals(aehOrig.getKeySize(), aehReload.getKeySize()); - - AgileEncryptionVerifier aevOrig = (AgileEncryptionVerifier)infoOrig.getVerifier(); - AgileEncryptionVerifier aevReload = (AgileEncryptionVerifier)infoReload.getVerifier(); - assertEquals(aevOrig.getBlockSize(), aevReload.getBlockSize()); - assertEquals(aevOrig.getChainingMode(), aevReload.getChainingMode()); - assertEquals(aevOrig.getCipherAlgorithm(), aevReload.getCipherAlgorithm()); - assertArrayEquals(aevOrig.getEncryptedKey(), aevReload.getEncryptedKey()); - assertArrayEquals(aevOrig.getEncryptedVerifier(), aevReload.getEncryptedVerifier()); - assertArrayEquals(aevOrig.getEncryptedVerifierHash(), aevReload.getEncryptedVerifierHash()); - assertEquals(aevOrig.getHashAlgorithm(), aevReload.getHashAlgorithm()); - assertEquals(aevOrig.getKeySize(), aevReload.getKeySize()); - assertArrayEquals(aevOrig.getSalt(), aevReload.getSalt()); - assertEquals(aevOrig.getSpinCount(), aevReload.getSpinCount()); - - AgileDecryptor adOrig = (AgileDecryptor)infoOrig.getDecryptor(); - AgileDecryptor adReload = (AgileDecryptor)infoReload.getDecryptor(); - - assertArrayEquals(adOrig.getIntegrityHmacKey(), adReload.getIntegrityHmacKey()); - // doesn't work without mocking ... see above - // assertArrayEquals(adOrig.getIntegrityHmacValue(), adReload.getIntegrityHmacValue()); - assertArrayEquals(adOrig.getSecretKey().getEncoded(), adReload.getSecretKey().getEncoded()); - assertArrayEquals(adOrig.getVerifier(), adReload.getVerifier()); - } - - @Test - void smallFile() throws IOException, GeneralSecurityException { - // see https://stackoverflow.com/questions/61463301 - final int tinyFileSize = 80_000_000; - final String pass = "s3cr3t"; - - File tmpFile = TempFile.createTempFile("tiny", ".bin"); - - // create/populate empty file - try (POIFSFileSystem poifs = new POIFSFileSystem(); - FileOutputStream fos = new FileOutputStream(tmpFile)) { - poifs.writeFilesystem(fos); - } - - EncryptionInfo info1 = new EncryptionInfo(EncryptionMode.agile); - Encryptor enc = info1.getEncryptor(); - enc.confirmPassword(pass); - - final MessageDigest md = getMessageDigest(HashAlgorithm.sha256); - - // reopen as mmap-ed file - try (POIFSFileSystem poifs = new POIFSFileSystem(tmpFile, false)) { - try (OutputStream os = enc.getDataStream(poifs); - RandomStream rs = new RandomStream(md)) { - IOUtils.copy(rs, os, tinyFileSize); - } - poifs.writeFilesystem(); - } - - final byte[] digest1 = md.digest(); - md.reset(); - - // reopen and check the digest - try (POIFSFileSystem poifs = new POIFSFileSystem(tmpFile)) { - EncryptionInfo info2 = new EncryptionInfo(poifs); - Decryptor dec = info2.getDecryptor(); - boolean passOk = dec.verifyPassword(pass); - assertTrue(passOk); - - try (InputStream is = dec.getDataStream(poifs); - DigestInputStream dis = new DigestInputStream(is, md); - NullOutputStream nos = new NullOutputStream()) { - IOUtils.copy(dis, nos); - } - } - - final byte[] digest2 = md.digest(); - assertArrayEquals(digest1, digest2); - - boolean isDeleted = tmpFile.delete(); - assertTrue(isDeleted); - } - - private static final class RandomStream extends InputStream { - private final Random rand = new Random(); - private final byte[] buf = new byte[1024]; - private final MessageDigest md; - - private RandomStream(MessageDigest md) { - this.md = md; - } - - @Override - public int read() { - int ret = rand.nextInt(256); - md.update((byte)ret); - return ret; - } - - @Override - public int read(byte[] b, final int off, int len) { - for (int start = off; start-off < len; start += buf.length) { - rand.nextBytes(buf); - int copyLen = Math.min(buf.length, len-(start-off)); - System.arraycopy(buf, 0, b, start, copyLen); - md.update(buf, 0, copyLen); - } - return len; - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java deleted file mode 100644 index bf5aebb590..0000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java +++ /dev/null @@ -1,215 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.crypt.tests; - -import static org.apache.poi.POIDataSamples.getDocumentInstance; -import static org.apache.poi.POIDataSamples.getSlideShowInstance; -import static org.apache.poi.POIDataSamples.getSpreadSheetInstance; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -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.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.stream.Stream; - -import org.apache.poi.hssf.model.WorkbookRecordList; -import org.apache.poi.hssf.record.FilePassRecord; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POIDocument; -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.extractor.POITextExtractor; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.binaryrc4.BinaryRC4EncryptionHeader; -import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionHeader; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -class TestHxxFEncryption { - public static Stream<Arguments> data() throws IOException { - final String base64 = - "H4sIAAAAAAAAAF1Uu24bMRDs/RULVwkgCUhSpHaZwkDgpHJH8fZ0G/Nx4ZI6y13yG/mRfIb9R5mlZFlIpdPtcnZmdnjPf57/vvx6+f3h6obuv3"+ - "ylbY5bEiVHe1fEpUp5pOgkrK0iabehm7FyoZi1ks8xcvHiQu8h5bLnorTlnUvkJ/YPOHKsLVInAqCs91KakuaxLq4w3g00SgCo9Xou1UnCmSBe"+ - "MhpRY6qHmXVFteQfQJ5yUaaOw4qXwgPVjPGAqhNH5bBHAfTmwqqoSkLdFT/J3nC0eZBRk7yiu5s7yoU+r+9l3tDtm5A3jgt6AQxNOY2ya+U4sK"+ - "XZ+YczbpfSVVuzFOuunKraqIVD2ND3yVXauT3TNthR/O3IJAM7gzTOGeIcXZvj14ahotW8wSognlMu0Yyp/Fi7O6s+CK6haUUjtPCji7MVcgqH"+ - "jh+42tqeqPDMroJ/lBAE4AZbJbJu6Fu35ej42Tw9mYeTwVXoBKJiPeFV94q2rZJAyNEPo/qOdWYLBpq3B2JX8GDZeJ14mZf3tOQWBmpd9yQ7kI"+ - "DCY/jmkj1oGOicFy62r9vutC5uJsVEMFgmAXXfYcC6BRBKNHCybALFJolnrDcPXNLl+K60Vctt09YZT7YgbeOICGJ/ZgC2JztOnm1JhX3eJXni"+ - "U5Bqhezzlu334vD/Ajr3yDGXw5G9IZ6aLmLfQafY42N3J7cjj1LaXOHihSrcC5ThmuYIB5FX5AU8tKlnNG9Dn1EnsdD4KcnPhsSNPRiXtz461b"+ - "VZw8Pm6vn0afh4fvr0D5P/+cMuBAAA"; - final String x = new String(RawDataUtil.decompress(base64), StandardCharsets.UTF_8); - - return Stream.of( - // binary rc4 - Arguments.of( getDocumentInstance(), "password_tika_binaryrc4.doc", "tika", "This is an encrypted Word 2007 File." ), - // cryptoapi - Arguments.of( getDocumentInstance(), "password_password_cryptoapi.doc", "password", "This is a test" ), - // binary rc4 - Arguments.of( getSpreadSheetInstance(), "password.xls", "password", x ), - // cryptoapi - Arguments.of( getSpreadSheetInstance(), "35897-type4.xls", "freedom", "Sheet1\nhello there!" ), - // cryptoapi (PPT only supports cryptoapi...) - Arguments.of( getSlideShowInstance(), "cryptoapi-proc2356.ppt", "crypto", "Dominic Salemno" ) - ); - } - - @ParameterizedTest - @MethodSource("data") - void extract(POIDataSamples sampleDir, String file, String password, String expected) throws IOException { - File f = sampleDir.getFile(file); - Biff8EncryptionKey.setCurrentUserPassword(password); - try (POITextExtractor te = ExtractorFactory.createExtractor(f)) { - String actual = te.getText().trim(); - assertEquals(expected, actual); - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } - - @ParameterizedTest - @MethodSource("data") - void changePassword(POIDataSamples sampleDir, String file, String password, String expected) throws IOException { - newPassword("test", sampleDir, file, password, expected); - } - - @ParameterizedTest - @MethodSource("data") - void removePassword(POIDataSamples sampleDir, String file, String password, String expected) throws IOException { - newPassword(null, sampleDir, file, password, expected); - } - - private void newPassword(String newPass, POIDataSamples sampleDir, String file, String password, String expected) throws IOException { - File f = sampleDir.getFile(file); - Biff8EncryptionKey.setCurrentUserPassword(password); - try (POITextExtractor te1 = ExtractorFactory.createExtractor(f)) { - Biff8EncryptionKey.setCurrentUserPassword(newPass); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (POIDocument doc = (POIDocument) te1.getDocument()) { - doc.write(bos); - } - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - try (POITextExtractor te2 = ExtractorFactory.createExtractor(bis)) { - String actual = te2.getText().trim(); - assertEquals(expected, actual); - } - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } - - /** changing the encryption mode and key size in poor mans style - see comments below */ - @ParameterizedTest - @MethodSource("data") - void changeEncryption(POIDataSamples sampleDir, String file, String password, String expected) throws IOException { - File f = sampleDir.getFile(file); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - Biff8EncryptionKey.setCurrentUserPassword(password); - try (POITextExtractor te1 = ExtractorFactory.createExtractor(f)) { - // first remove encryption - Biff8EncryptionKey.setCurrentUserPassword(null); - try (POIDocument doc = (POIDocument) te1.getDocument()) { - doc.write(bos); - } - // then use default setting, which is cryptoapi - String newPass = "newPass"; - try (POITextExtractor te2 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray()))) { - Biff8EncryptionKey.setCurrentUserPassword(newPass); - try (POIDocument doc = (POIDocument) te2.getDocument()) { - bos.reset(); - doc.write(bos); - } - } - // and finally update cryptoapi setting - try (POITextExtractor te3 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray())); - POIDocument doc = (POIDocument) te3.getDocument()) { - // need to cache data (i.e. read all data) before changing the key size - Class<?> clazz = doc.getClass(); - if ("HSLFSlideShow".equals(clazz.getSimpleName())) { - assertDoesNotThrow(() -> clazz.getDeclaredMethod("getPictureData").invoke(doc), - "either scratchpad jar is included and this should work or the clazz should be != HSLFSlideShowImpl"); - doc.getDocumentSummaryInformation(); - } - EncryptionInfo ei = doc.getEncryptionInfo(); - assertNotNull(ei); - assertTrue(ei.getHeader() instanceof CryptoAPIEncryptionHeader); - assertEquals(0x28, ei.getHeader().getKeySize()); - ei.getHeader().setKeySize(0x78); - bos.reset(); - doc.write(bos); - } - // check the setting - try (POITextExtractor te4 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray())); - POIDocument doc = (POIDocument) te4.getDocument()) { - EncryptionInfo ei = doc.getEncryptionInfo(); - assertNotNull(ei); - assertTrue(ei.getHeader() instanceof CryptoAPIEncryptionHeader); - assertEquals(0x78, ei.getHeader().getKeySize()); - } - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } - - @Test - public void changeEncryptionMode() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(10_000); - - try (HSSFWorkbook wb = new HSSFWorkbook()) { - wb.createSheet().createRow(1).createCell(1).setCellValue("Test"); - Biff8EncryptionKey.setCurrentUserPassword("test1"); - wb.write(bos); - } - - try (HSSFWorkbook wb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { - assertEquals(EncryptionMode.cryptoAPI, wb.getEncryptionMode()); - wb.setEncryptionMode(EncryptionMode.binaryRC4); - Biff8EncryptionKey.setCurrentUserPassword("test2"); - bos.reset(); - wb.write(bos); - } - - try (HSSFWorkbook wb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { - assertEquals(EncryptionMode.binaryRC4, wb.getEncryptionMode()); - wb.setEncryptionMode(null); - bos.reset(); - wb.write(bos); - } - - assertNull(Biff8EncryptionKey.getCurrentUserPassword()); - - try (HSSFWorkbook wb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { - assertNull(wb.getEncryptionMode()); - wb.setEncryptionMode(null); - assertEquals("Test", wb.getSheetAt(0).getRow(1).getCell(1).getStringCellValue()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestSecureTempZip.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestSecureTempZip.java deleted file mode 100644 index 7dbbbe3d2a..0000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/tests/TestSecureTempZip.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.crypt.tests; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; - -import javax.crypto.Cipher; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.util.ZipEntrySource; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.extractor.XSSFBEventBasedExcelExtractor; -import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.xmlbeans.XmlException; -import org.junit.jupiter.api.Test; - -class TestSecureTempZip { - - /** - * Test case for #59841 - this is an example on how to use encrypted temp files, - * which are streamed into POI opposed to having everything in memory - */ - @Test - void protectedTempZip() throws IOException, GeneralSecurityException, XmlException, OpenXML4JException { - File tikaProt = XSSFTestDataSamples.getSampleFile("protected_passtika.xlsx"); - FileInputStream fis = new FileInputStream(tikaProt); - POIFSFileSystem poifs = new POIFSFileSystem(fis); - EncryptionInfo ei = new EncryptionInfo(poifs); - Decryptor dec = ei.getDecryptor(); - boolean passOk = dec.verifyPassword("tika"); - assertTrue(passOk); - - // extract encrypted ooxml file and write to custom encrypted zip file - InputStream is = dec.getDataStream(poifs); - - // provide ZipEntrySource to poi which decrypts on the fly - ZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(is); - - // test the source - OPCPackage opc = OPCPackage.open(source); - String expected = "This is an Encrypted Excel spreadsheet."; - - XSSFEventBasedExcelExtractor extractor = new XSSFEventBasedExcelExtractor(opc); - extractor.setIncludeSheetNames(false); - String txt = extractor.getText(); - assertEquals(expected, txt.trim()); - - XSSFWorkbook wb = new XSSFWorkbook(opc); - txt = wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue(); - assertEquals(expected, txt); - - extractor.close(); - - wb.close(); - opc.close(); - source.close(); - poifs.close(); - fis.close(); - } - - /** - * Now try with xlsb. - */ - @Test - void protectedXLSBZip() throws IOException, GeneralSecurityException, XmlException, OpenXML4JException { - //The test file requires that JCE unlimited be installed. - //If it isn't installed, skip this test. - int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256"); - - File tikaProt = XSSFTestDataSamples.getSampleFile("protected_passtika.xlsb"); - FileInputStream fis = new FileInputStream(tikaProt); - POIFSFileSystem poifs = new POIFSFileSystem(fis); - EncryptionInfo ei = new EncryptionInfo(poifs); - Decryptor dec = ei.getDecryptor(); - boolean passOk = dec.verifyPassword("tika"); - assertTrue(passOk); - - // extract encrypted ooxml file and write to custom encrypted zip file - InputStream is = dec.getDataStream(poifs); - - // provide ZipEntrySource to poi which decrypts on the fly - ZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(is); - - // test the source - OPCPackage opc = OPCPackage.open(source); - String expected = "You can't see me"; - - XSSFBEventBasedExcelExtractor extractor = new XSSFBEventBasedExcelExtractor(opc); - extractor.setIncludeSheetNames(false); - String txt = extractor.getText(); - assertEquals(expected, txt.trim()); - - extractor.close(); - opc.close(); - poifs.close(); - fis.close(); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/SLCommonUtils.java b/src/ooxml/testcases/org/apache/poi/sl/tests/SLCommonUtils.java deleted file mode 100644 index 3c3d243db8..0000000000 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/SLCommonUtils.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.tests; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; - -public class SLCommonUtils { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - /** a generic way to open a sample slideshow document **/ - public static SlideShow<?,?> openSampleSlideshow(String sampleName) throws IOException { - try (InputStream is = _slTests.openResourceAsStream(sampleName)) { - return SlideShowFactory.create(is); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** - * Tests, if the scratchpad classes are on the classpath - * - * @return true, if only xslf is on the classpath, and false, if both classpaths - * (XSLF and HSLF) can be used/referenced - */ - public static boolean xslfOnly() { - try { - Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); - return false; - } catch (Exception e) { - return true; - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestFonts.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestFonts.java deleted file mode 100644 index bd5d190d69..0000000000 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestFonts.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.tests; - -import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.FontFormatException; -import java.awt.Graphics2D; -import java.awt.GraphicsEnvironment; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.common.usermodel.fonts.FontGroup; -import org.apache.poi.sl.draw.Drawable; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.apache.poi.sl.usermodel.TextBox; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - - -/** - * Test rendering - specific to font handling - */ -class TestFonts { - private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - private static final String JPTEXT = - "\u3061\u3087\u3063\u3068\u65E9\u3044\u3051\u3069T\u30B7\u30E3\u30C4\u304C\u7740\u305F\u304F\u306A" + - "\u308B\u5B63\u7BC0\u2661\u304A\u6BCD\u3055\u3093\u306E\u5F71\u97FF\u304B\u3001\u975E\u5E38\u306B" + - "\u6050\u7ADC\u304C\u5927\u597D\u304D\u3067\u3059\u3002\u3082\u3046\u98FC\u3044\u305F\u3044\u304F" + - "\u3089\u3044\u5927\u597D\u304D\u3067\u3059\u3002#\u30B8\u30E5\u30E9\u30B7\u30C3\u30AF\u30EF\u30FC" + - "\u30EB\u30C9 \u306E\u30E9\u30D7\u30C8\u30EB4\u59C9\u59B9\u3068\u304B\u6FC0\u7684\u306B\u53EF\u611B" + - "\u304F\u3066\u53EF\u611B\u304F\u3066\u53EF\u611B\u304F\u3066\u53EF\u611B\u3044\u3067\u3059\u3002" + - "\u3081\u308D\u3081\u308D\u3001\u5927\u597D\u304D\u2661\u304A\u6BCD\u3055\u3093\u3082\u6050\u7ADC" + - "\u304C\u597D\u304D\u3067\u3001\u5C0F\u3055\u3044\u9803\u3001\u53E4\u4EE3\u751F\u7269\u306E\u56F3" + - "\u9451\u3092\u4E00\u7DD2\u306B\u898B\u3066\u305F\u306E\u601D\u3044\u51FA\u3059\u301C\u3068\u3044"; - - private static final String[] INIT_FONTS = {"mona.ttf"}; - - @BeforeAll - public static void initGE() throws FontFormatException, IOException { - GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); - for (String s : INIT_FONTS) { - Font font = Font.createFont(Font.TRUETYPE_FONT, _slTests.getFile(s)); - ge.registerFont(font); - } - } - - @Test - void resizeToFitTextHSLF() throws IOException { - assumeFalse(xslfOnly()); - SlideShow<?,?> ppt = SlideShowFactory.create(false); - resizeToFitText(ppt); - ppt.close(); - } - - @Test - void resizeToFitTextXSLF() throws IOException { - SlideShow<?,?> ppt = new XMLSlideShow(); - resizeToFitText(ppt); - ppt.close(); - } - - private void resizeToFitText(SlideShow<?,?> slideshow) throws IOException { - Slide<?,?> sld = slideshow.createSlide(); - TextBox<?,?> tb = sld.createTextBox(); - tb.setAnchor(new Rectangle(50, 50, 200, 50)); - tb.setStrokeStyle(Color.black, LineDash.SOLID, 3); - tb.setText(JPTEXT); - - setFont(tb, "NoSuchFont", FontGroup.LATIN); - - Dimension pgsize = slideshow.getPageSize(); - int width = (int)pgsize.getWidth(); - int height = (int)pgsize.getHeight(); - - BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = img.createGraphics(); - - Map<String,String> fallbackMap = new HashMap<>(); - fallbackMap.put("NoSuchFont", "Mona"); - // in XSLF the fonts default to the theme fonts (Calibri), if the font group is not overridden - // see XSLFTextRun.XSLFTextInfo.getCTTextFont - fallbackMap.put("Calibri", "Mona"); - graphics.setRenderingHint(Drawable.FONT_FALLBACK, fallbackMap); - graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - - tb.resizeToFitText(graphics); - graphics.dispose(); - - Rectangle2D anc = tb.getAnchor(); - // ignore font metrics differences on windows / linux (... hopefully ...) - int tbHeight = (int)anc.getHeight(); - assertTrue(tbHeight > 100); - } - - private void setFont(TextBox<?,?> tb, String fontFamily, FontGroup fontGroup) { - // TODO: set east asian font family - MS Office uses "MS Mincho" or "MS Gothic" as a fallback - // see https://stackoverflow.com/questions/26063828 for good explanation about the font metrics - // differences on different environments - for (TextParagraph<?,?,? extends TextRun> p : tb.getTextParagraphs()) { - for (TextRun r : p.getTextRuns()) { - r.setFontFamily(fontFamily, fontGroup); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestHeadersFooters.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestHeadersFooters.java deleted file mode 100644 index bd0d0ccb85..0000000000 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestHeadersFooters.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.tests; - -import static org.apache.poi.sl.tests.SLCommonUtils.openSampleSlideshow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextShape; -import org.junit.jupiter.api.Test; - -class TestHeadersFooters { - @Test - void bug58144c() throws IOException { - SlideShow<?,?> ppt = openSampleSlideshow("bug58144-headers-footers-2007.pptx"); - testSlideShow(ppt); - ppt.close(); - } - - private void testSlideShow(SlideShow<?,?> ppt) { - Slide<?,?> sl = ppt.getSlides().get(0); - - List<? extends Shape<?,?>> shapes = sl.getShapes(); - TextShape<?,?> ts0 = (TextShape<?,?>)shapes.get(0); - assertEquals("Test file", ts0.getText()); - TextShape<?,?> ts1 = (TextShape<?,?>)shapes.get(1); - assertEquals("Has some text in the headers and footers", ts1.getText()); - TextShape<?,?> ts2 = (TextShape<?,?>)shapes.get(2); - assertEquals("Slide footer", ts2.getText()); - List<? extends TextParagraph<?,?,?>> ltp = ts2.getTextParagraphs(); - assertTrue(ltp.get(0).isHeaderOrFooter()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestOleShape.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestOleShape.java deleted file mode 100644 index bda636d2ad..0000000000 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestOleShape.java +++ /dev/null @@ -1,212 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.tests; - -import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly; -import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.EXCEL_V12; -import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.EXCEL_V8; -import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.PDF; -import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.WORD_V12; -import static org.apache.poi.sl.usermodel.ObjectMetaData.Application.WORD_V8; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.stream.Stream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POIDocument; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.apache.poi.sl.usermodel.ObjectMetaData; -import org.apache.poi.sl.usermodel.ObjectShape; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -class TestOleShape { - private static final String PDF_SAMPLE = - "H4sIAAAAAAAAAJWUezRUWxzHe+o2FXncVtxLpxi3FPOeKYspjMdM5J1S4TTOaDIzxzpzJo9CUrnrSiUxIeT" + - "9jB7yqInihrhepTwqt1AT5VZCC7XcY0LWcv+5Z521zz6fvX+/vb/7t9cX78CyMiQZ0XD4W4OFEzgKQATgg4" + - "dxJiYAwRYS+aCHACqGnHAAABCs+AIUQrCvAEQhFsSFvSEck4kTowgECnEBl6E4OxGesfLkl2Bc0g5V/MCHt" + - "duqroTFC27YIKGAp+OL5Ou1SsmebA1XvciLk+Ucg84aLclQZhRZmh0amrG9Ina4t7Lh+ZCAHyezsg/NXsZg" + - "vuPw8NIedsrI2sZlz2vfhLkZfIgfMr4zFvTrmfbRgMmPw1UTvWk+r4MCZfLtj2WPPStVJ0P2PiKkxo+YnJ5" + - "Ua7v5UnefkB9ev0vSR37a8NrsC2lApaLp7086wS3Lzi2LqB3TMW2POrdRRUYMFYWs8vBo/kSQ6dYXpR6rxM" + - "UXM0vqu4arpe5dha7XS5MYS5P1arVG653sb8pXqReVw/TfjK8R3q4Z7X7Uk9dZ2Bcl8Wpmsl80Xf1QTOxe3" + - "Nutwus0kYge1LoHvgKLbc/f6WvdcsBfS9ctU3vSaneHNm0w/uhrm0Zett5O83s2xh2Gm8WZfWJ+/CNWruZ2" + - "cap8tR2/U9bAfRBbYt3PL9jvb3+0usqSF6vfrFuEq8Hf6jgrx/fERpZJEjKbHtJ11jCdUwI7Oc8QrmZf2pr" + - "L43WJn1mlT1ydV+QbrndcdN3qSEnicVhmoJyfWyprUEsIZlPyvi0tiEy7FzkOnqlE/qC6xFSpyg0E8tODa7" + - "qiKX61hMxRkZt73ITLWIHwtZtj71NbS4/BgKHnssOMcXOp1aacX4A//V+VFN4TWl6QryxdkcAp79BZcipmP" + - "OWOWkS6KhqUWlG+yCCxVMMtfW+9e56++gKHYEs9PNJztTI6KtyfOCDPOBppt3udRs3NpGrKfrs3i3Nivtrs" + - "VTl5LFerXZlTbf5XumbeYsOfwnve5ksEjKy6s1Z78rpbeJq7biTdzWwU3vhZ1GqkYb9D+t6mYvWLhXn6FWi" + - "c60VWpbBtVYHLQkmbh6Txwm6Ul3LbNW/Hs5FtLnlNX3fsAX2jPdlOI5W3HDIcm2MyNiR39rdyHlpwusjoOj" + - "I3IKfgPMILSzHZInmQaWyUFXEi0bHsCLX8pm9Gzl2vou7E3rrkPYdt1EwW3R5Qcg8rwzk88c1p13l8v+WkY" + - "75FHeS7XrvRsHgLy+wfr2EBRfNJ/4UVhUrihRqDktXciPGxWv1eXs396/0lqWG3YtU/A+D90hrT46cumSUN" + - "rBdG0G2Knn3T9Kw0X96vbhxMyr92uqUNOa4aEnGqP8us6GULm7mIyFKuxnOW2MZEEuKXmOpxnnqlwiMn+ju" + - "Xu+inC5mpG9oesxKkhcJq9bra5vR3H7l10hGbAxqu6t0LvHzaDnPIp/zeu0iXj1NNtVc+cMyUsH18u7TGXJ" + - "XiL4W3tqaL2mq6zkgXWB6kOTB3RxW8PHAOvzfaufDptdg7qmZlEcrUzbd5jKtVb85Sr9jaMT8a3y2Q30+3/" + - "FrsfGZDblh/mYnHhCg3ekm2q1JIYEVCd9rv42PNb9RFpuSsa4MNE0GfdSYDv6lsudikg4NE3tNugfWmfIY6" + - "7TeYvZCItG0zmDxrQwrjsQxArZ1RzHSA72CKgURgyqQszAASQOCCWItZETaAtdg7nYc2x85cAv0ggOAA+kC" + - "KnA4gAolQLGzG3ewgbz5oDgcA+zBEBEhUkhGDQiZvpc3tHlBMtYBFKBYsBiiz0dYILPGbs73vqynoDHLGKA" + - "KKxH5TK3MDZzAbQBEJNPNngc1iQUf4XMjJ2nxazxR3gsSwBOFCYoCsWPOHRtJ/ahQronbyvcWYnqljcJrdu" + - "2RK9pwE9DkJLLDioDACbOSCfAQGSEYkqhGJCGw8hKJ+xgSCgvogoN8hPldsBCM+mzZ9P0wE9pZwof8V92MD" + - "jHkKLEAUFMA+04XC1EzX6UdMAALxcERgK444+wB0Go1CA3jANCNRGdj1UoyIZhlpPsMobf48GmkeI1Pp8xi" + - "Nsm0eo9O3/mAoAvIFEKIQ58wPgrAtK+oJwyjAmL0+bBEPBugzGsUoiKAKhSQGmYjD4y3trXD/AmBc9IeqBwAA"; - - enum Api { HSLF, XSLF } - - - private static File pictureFile; - - @BeforeAll - public static void initPicture() { - pictureFile = POIDataSamples.getSlideShowInstance().getFile("wrench.emf"); - } - - public static Stream<Arguments> data() { - return Stream.of( - Arguments.of( Api.HSLF, EXCEL_V8 ), - Arguments.of( Api.HSLF, WORD_V8 ), - Arguments.of( Api.HSLF, PDF ), - Arguments.of( Api.XSLF, EXCEL_V12 ), - Arguments.of( Api.XSLF, WORD_V12 ), - Arguments.of( Api.XSLF, PDF ) - ); - } - - @ParameterizedTest - @MethodSource("data") - void embedData(Api api, ObjectMetaData.Application app) throws IOException, ReflectiveOperationException { - final ByteArrayInputStream pptBytes; - try (SlideShow<?,?> ppt = createSlideShow(api)) { - final PictureData picData = ppt.addPicture(pictureFile, PictureType.EMF); - final Slide<?,?> slide = ppt.createSlide(); - final ObjectShape<?,?> oleShape = slide.createOleShape(picData); - oleShape.setAnchor(new Rectangle2D.Double(100,100,100,100)); - try (OutputStream os = oleShape.updateObjectData(app, null)) { - fillOleData(app, os); - } - final ByteArrayOutputStream bos = new ByteArrayOutputStream(50000); - ppt.write(bos); - pptBytes = new ByteArrayInputStream(bos.toByteArray()); - } - try (SlideShow<?,?> ppt = SlideShowFactory.create(pptBytes)) { - final ObjectShape<?,?> oleShape = (ObjectShape<?,?>)ppt.getSlides().get(0).getShapes().get(0); - try (InputStream bis = oleShape.readObjectData()) { - validateOleData(app, bis); - } - } - } - - private SlideShow<?,?> createSlideShow(Api api) throws IOException { - if (api == Api.XSLF) { - return new XMLSlideShow(); - } else { - assumeFalse(xslfOnly()); - return SlideShowFactory.create(false); - } - } - - - private void fillOleData(ObjectMetaData.Application app, final OutputStream out) throws IOException { - switch (app) { - case EXCEL_V8: - case EXCEL_V12: - try (Workbook wb = (app == EXCEL_V12) ? new XSSFWorkbook() : new HSSFWorkbook()) { - wb.createSheet().createRow(0).createCell(0).setCellValue("test me"); - wb.write(out); - } - break; - case WORD_V8: - try (InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream("simple.doc")) { - IOUtils.copy(is, out); - } - break; - case WORD_V12: - try (XWPFDocument doc = new XWPFDocument()) { - doc.createParagraph().createRun().setText("Test me"); - doc.write(out); - } - break; - case PDF: - out.write(RawDataUtil.decompress(PDF_SAMPLE)); - break; - default: - case CUSTOM: - fail("not implemented"); - break; - } - } - - private void validateOleData(ObjectMetaData.Application app, final InputStream in) throws IOException, ReflectiveOperationException { - switch (app) { - case EXCEL_V8: - case EXCEL_V12: - try (Workbook wb = WorkbookFactory.create(in)) { - assertEquals("test me", wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); - } - break; - case WORD_V8: - @SuppressWarnings("unchecked") - Class<? extends POIDocument> clazz = (Class<? extends POIDocument>)Class.forName("org.apache.poi.hwpf.HWPFDocument"); - Constructor<? extends POIDocument> con = clazz.getDeclaredConstructor(InputStream.class); - Method m = clazz.getMethod("getDocumentText"); - try (POIDocument doc = con.newInstance(in)) { - assertEquals("This is a simple file created with Word 97-SR2.\r", m.invoke(doc)); - } - break; - case WORD_V12: - try (XWPFDocument doc = new XWPFDocument(in)) { - assertEquals("Test me", doc.getParagraphs().get(0).getText()); - } - break; - case PDF: - final byte[] expected = RawDataUtil.decompress(PDF_SAMPLE); - final byte[] actual = IOUtils.toByteArray(in); - assertArrayEquals(expected, actual); - break; - default: - case CUSTOM: - fail("not implemented"); - break; - } - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestSlide.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestSlide.java deleted file mode 100644 index eb066e4688..0000000000 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestSlide.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.tests; - -import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.junit.jupiter.api.Test; - -class TestSlide { - - @Test - void hideHSLF() throws IOException { - assumeFalse(xslfOnly()); - try (SlideShow<?,?> ppt1 = SlideShowFactory.create(false)) { - hideSlide(ppt1); - } - } - - @Test - void hideXSLF() throws IOException { - try (SlideShow<?,?> ppt1 = new XMLSlideShow()) { - hideSlide(ppt1); - } - } - - private void hideSlide(SlideShow<?,?> ppt1) throws IOException { - ppt1.createSlide().setHidden(true); - ppt1.createSlide(); - - try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { - ppt1.write(bos); - - try (InputStream is = new ByteArrayInputStream(bos.toByteArray()); - SlideShow<?, ?> ppt2 = SlideShowFactory.create(is)) { - - Boolean[] hiddenState = ppt2.getSlides().stream().map(Slide::isHidden).toArray(Boolean[]::new); - - assertTrue(hiddenState[0]); - assertFalse(hiddenState[1]); - - } - } - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/TestTable.java b/src/ooxml/testcases/org/apache/poi/sl/tests/TestTable.java deleted file mode 100644 index cedb11eed0..0000000000 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/TestTable.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.tests; - -import static org.apache.poi.sl.tests.SLCommonUtils.openSampleSlideshow; -import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly; -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.sl.usermodel.TableCell; -import org.apache.poi.sl.usermodel.TableShape; -import org.apache.poi.sl.usermodel.TextShape.TextDirection; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.junit.jupiter.api.Test; - -class TestTable { - - @Test - void colWidthRowHeight() throws IOException { - assumeFalse(xslfOnly()); - - // Test of table dimensions of same slideshow saved as ppt/x - // to check if both return similar (points) value - SlideShow<?,?> ppt = openSampleSlideshow("table_test.ppt"); - TableShape<?,?> ts = (TableShape<?,?>)ppt.getSlides().get(0).getShapes().get(0); - - SlideShow<?,?> pptx = openSampleSlideshow("table_test.pptx"); - TableShape<?,?> tsx = (TableShape<?,?>)pptx.getSlides().get(0).getShapes().get(0); - - // assume table shape should be equal to itself - confirmTableShapeEqual(ts, ts); - confirmTableShapeEqual(tsx, tsx); - - // assert ppt and pptx versions of the same table have the same shape - confirmTableShapeEqual(ts, tsx); - - // change row height and validate again - tsx.setRowHeight(1, 50); - ts.setRowHeight(1, 50); - confirmTableShapeEqual(ts, tsx); - - pptx.close(); - ppt.close(); - } - - private void confirmTableShapeEqual(TableShape<?,?> tableA, TableShape<?,?> tableB) { - int cols = tableA.getNumberOfColumns(); - int rows = tableA.getNumberOfRows(); - - int colsx = tableB.getNumberOfColumns(); - int rowsx = tableB.getNumberOfRows(); - - assertEquals(cols, colsx, "tables should have same number of columns"); - assertEquals(rows, rowsx, "tables should have same number of rows"); - - for (int i=0; i<cols; i++) { - assertEquals(tableA.getColumnWidth(i), tableB.getColumnWidth(i), 0.2, "Width of column " + i + " should be equal"); - } - - for (int i=0; i<rows; i++) { - assertEquals(tableA.getRowHeight(i), tableB.getRowHeight(i), 0.3, "Height of row " + i + " should be equal"); - } - } - - @Test - void directionHSLF() throws IOException { - assumeFalse(xslfOnly()); - SlideShow<?,?> ppt1 = SlideShowFactory.create(false); - testTextDirection(ppt1); - ppt1.close(); - } - - @Test - void directionXSLF() throws IOException { - SlideShow<?,?> ppt1 = new XMLSlideShow(); - testTextDirection(ppt1); - ppt1.close(); - } - - private void testTextDirection(SlideShow<?,?> ppt1) throws IOException { - - TextDirection[] tds = { - TextDirection.HORIZONTAL, - TextDirection.VERTICAL, - TextDirection.VERTICAL_270, - // TextDirection.STACKED is not supported on HSLF - }; - - TableShape<?,?> tbl1 = ppt1.createSlide().createTable(1, 3); - tbl1.setAnchor(new Rectangle2D.Double(50, 50, 200, 200)); - - int col = 0; - for (TextDirection td : tds) { - TableCell<?,?> c = tbl1.getCell(0, col++); - if (c != null) { - c.setTextDirection(td); - c.setText("bla"); - } - } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ppt1.write(bos); - ppt1.close(); - - InputStream is = new ByteArrayInputStream(bos.toByteArray()); - SlideShow<?,?> ppt2 = SlideShowFactory.create(is); - TableShape<?,?> tbl2 = (TableShape<?,?>)ppt2.getSlides().get(0).getShapes().get(0); - - col = 0; - for (TextDirection td : tds) { - TableCell<?,?> c = tbl2.getCell(0, col++); - assertEquals(td, c.getTextDirection()); - } - ppt2.close(); - } - - @Test - void tableSpan() throws IOException { - String[] files = (xslfOnly()) ? new String[]{"bug60993.pptx"} : new String[]{"bug60993.pptx", "bug60993.ppt"}; - for (String f : files) { - SlideShow<?,?> ppt = openSampleSlideshow(f); - Slide<?,?> slide = ppt.getSlides().get(0); - TableShape<?,?> ts = (TableShape<?,?>)slide.getShapes().get(0); - int cols = ts.getNumberOfColumns(); - int rows = ts.getNumberOfRows(); - for (int r=0; r<rows; r++) { - for (int c=0; c<cols; c++) { - TableCell<?,?> tc = ts.getCell(r, c); - int rc = r*10+c; - String msg = f+" (r"+r+",c"+c+")"; - switch (rc) { - case 22: - case 51: - if (f.endsWith("ppt")) { - assertNull(tc, msg); - } else { - assertNotNull(tc, msg); - assertTrue(tc.isMerged(), msg); - } - break; - case 21: - assertNotNull(tc, msg); - assertEquals(1, tc.getRowSpan(), msg); - assertEquals(2, tc.getGridSpan(), msg); - assertFalse(tc.isMerged(), msg); - break; - case 41: - assertNotNull(tc, msg); - assertEquals(2, tc.getRowSpan(), msg); - assertEquals(1, tc.getGridSpan(), msg); - assertFalse(tc.isMerged(), msg); - break; - default: - assertNotNull(tc, msg); - assertEquals(1, tc.getRowSpan(), msg); - assertEquals(1, tc.getGridSpan(), msg); - assertFalse(tc.isMerged(), msg); - break; - } - } - } - ppt.close(); - } - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/sl/tests/draw/TestDrawPictureShape.java b/src/ooxml/testcases/org/apache/poi/sl/tests/draw/TestDrawPictureShape.java deleted file mode 100644 index 9f5568c4c4..0000000000 --- a/src/ooxml/testcases/org/apache/poi/sl/tests/draw/TestDrawPictureShape.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.sl.tests.draw; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.awt.Dimension; -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.sl.draw.DrawPictureShape; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.PictureShape; -import org.apache.poi.sl.usermodel.RectAlign; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.util.Units; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -class TestDrawPictureShape { - static final POIDataSamples ssSamples = POIDataSamples.getSlideShowInstance(); - - private static boolean xslfOnly; - - @BeforeAll - public static void checkHslf() { - try { - Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); - } catch (Exception e) { - xslfOnly = true; - } - } - - /** a generic way to open a sample slideshow document **/ - public static SlideShow<?,?> openSampleDocument(String sampleName) throws IOException { - try (InputStream is = ssSamples.openResourceAsStream(sampleName)) { - return SlideShowFactory.create(is); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Test - void testResizeHSLF() throws IOException { - assumeFalse(xslfOnly); - testResize("pictures.ppt"); - } - - @Test - void testResizeXSLF() throws IOException { - testResize("shapes.pptx"); - } - - - void testResize(String file) throws IOException { - SlideShow<?,?> ss = openSampleDocument(file); - - Slide<?,?> slide = ss.getSlides().get(0); - PictureShape<?,?> picShape = null; - for (Shape<?,?> shape : slide.getShapes()) { - if (shape instanceof PictureShape) { - picShape = (PictureShape<?,?>)shape; - break; - } - } - assertNotNull(picShape); - PictureData pd = picShape.getPictureData(); - Dimension dimPd = pd.getImageDimension(); - new DrawPictureShape(picShape).resize(); - Dimension dimShape = new Dimension( - (int)picShape.getAnchor().getWidth(), - (int)picShape.getAnchor().getHeight() - ); - assertEquals(dimPd, dimShape); - - double newWidth = (dimPd.getWidth()*(100d/dimPd.getHeight())); - // ... -1 is a rounding error - Rectangle2D expRect = new Rectangle2D.Double(rbf(50+300-newWidth, picShape), 50, rbf(newWidth, picShape), 100); - Rectangle2D target = new Rectangle2D.Double(50,50,300,100); - new DrawPictureShape(picShape).resize(target, RectAlign.BOTTOM_RIGHT); - Rectangle2D actRect = picShape.getAnchor(); - assertEquals(expRect.getX(), actRect.getX(), .0001); - assertEquals(expRect.getY(), actRect.getY(), .0001); - assertEquals(expRect.getWidth(), actRect.getWidth(), .0001); - assertEquals(expRect.getHeight(), actRect.getHeight(), .0001); - ss.close(); - } - - // round back and forth - points -> master -> points - static double rbf(double val, PictureShape<?,?> picShape) { - if (picShape.getClass().getName().contains("HSLF")) { - return Units.masterToPoints(Units.pointsToMaster(val)); - } else { - return val; - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/TestWorkbookFactory.java b/src/ooxml/testcases/org/apache/poi/ss/tests/TestWorkbookFactory.java deleted file mode 100644 index 200407e3ef..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/TestWorkbookFactory.java +++ /dev/null @@ -1,354 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -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.ByteArrayInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.stream.Stream; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.EmptyFileException; -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.util.SuppressForbidden; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbookFactory; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -public final class TestWorkbookFactory { - private static final String xls = "SampleSS.xls"; - private static final String xlsx = "SampleSS.xlsx"; - private static final String[] xls_protected = new String[]{"password.xls", "password"}; - private static final String[] xlsx_protected = new String[]{"protected_passtika.xlsx", "tika"}; - private static final String txt = "SampleSS.txt"; - - private static final Logger LOGGER = LogManager.getLogger(TestWorkbookFactory.class); - - /** - * Closes the sample workbook read in from filename. - * Throws an exception if closing the workbook results in the file on disk getting modified. - * - * @param filename the sample workbook to read in - * @param wb the workbook to close - */ - private static void assertCloseDoesNotModifyFile(String filename, Workbook wb) throws IOException { - final byte[] before = HSSFTestDataSamples.getTestDataFileContent(filename); - // FIXME: replace with wb.close() when bug 58779 is resolved - closeOrRevert(wb); - final byte[] after = HSSFTestDataSamples.getTestDataFileContent(filename); - assertArrayEquals(before, after, filename + " sample file was modified as a result of closing the workbook"); - } - - /** - * bug 58779: Closing an XSSFWorkbook that was created with WorkbookFactory modifies the file - * FIXME: replace this method with wb.close() when bug 58779 is resolved. - * - * @param wb the workbook to close or revert - */ - private static void closeOrRevert(Workbook wb) throws IOException { - if (wb instanceof HSSFWorkbook) { - wb.close(); - } else if (wb instanceof XSSFWorkbook) { - final XSSFWorkbook xwb = (XSSFWorkbook) wb; - if (PackageAccess.READ == xwb.getPackage().getPackageAccess()) { - xwb.close(); - } else { - // TODO: close() re-writes the sample-file?! Resort to revert() for now to close file handle... - LOGGER.atWarn().log("reverting XSSFWorkbook rather than closing it to avoid close() modifying the file on disk. Refer to bug 58779."); - xwb.getPackage().revert(); - } - } else { - throw new RuntimeException("Unsupported workbook type"); - } - } - - @Test - void testCreateNative() throws Exception { - // POIFS -> hssf - try (Workbook wb = WorkbookFactory.create( - new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls)) - )) { - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - } - - try (Workbook wb = WorkbookFactory.create( - new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls)).getRoot() - )) { - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - } - - // Package -> xssf - try (Workbook wb = XSSFWorkbookFactory.createWorkbook( - OPCPackage.open(HSSFTestDataSamples.openSampleFileStream(xlsx)) - )) { - assertNotNull(wb); - //noinspection ConstantConditions - assertTrue(wb instanceof XSSFWorkbook); - } - } - - @Test - void testCreateReadOnly() throws Exception { - // POIFS -> hssf - try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xls), null, true)) { - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - } - - // Package -> xssf - try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xlsx), null, true)) { - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - } - } - - /** - * Creates the appropriate kind of Workbook, but - * checking the mime magic at the start of the - * InputStream, then creating what's required. - */ - @Test - void testCreateGeneric() throws Exception { - // InputStream -> either - try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.openSampleFileStream(xls))) { - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - } - - try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.openSampleFileStream(xlsx))) { - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - } - - // File -> either - try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xls))) { - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - } - - try (Workbook wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xlsx))) { - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - } - - // Invalid type -> exception - final byte[] before = HSSFTestDataSamples.getTestDataFileContent(txt); - assertThrows(IOException.class, () -> WorkbookFactory.create(new File(txt))); - final byte[] after = HSSFTestDataSamples.getTestDataFileContent(txt); - assertArrayEquals(before, after, "Invalid type file was modified after trying to open the file as a spreadsheet"); - } - - public static Stream<Arguments> workbookPass() { - return Stream.of( - // Unprotected, no password given, opens normally - Arguments.of(xls, null, false, HSSFWorkbook.class), - Arguments.of(xlsx, null, false, XSSFWorkbook.class), - // Unprotected, wrong password, opens normally - Arguments.of(xls, "wrong", false, HSSFWorkbook.class), - Arguments.of(xlsx, "wrong", false, XSSFWorkbook.class), - // Protected, correct password, opens fine - Arguments.of(xls_protected[0], xls_protected[1], false, HSSFWorkbook.class), - Arguments.of(xlsx_protected[0], xlsx_protected[1], false, XSSFWorkbook.class), - // Protected, wrong password, throws Exception - Arguments.of(xls_protected[0], "wrong", true, HSSFWorkbook.class), - Arguments.of(xlsx_protected[0], "wrong", true, XSSFWorkbook.class) - ); - } - - /** - * Check that the overloaded stream methods which take passwords work properly - */ - @ParameterizedTest - @MethodSource("workbookPass") - void testCreateWithPasswordFromStream(String file, String pass, boolean fails, Class<? extends Workbook> clazz) throws Exception { - try (InputStream is = HSSFTestDataSamples.openSampleFileStream(file)) { - if (fails) { - assertThrows(EncryptedDocumentException.class, () -> WorkbookFactory.create(is, pass), - "Shouldn't be able to open with the wrong password"); - } else { - try (Workbook wb = WorkbookFactory.create(is, pass)) { - assertNotNull(wb); - assertTrue(clazz.isInstance(wb)); - } - } - } - } - - /** - * Check that the overloaded file methods which take passwords work properly - */ - @ParameterizedTest - @MethodSource("workbookPass") - void testCreateWithPasswordFromFile(String fileName, String pass, boolean fails, Class<? extends Workbook> clazz) throws Exception { - File file = HSSFTestDataSamples.getSampleFile(fileName); - if (fails) { - assertThrows(EncryptedDocumentException.class, () -> WorkbookFactory.create(file, pass), - "Shouldn't be able to open with the wrong password"); - } else { - try (Workbook wb = WorkbookFactory.create(file, pass)) { - assertNotNull(wb); - assertTrue(clazz.isInstance(wb)); - assertCloseDoesNotModifyFile(fileName, wb); - } - } - } - - /** - * Check that a helpful exception is given on an empty input stream - */ - @Test - void testEmptyInputStream() { - InputStream emptyStream = new ByteArrayInputStream(new byte[0]); - assertThrows(EmptyFileException.class, () -> WorkbookFactory.create(emptyStream)); - } - - /** - * Check that a helpful exception is given on an empty file - */ - @Test - void testEmptyFile() throws Exception { - File emptyFile = TempFile.createTempFile("empty", ".poi"); - assertThrows(EmptyFileException.class, () -> WorkbookFactory.create(emptyFile), - "Shouldn't be able to create for an empty file"); - assertTrue(emptyFile.delete()); - } - - /** - * Check that a helpful exception is raised on a non-existing file - */ - @Test - void testNonExistingFile() { - File nonExistingFile = new File("notExistingFile"); - assertFalse(nonExistingFile.exists()); - assertThrows(FileNotFoundException.class, () -> WorkbookFactory.create(nonExistingFile, "password", true)); - } - - /** - * See Bugzilla bug #62831 - #WorkbookFactory.create(File) needs - * to work for sub-classes of File too, eg JFileChooser - */ - @Test - void testFileSubclass() throws Exception { - File normalXLS = HSSFTestDataSamples.getSampleFile(xls); - File normalXLSX = HSSFTestDataSamples.getSampleFile(xlsx); - File altXLS = new TestFile(normalXLS.getAbsolutePath()); - File altXLSX = new TestFile(normalXLSX.getAbsolutePath()); - assertTrue(altXLS.exists()); - assertTrue(altXLSX.exists()); - - try (Workbook wb = WorkbookFactory.create(altXLS)) { - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - closeOrRevert(wb); - } - - try (Workbook wb = WorkbookFactory.create(altXLSX)) { - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - closeOrRevert(wb); - } - } - - private static class TestFile extends File { - public TestFile(String file) { - super(file); - } - } - - /** - * Check that the overloaded file methods which take passwords work properly - */ - @Test - void testCreateEmpty() throws Exception { - Workbook wb = WorkbookFactory.create(false); - assertTrue(wb instanceof HSSFWorkbook); - closeOrRevert(wb); - - wb = WorkbookFactory.create(true); - assertTrue(wb instanceof XSSFWorkbook); - closeOrRevert(wb); - } - - @Test - @SuppressForbidden("test code") - void testOpenManyHSSF() throws Exception { - final int size = 1000; - ExecutorService executorService = Executors.newFixedThreadPool(10); - ArrayList<Future<Boolean>> futures = new ArrayList<>(size); - for (int i = 0; i < size; i++) { - futures.add(executorService.submit(this::openHSSFFile)); - } - for (Future<Boolean> future : futures) { - assertTrue(future.get()); - } - } - - @Test - void testInvalidFormatException() throws IOException { - String filename = "OPCCompliance_DerivedPartNameFAIL.docx"; - try (InputStream is = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename)) { - assertThrows(IOException.class, () -> WorkbookFactory.create(is)); - } - } - - private boolean openHSSFFile() { - try { - // POIFS -> hssf - try (InputStream is = HSSFTestDataSamples.openSampleFileStream(xls)) { - Workbook wb = WorkbookFactory.create(new POIFSFileSystem(is)); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - } - return true; - } catch (Exception e) { - return false; - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/extractor/TestEmbeddedExtractor.java b/src/ooxml/testcases/org/apache/poi/ss/tests/extractor/TestEmbeddedExtractor.java deleted file mode 100644 index ca3ec7d1fe..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/extractor/TestEmbeddedExtractor.java +++ /dev/null @@ -1,135 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.extractor; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; -import java.io.InputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.ss.extractor.EmbeddedData; -import org.apache.poi.ss.extractor.EmbeddedExtractor; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.junit.jupiter.api.Test; - -class TestEmbeddedExtractor { - private static final POIDataSamples samples = POIDataSamples.getSpreadSheetInstance(); - - @Test - void extractPDFfromEMF() throws Exception { - InputStream fis = samples.openResourceAsStream("Basic_Expense_Template_2011.xls"); - Workbook wb = WorkbookFactory.create(fis); - fis.close(); - - EmbeddedExtractor ee = new EmbeddedExtractor(); - List<EmbeddedData> edList = new ArrayList<>(); - for (Sheet s : wb) { - edList.addAll(ee.extractAll(s)); - } - wb.close(); - - assertEquals(2, edList.size()); - - String filename1 = "Sample.pdf"; - EmbeddedData ed0 = edList.get(0); - assertEquals(filename1, ed0.getFilename()); - assertEquals(filename1, ed0.getShape().getShapeName().trim()); - assertEquals("uNplB1QpYug+LWappiTh0w==", md5hash(ed0.getEmbeddedData())); - - String filename2 = "kalastuslupa_jiyjhnj_yuiyuiyuio_uyte_sldfsdfsdf_sfsdfsdf_sfsssfsf_sdfsdfsdfsdf_sdfsdfsdf.pdf"; - EmbeddedData ed1 = edList.get(1); - assertEquals(filename2, ed1.getFilename()); - assertEquals(filename2, ed1.getShape().getShapeName().trim()); - assertEquals("QjLuAZ+cd7KbhVz4sj+QdA==", md5hash(ed1.getEmbeddedData())); - } - - @Test - void extractFromXSSF() throws IOException, EncryptedDocumentException, InvalidFormatException { - InputStream fis = samples.openResourceAsStream("58325_db.xlsx"); - Workbook wb = WorkbookFactory.create(fis); - fis.close(); - - EmbeddedExtractor ee = new EmbeddedExtractor(); - List<EmbeddedData> edList = new ArrayList<>(); - for (Sheet s : wb) { - edList.addAll(ee.extractAll(s)); - } - wb.close(); - - assertEquals(4, edList.size()); - EmbeddedData ed0 = edList.get(0); - assertEquals("Object 1.pdf", ed0.getFilename()); - assertEquals("Object 1", ed0.getShape().getShapeName().trim()); - assertEquals("Oyys6UtQU1gbHYBYqA4NFA==", md5hash(ed0.getEmbeddedData())); - - EmbeddedData ed1 = edList.get(1); - assertEquals("Object 2.pdf", ed1.getFilename()); - assertEquals("Object 2", ed1.getShape().getShapeName().trim()); - assertEquals("xLScPUS0XH+5CTZ2A3neNw==", md5hash(ed1.getEmbeddedData())); - - EmbeddedData ed2 = edList.get(2); - assertEquals("Object 3.pdf", ed2.getFilename()); - assertEquals("Object 3", ed2.getShape().getShapeName().trim()); - assertEquals("rX4klZqJAeM5npb54Gi2+Q==", md5hash(ed2.getEmbeddedData())); - - EmbeddedData ed3 = edList.get(3); - assertEquals("Microsoft_Excel_Worksheet1.xlsx", ed3.getFilename()); - assertEquals("Object 1", ed3.getShape().getShapeName().trim()); - assertEquals("4m4N8ji2tjpEGPQuw2YwGA==", md5hash(ed3.getEmbeddedData())); - } - - public static String md5hash(byte[] input) { - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - byte[] hash = md.digest(input); - return Base64.getEncoder().encodeToString(hash); - } catch (NoSuchAlgorithmException e) { - // doesn't happen - throw new RuntimeException(e); - } - } - - - @Test - void testNPE() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("angelo.edu_content_files_19555-nsse-2011-multiyear-benchmark.xls"); - EmbeddedExtractor ee = new EmbeddedExtractor(); - - for (Sheet s : wb) { - for (EmbeddedData ed : ee.extractAll(s)) { - assertNotNull(ed.getFilename()); - assertNotNull(ed.getEmbeddedData()); - assertNotNull(ed.getShape()); - } - } - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/format/TestCellFormatPart.java b/src/ooxml/testcases/org/apache/poi/ss/tests/format/TestCellFormatPart.java deleted file mode 100644 index 8514542080..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/format/TestCellFormatPart.java +++ /dev/null @@ -1,209 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.tests.format; - -import static java.awt.Color.ORANGE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.awt.Color; -import java.io.IOException; -import java.util.Locale; -import java.util.TimeZone; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.swing.JLabel; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.format.CellFormat; -import org.apache.poi.ss.format.CellFormatPart; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -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.util.LocaleUtil; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Class for spreadsheet-based tests, such as are used for cell formatting. - * This reads tests from the spreadsheet, as well as reading - * flags that can be used to paramterize these tests. - * <p> - * Each test has four parts: The expected result (column A), the format string - * (column B), the value to format (column C), and a comma-separated list of - * categores that this test falls in. Normally all tests are run, but if the - * flag "Categories" is not empty, only tests that have at least one category - * listed in "Categories" are run. - */ -class TestCellFormatPart { - private static final Pattern NUMBER_EXTRACT_FMT = Pattern.compile( - "([-+]?[0-9]+)(\\.[0-9]+)?.*(?:(e).*?([+-]?[0-9]+))", - Pattern.CASE_INSENSITIVE); - private static final Color TEST_COLOR = ORANGE.darker(); - private static Locale userLocale; - - - - @BeforeAll - public static void setLocale() { - userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.UK); - } - - @AfterAll - public static void unsetLocale() { - LocaleUtil.setUserLocale(userLocale); - } - - private final ITestDataProvider _testDataProvider = XSSFITestDataProvider.instance; - - private interface CellValue { - Object getValue(Cell cell); - - default void equivalent(String expected, String actual, CellFormatPart format) { - assertEquals('"' + expected + '"', '"' + actual + '"', "format \"" + format + "\""); - } - } - - @Test - void testGeneralFormat() throws IOException { - runFormatTests("GeneralFormatTests.xlsx", cell -> { - assertNotNull(cell); - switch (CellFormat.ultimateType(cell)) { - case BOOLEAN: - return cell.getBooleanCellValue(); - case NUMERIC: - return cell.getNumericCellValue(); - default: - return cell.getStringCellValue(); - } - }); - } - - @Test - void testNumberFormat() throws IOException { - runFormatTests("NumberFormatTests.xlsx", Cell::getNumericCellValue); - } - - @Test - void testNumberApproxFormat() throws IOException { - runFormatTests("NumberFormatApproxTests.xlsx", new CellValue() { - @Override - public Object getValue(Cell cell) { - return cell.getNumericCellValue(); - } - - @Override - public void equivalent(String expected, String actual, - CellFormatPart format) { - double expectedVal = extractNumber(expected); - double actualVal = extractNumber(actual); - // equal within 1% - double delta = expectedVal / 100; - assertEquals(expectedVal, actualVal, delta, "format \"" + format + "\"," + expected + " ~= " + actual); - } - }); - } - - @Test - void testDateFormat() throws IOException { - TimeZone tz = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - try { - runFormatTests("DateFormatTests.xlsx", Cell::getDateCellValue); - } finally { - LocaleUtil.setUserTimeZone(tz); - } - } - - @Test - void testElapsedFormat() throws IOException { - runFormatTests("ElapsedFormatTests.xlsx", Cell::getNumericCellValue); - } - - @Test - void testTextFormat() throws IOException { - runFormatTests("TextFormatTests.xlsx", cell -> - (CellFormat.ultimateType(cell) == CellType.BOOLEAN) ? cell.getBooleanCellValue() : cell.getStringCellValue() - ); - } - - @Test - void testConditions() throws IOException { - runFormatTests("FormatConditionTests.xlsx", Cell::getNumericCellValue); - } - - private double extractNumber(String str) { - Matcher m = NUMBER_EXTRACT_FMT.matcher(str); - if (!m.find()) { - throw new IllegalArgumentException("Cannot find number in \"" + str + "\""); - } - - StringBuilder sb = new StringBuilder(); - // The groups in the pattern are the parts of the number - for (int i = 1; i <= m.groupCount(); i++) { - String part = m.group(i); - if (part != null) - sb.append(part); - } - return Double.parseDouble(sb.toString()); - } - - - protected void runFormatTests(String workbookName, CellValue valueGetter) throws IOException { - try (Workbook workbook = _testDataProvider.openSampleWorkbook(workbookName)) { - workbook.setMissingCellPolicy(Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); - - Sheet sheet = workbook.getSheet("Tests"); - boolean isHeader = true; - for (Row row : sheet) { - // Skip the header row - if (isHeader || row == null) { - isHeader = false; - continue; - } - String expectedText = row.getCell(0).getStringCellValue(); - String format = row.getCell(1).getStringCellValue(); - Cell value = row.getCell(2); - - if (expectedText.isEmpty() && format.isEmpty()) { - continue; - } - - Object objVal = valueGetter.getValue(value); - JLabel label = new JLabel(); - label.setForeground(TEST_COLOR); - label.setText("xyzzy"); - - Color origColor = label.getForeground(); - CellFormatPart cellFormatPart = new CellFormatPart(format); - // If this doesn't apply, no color change is expected - Color expectedColor = cellFormatPart.apply(label, objVal).applies ? TEST_COLOR : origColor; - - String actualText = label.getText(); - Color actualColor = label.getForeground(); - valueGetter.equivalent(expectedText, actualText, cellFormatPart); - assertEquals(expectedColor, actualColor, "no color"); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestFormulaParser.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestFormulaParser.java deleted file mode 100644 index 5d1c7d8e31..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestFormulaParser.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.ss.tests.formula; - -import static org.junit.jupiter.api.Assertions.assertEquals; -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 org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaParsingWorkbook; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.AbstractFunctionPtg; -import org.apache.poi.ss.formula.ptg.NameXPxg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.Ref3DPxg; -import org.apache.poi.ss.formula.ptg.StringPtg; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFEvaluationWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Test {@link FormulaParser}'s handling of row numbers at the edge of the - * HSSF/XSSF ranges. - * - * @author David North - */ -class TestFormulaParser { - - @Test - void testHSSFFailsForOver65536() { - FormulaParsingWorkbook workbook = HSSFEvaluationWorkbook.create(new HSSFWorkbook()); - assertThrows(FormulaParseException.class, () -> - FormulaParser.parse("Sheet1!1:65537", workbook, FormulaType.CELL, 0)); - } - - private static void checkHSSFFormula(String formula) { - HSSFWorkbook wb = new HSSFWorkbook(); - FormulaParsingWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - FormulaParser.parse(formula, workbook, FormulaType.CELL, 0); - IOUtils.closeQuietly(wb); - } - private static void checkXSSFFormula(String formula) { - XSSFWorkbook wb = new XSSFWorkbook(); - FormulaParsingWorkbook workbook = XSSFEvaluationWorkbook.create(wb); - FormulaParser.parse(formula, workbook, FormulaType.CELL, 0); - IOUtils.closeQuietly(wb); - } - private static void checkFormula(String formula) { - checkHSSFFormula(formula); - checkXSSFFormula(formula); - } - - @Test - void testHSSFPassCase() { - checkHSSFFormula("Sheet1!1:65536"); - } - - @Test - void testXSSFWorksForOver65536() { - checkXSSFFormula("Sheet1!1:65537"); - } - - @Test - void testXSSFFailCase() { - FormulaParsingWorkbook workbook = XSSFEvaluationWorkbook.create(new XSSFWorkbook()); - assertThrows(FormulaParseException.class, () -> - FormulaParser.parse("Sheet1!1:1048577", workbook, FormulaType.CELL, 0), "one more than max rows"); - } - - // copied from org.apache.poi.hssf.model.TestFormulaParser - @Test - void testMacroFunction() throws Exception { - // testNames.xlsm contains a VB function called 'myFunc' - final String testFile = "testNames.xlsm"; - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(testFile)) { - XSSFEvaluationWorkbook workbook = XSSFEvaluationWorkbook.create(wb); - - //Expected ptg stack: [NamePtg(myFunc), StringPtg(arg), (additional operands would go here...), FunctionPtg(myFunc)] - Ptg[] ptg = FormulaParser.parse("myFunc(\"arg\")", workbook, FormulaType.CELL, -1); - assertEquals(3, ptg.length); - - // the name gets encoded as the first operand on the stack - NameXPxg tname = (NameXPxg) ptg[0]; - assertEquals("myFunc", tname.toFormulaString()); - - // the function's arguments are pushed onto the stack from left-to-right as OperandPtgs - StringPtg arg = (StringPtg) ptg[1]; - assertEquals("arg", arg.getValue()); - - // The external FunctionPtg is the last Ptg added to the stack - // During formula evaluation, this Ptg pops off the the appropriate number of - // arguments (getNumberOfOperands()) and pushes the result on the stack - AbstractFunctionPtg tfunc = (AbstractFunctionPtg) ptg[2]; - assertTrue(tfunc.isExternalFunction()); - - // confirm formula parsing is case-insensitive - FormulaParser.parse("mYfUnC(\"arg\")", workbook, FormulaType.CELL, -1); - - // confirm formula parsing doesn't care about argument count or type - // this should only throw an error when evaluating the formula. - FormulaParser.parse("myFunc()", workbook, FormulaType.CELL, -1); - FormulaParser.parse("myFunc(\"arg\", 0, TRUE)", workbook, FormulaType.CELL, -1); - - // A completely unknown formula name (not saved in workbook) should still be parseable and renderable - // but will throw an NotImplementedFunctionException or return a #NAME? error value if evaluated. - FormulaParser.parse("yourFunc(\"arg\")", workbook, FormulaType.CELL, -1); - - // Make sure workbook can be written and read - XSSFTestDataSamples.writeOutAndReadBack(wb).close(); - - // Manually check to make sure file isn't corrupted - // TODO: develop a process for occasionally manually reviewing workbooks - // to verify workbooks are not corrupted - /* - final File fileIn = XSSFTestDataSamples.getSampleFile(testFile); - final File reSavedFile = new File(fileIn.getParentFile(), fileIn.getName().replace(".xlsm", "-saved.xlsm")); - final FileOutputStream fos = new FileOutputStream(reSavedFile); - wb.write(fos); - fos.close(); - */ - } - } - - @Test - void testParserErrors() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("testNames.xlsm")) { - XSSFEvaluationWorkbook workbook = XSSFEvaluationWorkbook.create(wb); - - parseExpectedException("("); - parseExpectedException(")"); - parseExpectedException("+"); - parseExpectedException("42+"); - parseExpectedException("IF()"); - parseExpectedException("IF("); //no closing paren - parseExpectedException("myFunc(", workbook); //no closing paren - } - } - - private static void parseExpectedException(String formula) { - parseExpectedException(formula, null); - } - - /** confirm formula has invalid syntax and parsing the formula results in FormulaParseException - */ - private static void parseExpectedException(String formula, FormulaParsingWorkbook wb) { - FormulaParseException e = assertThrows(FormulaParseException.class, () -> - FormulaParser.parse(formula, wb, FormulaType.CELL, -1)); - assertNotNull(e.getMessage()); - } - - // trivial case for bug 60219: FormulaParser can't parse external references when sheet name is quoted - @Test - void testParseExternalReferencesWithUnquotedSheetName() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpwb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs = FormulaParser.parse("[1]Sheet1!A1", fpwb, FormulaType.CELL, -1); - // org.apache.poi.ss.formula.ptg.Ref3DPxg [ [workbook=1] sheet=Sheet 1 ! A1] - assertEquals(1, ptgs.length, "Ptgs length"); - assertTrue(ptgs[0] instanceof Ref3DPxg, "Ptg class"); - Ref3DPxg pxg = (Ref3DPxg) ptgs[0]; - assertEquals(1, pxg.getExternalWorkbookNumber(), "External workbook number"); - assertEquals("Sheet1", pxg.getSheetName(), "Sheet name"); - assertEquals(0, pxg.getRow(), "Row"); - assertEquals(0, pxg.getColumn(), "Column"); - wb.close(); - } - - // bug 60219: FormulaParser can't parse external references when sheet name is quoted - @Test - void testParseExternalReferencesWithQuotedSheetName() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpwb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs = FormulaParser.parse("'[1]Sheet 1'!A1", fpwb, FormulaType.CELL, -1); - // org.apache.poi.ss.formula.ptg.Ref3DPxg [ [workbook=1] sheet=Sheet 1 ! A1] - assertEquals(1, ptgs.length, "Ptgs length"); - assertTrue(ptgs[0] instanceof Ref3DPxg, "Ptg class"); - Ref3DPxg pxg = (Ref3DPxg) ptgs[0]; - assertEquals(1, pxg.getExternalWorkbookNumber(), "External workbook number"); - assertEquals("Sheet 1", pxg.getSheetName(), "Sheet name"); - assertEquals(0, pxg.getRow(), "Row"); - assertEquals(0, pxg.getColumn(), "Column"); - wb.close(); - } - - // bug 60260 - @Test - void testUnicodeSheetName() { - checkFormula("'Sheet\u30FB1'!A1:A6"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestStructuredReferences.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestStructuredReferences.java deleted file mode 100644 index f169e7b69d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/TestStructuredReferences.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.formula; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Table; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFTable; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests Excel Table expressions (structured references) - * @see <a href="https://support.office.com/en-us/article/Using-structured-references-with-Excel-tables-F5ED2452-2337-4F71-BED3-C8AE6D2B276E"> - * Excel Structured Reference Syntax - * </a> - */ -class TestStructuredReferences { - - /** - * Test the regular expression used in INDIRECT() evaluation to recognize structured references - */ - @Test - void testTableExpressionSyntax() { - assertTrue(Table.isStructuredReference.matcher("abc[col1]").matches(), "Valid structured reference syntax didn't match expression"); - assertTrue(Table.isStructuredReference.matcher("_abc[col1]").matches(), "Valid structured reference syntax didn't match expression"); - assertTrue(Table.isStructuredReference.matcher("_[col1]").matches(), "Valid structured reference syntax didn't match expression"); - assertTrue(Table.isStructuredReference.matcher("\\[col1]").matches(), "Valid structured reference syntax didn't match expression"); - assertTrue(Table.isStructuredReference.matcher("\\[col1]").matches(), "Valid structured reference syntax didn't match expression"); - assertTrue(Table.isStructuredReference.matcher("\\[#This Row]").matches(), "Valid structured reference syntax didn't match expression"); - assertTrue(Table.isStructuredReference.matcher("\\[ [col1], [col2] ]").matches(), "Valid structured reference syntax didn't match expression"); - - // can't have a space between the table name and open bracket - assertFalse(Table.isStructuredReference.matcher("\\abc [ [col1], [col2] ]").matches(), "Invalid structured reference syntax didn't fail expression"); - } - - @Test - void testTableFormulas() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - - final FormulaEvaluator eval = new XSSFFormulaEvaluator(wb); - final XSSFSheet tableSheet = wb.getSheet("Table"); - final XSSFSheet formulaSheet = wb.getSheet("Formulas"); - - confirm(eval, tableSheet.getRow(5).getCell(0), 49); - confirm(eval, formulaSheet.getRow(0).getCell(0), 209); - confirm(eval, formulaSheet.getRow(1).getCell(0), "one"); - - // test changing a table value, to see if the caches are properly cleared - // Issue 59814 - - // this test passes before the fix for 59814 - tableSheet.getRow(1).getCell(1).setCellValue("ONEA"); - confirm(eval, formulaSheet.getRow(1).getCell(0), "ONEA"); - - // test adding a row to a table, issue 59814 - Row newRow = tableSheet.getRow(7); - if (newRow == null) newRow = tableSheet.createRow(7); - newRow.createCell(0, CellType.FORMULA).setCellFormula("\\_Prime.1[[#This Row],[@Number]]*\\_Prime.1[[#This Row],[@Number]]"); - newRow.createCell(1, CellType.STRING).setCellValue("thirteen"); - newRow.createCell(2, CellType.NUMERIC).setCellValue(13); - - // update Table - final XSSFTable table = wb.getTable("\\_Prime.1"); - final AreaReference newArea = wb.getCreationHelper().createAreaReference( - table.getStartCellReference(), - new CellReference(table.getEndRowIndex() + 1, table.getEndColIndex())); - String newAreaStr = newArea.formatAsString(); - table.getCTTable().setRef(newAreaStr); - table.getCTTable().getAutoFilter().setRef(newAreaStr); - table.updateHeaders(); - table.updateReferences(); - - // these fail before the fix for 59814 - confirm(eval, tableSheet.getRow(7).getCell(0), 13 * 13); - confirm(eval, formulaSheet.getRow(0).getCell(0), 209 + 13 * 13); - - } - } - - private static void confirm(FormulaEvaluator fe, Cell cell, double expectedResult) { - fe.clearAllCachedResultValues(); - CellValue cv = fe.evaluate(cell); - assertEquals(CellType.NUMERIC, cv.getCellType(), "expected numeric cell type but got " + cv.formatAsString()); - assertEquals(expectedResult, cv.getNumberValue(), 0.0); - } - - private static void confirm(FormulaEvaluator fe, Cell cell, String expectedResult) { - fe.clearAllCachedResultValues(); - CellValue cv = fe.evaluate(cell); - assertEquals(CellType.STRING, cv.getCellType(), "expected String cell type but got " + cv.formatAsString()); - assertEquals(expectedResult, cv.getStringValue()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/eval/TestXSSFCircularReferences.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/eval/TestXSSFCircularReferences.java deleted file mode 100644 index 114f70a13e..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/eval/TestXSSFCircularReferences.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.formula.eval; - -import org.apache.poi.ss.formula.eval.BaseTestCircularReferences; -import org.apache.poi.xssf.XSSFITestDataProvider; - -/** - * Tests XSSFFormulaEvaluator for its handling of cell formula circular references. - * - * @author Josh Micich - */ -public final class TestXSSFCircularReferences extends BaseTestCircularReferences { - public TestXSSFCircularReferences() { - super(XSSFITestDataProvider.instance); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestCountifs.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestCountifs.java deleted file mode 100644 index 902de11a80..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestCountifs.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.ss.tests.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.SheetUtil; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Test the COUNTIFS() function - */ -class TestCountifs { - - private Workbook workbook; - - /** - * initialize a workbook - */ - @BeforeEach - void before() { - // not sure why we allow this, COUNTIFS() is only available - // in OOXML, it was introduced with Office 2007 - workbook = new HSSFWorkbook(); - } - - /** - * Close the workbook if needed - */ - @AfterEach - void after() { - IOUtils.closeQuietly(workbook); - } - - /** - * Basic call - */ - @Test - void testCallFunction() { - Sheet sheet = workbook.createSheet("test"); - Row row1 = sheet.createRow(0); - Cell cellA1 = row1.createCell(0, CellType.FORMULA); - Cell cellB1 = row1.createCell(1, CellType.NUMERIC); - Cell cellC1 = row1.createCell(2, CellType.NUMERIC); - Cell cellD1 = row1.createCell(3, CellType.NUMERIC); - Cell cellE1 = row1.createCell(4, CellType.NUMERIC); - cellB1.setCellValue(1); - cellC1.setCellValue(1); - cellD1.setCellValue(2); - cellE1.setCellValue(4); - - cellA1.setCellFormula("COUNTIFS(B1:C1,1, D1:E1,2)"); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - CellValue evaluate = evaluator.evaluate(cellA1); - assertEquals(1.0d, evaluate.getNumberValue(), 0.000000000000001); - } - - /** - * Test argument count check - */ - @Test - void testCallFunction_invalidArgs() { - Sheet sheet = workbook.createSheet("test"); - Row row1 = sheet.createRow(0); - Cell cellA1 = row1.createCell(0, CellType.FORMULA); - cellA1.setCellFormula("COUNTIFS()"); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - CellValue evaluate = evaluator.evaluate(cellA1); - assertEquals(15, evaluate.getErrorValue()); - cellA1.setCellFormula("COUNTIFS(A1:C1)"); - evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - evaluate = evaluator.evaluate(cellA1); - assertEquals(15, evaluate.getErrorValue()); - cellA1.setCellFormula("COUNTIFS(A1:C1,2,2)"); - evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - evaluate = evaluator.evaluate(cellA1); - assertEquals(15, evaluate.getErrorValue()); - } - - /** - * the bug returned the wrong count, this verifies the fix - */ - @Test - void testBug56822() { - workbook = XSSFTestDataSamples.openSampleWorkbook("56822-Countifs.xlsx"); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - Cell cell = SheetUtil.getCell(workbook.getSheetAt(0), 0, 3); - assertNotNull(cell, "Test workbook missing cell D1"); - CellValue evaluate = evaluator.evaluate(cell); - assertEquals(2.0d, evaluate.getNumberValue(), 0.00000000000001); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestProper.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestProper.java deleted file mode 100644 index c1a80cb5a4..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestProper.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.TextFunction; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -public final class TestProper { - private Cell cell11; - private FormulaEvaluator evaluator; - - @Test - void testValidHSSF() { - HSSFWorkbook wb = new HSSFWorkbook(); - evaluator = new HSSFFormulaEvaluator(wb); - - confirm(wb); - } - - @Test - void testValidXSSF() { - XSSFWorkbook wb = new XSSFWorkbook(); - evaluator = new XSSFFormulaEvaluator(wb); - - confirm(wb); - } - - private void confirm(Workbook wb) { - Sheet sheet = wb.createSheet("new sheet"); - cell11 = sheet.createRow(0).createCell(0); - - confirm("PROPER(\"hi there\")", "Hi There"); //simple case - confirm("PROPER(\"what's up\")", "What'S Up"); //apostrophes are treated as word breaks - confirm("PROPER(\"I DON'T TH!NK SO!\")", "I Don'T Th!Nk So!"); //capitalization is ignored, special punctuation is treated as a word break - confirm("PROPER(\"dr\u00dcb\u00f6'\u00e4 \u00e9lo\u015f|\u00eb\u00e8 \")", "Dr\u00fcb\u00f6'\u00c4 \u00c9lo\u015f|\u00cb\u00e8 "); - confirm("PROPER(\"hi123 the123re\")", "Hi123 The123Re"); //numbers are treated as word breaks - confirm("PROPER(\"-\")", "-"); //nothing happens with ascii punctuation that is not upper or lower case - confirm("PROPER(\"!\u00a7$\")", "!\u00a7$"); //nothing happens with unicode punctuation (section sign) that is not upper or lower case - confirm("PROPER(\"/&%\")", "/&%"); //nothing happens with ascii punctuation that is not upper or lower case - confirm("PROPER(\"Apache POI\")", "Apache Poi"); //acronyms are not special - confirm("PROPER(\" hello world\")", " Hello World"); //leading whitespace is ignored - - final String scharfes = "\u00df"; //German lowercase eszett, scharfes s, sharp s - confirm("PROPER(\"stra"+scharfes+"e\")", "Stra"+scharfes+"e"); - assertTrue(Character.isLetter(scharfes.charAt(0))); - - // CURRENTLY FAILS: result: "SSUnd"+scharfes - // LibreOffice 5.0.3.2 behavior: "Sund"+scharfes - // Excel 2013 behavior: ??? - confirm("PROPER(\""+scharfes+"und"+scharfes+"\")", "SSund"+scharfes); - - // also test longer string - StringBuilder builder = new StringBuilder("A"); - StringBuilder expected = new StringBuilder("A"); - for(int i = 1;i < 254;i++) { - builder.append((char)(65 + (i % 26))); - expected.append((char)(97 + (i % 26))); - } - confirm("PROPER(\"" + builder + "\")", expected.toString()); - } - - private void confirm(String formulaText, String expectedResult) { - cell11.setCellFormula(formulaText); - evaluator.clearAllCachedResultValues(); - CellValue cv = evaluator.evaluate(cell11); - assertEquals(CellType.STRING, cv.getCellType(), "Wrong result type"); - String actualValue = cv.getStringValue(); - assertEquals(expectedResult, actualValue); - } - - @Test - void test() { - checkProper("", ""); - checkProper("a", "A"); - checkProper("abc", "Abc"); - checkProper("abc abc", "Abc Abc"); - checkProper("abc/abc", "Abc/Abc"); - checkProper("ABC/ABC", "Abc/Abc"); - checkProper("aBc/ABC", "Abc/Abc"); - checkProper("aBc@#$%^&*()_+=-ABC", "Abc@#$%^&*()_+=-Abc"); - checkProper("aBc25aerg/ABC", "Abc25Aerg/Abc"); - checkProper("aBc/\u00C4\u00F6\u00DF\u00FC/ABC", "Abc/\u00C4\u00F6\u00DF\u00FC/Abc"); // Some German umlauts with uppercase first letter is not changed - checkProper("\u00FC", "\u00DC"); - checkProper("\u00DC", "\u00DC"); - checkProper("\u00DF", "SS"); // German "scharfes s" is uppercased to "SS" - checkProper("\u00DFomesing", "SSomesing"); // German "scharfes s" is uppercased to "SS" - checkProper("aBc/\u00FC\u00C4\u00F6\u00DF\u00FC/ABC", "Abc/\u00DC\u00E4\u00F6\u00DF\u00FC/Abc"); // Some German umlauts with lowercase first letter is changed to uppercase - } - - @Test - void testMicroBenchmark() { - ValueEval strArg = new StringEval("some longer text that needs a number of replacements to check for runtime of different implementations"); - // long start = System.currentTimeMillis(); - for(int i = 0;i < 300000;i++) { - final ValueEval ret = TextFunction.PROPER.evaluate(new ValueEval[]{strArg}, 0, 0); - assertEquals("Some Longer Text That Needs A Number Of Replacements To Check For Runtime Of Different Implementations", ((StringEval)ret).getStringValue()); - } - // Took approx. 600ms on a decent Laptop in July 2016 - //System.out.println("Took: " + (System.currentTimeMillis() - start) + "ms"); - } - - private void checkProper(String input, String expected) { - ValueEval strArg = new StringEval(input); - final ValueEval ret = TextFunction.PROPER.evaluate(new ValueEval[]{strArg}, 0, 0); - assertEquals(expected, ((StringEval)ret).getStringValue()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestSumifsXSSF.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestSumifsXSSF.java deleted file mode 100644 index 2beafffd13..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestSumifsXSSF.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.tests.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * - */ -class TestSumifsXSSF { - - /** - * handle null cell predicate - */ - @Test - void testBug60858() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("bug60858.xlsx")) { - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sheet = wb.getSheetAt(0); - Cell cell = sheet.getRow(1).getCell(5); - fe.evaluate(cell); - assertEquals(0.0, cell.getNumericCellValue(), 0.0000000000000001); - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestVlookup.java b/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestVlookup.java deleted file mode 100644 index 753e2046d2..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/formula/functions/TestVlookup.java +++ /dev/null @@ -1,141 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.formula.functions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -/** - * Test the VLOOKUP function - */ -@Execution(ExecutionMode.CONCURRENT) -class TestVlookup { - - @Test - void testFullColumnAreaRef61841() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("VLookupFullColumn.xlsx")) { - FormulaEvaluator feval = wb.getCreationHelper().createFormulaEvaluator(); - feval.evaluateAll(); - assertEquals("Value1", feval.evaluate(wb.getSheetAt(0).getRow(3).getCell(1)).getStringValue(), - "Wrong lookup value"); - assertEquals(CellType.ERROR, feval.evaluate(wb.getSheetAt(0).getRow(4).getCell(1)).getCellType(), - "Lookup should return #N/A"); - } - } - - @Test - void bug62275_true() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - Cell cell = row.createCell(0); - cell.setCellFormula("vlookup(A2,B1:B5,2,true)"); - - CreationHelper createHelper = wb.getCreationHelper(); - FormulaEvaluator eval = createHelper.createFormulaEvaluator(); - CellValue value = eval.evaluate(cell); - - assertFalse(value.getBooleanValue()); - } - } - - @Test - void bug62275_false() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - Cell cell = row.createCell(0); - cell.setCellFormula("vlookup(A2,B1:B5,2,false)"); - - CreationHelper crateHelper = wb.getCreationHelper(); - FormulaEvaluator eval = crateHelper.createFormulaEvaluator(); - CellValue value = eval.evaluate(cell); - - assertFalse(value.getBooleanValue()); - } - } - - @Test - void bug62275_empty_3args() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - Cell cell = row.createCell(0); - cell.setCellFormula("vlookup(A2,B1:B5,2,)"); - - CreationHelper crateHelper = wb.getCreationHelper(); - FormulaEvaluator eval = crateHelper.createFormulaEvaluator(); - CellValue value = eval.evaluate(cell); - - assertFalse(value.getBooleanValue()); - } - } - - @Test - void bug62275_empty_2args() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - Cell cell = row.createCell(0); - cell.setCellFormula("vlookup(A2,B1:B5,,)"); - - CreationHelper crateHelper = wb.getCreationHelper(); - FormulaEvaluator eval = crateHelper.createFormulaEvaluator(); - CellValue value = eval.evaluate(cell); - - assertFalse(value.getBooleanValue()); - } - } - - @Test - void bug62275_empty_1arg() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - Cell cell = row.createCell(0); - cell.setCellFormula("vlookup(A2,,,)"); - - CreationHelper crateHelper = wb.getCreationHelper(); - FormulaEvaluator eval = crateHelper.createFormulaEvaluator(); - CellValue value = eval.evaluate(cell); - - assertFalse(value.getBooleanValue()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXCell.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXCell.java deleted file mode 100644 index f43609c392..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXCell.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestCell; -import org.apache.poi.ss.usermodel.Cell; -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.xssf.streaming.SXSSFCell; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.junit.jupiter.api.Test; - -/** - * Class for combined testing of XML-specific functionality of - * {@link XSSFCell} and {@link SXSSFCell}. - * - * Any test that is applicable for {@link HSSFCell} as well should go into - * the common base class {@link BaseTestCell}. - */ -public abstract class BaseTestXCell extends BaseTestCell { - protected BaseTestXCell(ITestDataProvider testDataProvider) { - super(testDataProvider); - } - - @Test - void testXmlEncoding() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sh = wb1.createSheet(); - Row row = sh.createRow(0); - Cell cell = row.createCell(0); - String sval = "\u0000\u0002\u0012<>\t\n\u00a0 &\"POI'\u2122"; - cell.setCellValue(sval); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - // invalid characters are replaced with question marks - assertEquals("???<>\t\n\u00a0 &\"POI'\u2122", wb2.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); - wb2.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXRow.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXRow.java deleted file mode 100644 index 744f342694..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXRow.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.usermodel; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestRow; -import org.apache.poi.xssf.streaming.SXSSFRow; -import org.apache.poi.xssf.usermodel.XSSFRow; - -/** - * Class for combined testing of XML-specific functionality of - * {@link XSSFRow} and {@link SXSSFRow}. - * - * Any test that is applicable for {@link org.apache.poi.hssf.usermodel.HSSFRow} as well should go into - * the common base class {@link BaseTestRow}. - */ -public abstract class BaseTestXRow extends BaseTestRow { - protected BaseTestXRow(ITestDataProvider testDataProvider) { - super(testDataProvider); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXSheet.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXSheet.java deleted file mode 100644 index ae68cace8c..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXSheet.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.usermodel; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestSheet; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFSheet; - -/** - * Class for combined testing of XML-specific functionality of - * {@link XSSFSheet} and {@link SXSSFSheet}. - * - * Any test that is applicable for {@link org.apache.poi.hssf.usermodel.HSSFSheet} as well should go into - * the common base class {@link BaseTestSheet}. - */ -public abstract class BaseTestXSheet extends BaseTestSheet { - protected BaseTestXSheet(ITestDataProvider testDataProvider) { - super(testDataProvider); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXWorkbook.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXWorkbook.java deleted file mode 100644 index 49ea01f697..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/BaseTestXWorkbook.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.usermodel; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestWorkbook; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Class for combined testing of XML-specific functionality of - * {@link XSSFWorkbook} and {@link SXSSFWorkbook}. - * - * Any test that is applicable for {@link org.apache.poi.hssf.usermodel.HSSFWorkbook} as well should go into - * the common base class {@link BaseTestWorkbook}. - */ -public abstract class BaseTestXWorkbook extends BaseTestWorkbook { - protected BaseTestXWorkbook(ITestDataProvider testDataProvider) { - super(testDataProvider); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestConditionalFormattingEval.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestConditionalFormattingEval.java deleted file mode 100644 index 4e6257c650..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestConditionalFormattingEval.java +++ /dev/null @@ -1,218 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.usermodel; - - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import java.util.Date; -import java.util.List; - -import org.apache.poi.ss.formula.ConditionalFormattingEvaluator; -import org.apache.poi.ss.formula.EvaluationConditionalFormatRule; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Color; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestConditionalFormattingEval { - - private XSSFWorkbook wb; - private Sheet sheet; - private XSSFFormulaEvaluator formulaEval; - private ConditionalFormattingEvaluator cfe; - private CellReference ref; - private List<EvaluationConditionalFormatRule> rules; - - @BeforeEach - void openWB() { - wb = XSSFTestDataSamples.openSampleWorkbook("ConditionalFormattingSamples.xlsx"); - formulaEval = new XSSFFormulaEvaluator(wb); - cfe = new ConditionalFormattingEvaluator(wb, formulaEval); - } - - @AfterEach - void closeWB() { - formulaEval = null; - cfe = null; - ref = null; - rules = null; - IOUtils.closeQuietly(wb); - } - - @Test - void testFormattingEvaluation() { - sheet = wb.getSheet("Products1"); - - getRulesFor(12, 1); - assertEquals(1, rules.size(), "wrong # of rules for " + ref); - assertEquals("FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref); - assertFalse(rules.get(0).getRule().getFontFormatting().isItalic(), "should not be italic " + ref); - - getRulesFor(16, 3); - assertEquals(1, rules.size(), "wrong # of rules for " + ref); - assertEquals(0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001, "wrong bg color for " + ref); - - getRulesFor(12, 3); - assertEquals(0, rules.size(), "wrong # of rules for " + ref); - - sheet = wb.getSheet("Products2"); - - getRulesFor(15,1); - assertEquals(1, rules.size(), "wrong # of rules for " + ref); - assertEquals("FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref); - - getRulesFor(20,3); - assertEquals(0, rules.size(), "wrong # of rules for " + ref); - - // now change a cell value that's an input for the rules - Cell cell = sheet.getRow(1).getCell(6); - cell.setCellValue("Dairy"); - formulaEval.notifyUpdateCell(cell); - cell = sheet.getRow(4).getCell(6); - cell.setCellValue(500); - formulaEval.notifyUpdateCell(cell); - // need to throw away all evaluations, since we don't know how value changes may have affected format formulas - cfe.clearAllCachedValues(); - - // test that the conditional validation evaluations changed - getRulesFor(15,1); - assertEquals(0, rules.size(), "wrong # of rules for " + ref); - - getRulesFor(20,3); - assertEquals(1, rules.size(), "wrong # of rules for " + ref); - assertEquals(0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001, "wrong bg color for " + ref); - - getRulesFor(20,1); - assertEquals(1, rules.size(), "wrong # of rules for " + ref); - assertEquals("FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref); - - sheet = wb.getSheet("Book tour"); - - getRulesFor(8,2); - assertEquals(1, rules.size(), "wrong # of rules for " + ref); - - sheet = wb.getSheet("Compare to totals"); - getRulesFor(3, 2); - assertEquals(1, rules.size(), "wrong # of rules for " + ref); - assertEquals("FFFF0000", getColor(rules.get(0).getRule().getFontFormatting().getFontColor()), "wrong fg color for " + ref); - getRulesFor(3, 3); - assertEquals(0, rules.size(), "wrong # of rules for " + ref); - getRulesFor(15, 4); - assertEquals(0, rules.size(), "wrong # of rules for " + ref); - getRulesFor(16, 1); - assertEquals(1, rules.size(), "wrong # of rules for " + ref); - assertEquals("FFFF0000", getColor(rules.get(0).getRule().getFontFormatting().getFontColor()), "wrong fg color for " + ref); - - sheet = wb.getSheet("Products3"); - sheet.getRow(8).getCell(0).setCellValue(new Date()); - getRulesFor(8, 0); - assertEquals(1, rules.size(), "wrong # of rules for " + ref); - getRulesFor(8, 3); - assertEquals(1, rules.size(), "wrong # of rules for " + ref); - - sheet = wb.getSheet("Customers2"); - getRulesFor(3, 0); - assertEquals(0, rules.size(), "wrong # of rules for " + ref); - } - - @Test - void testFormattingOnUndefinedCell() { - wb = XSSFTestDataSamples.openSampleWorkbook("conditional_formatting_with_formula_on_second_sheet.xlsx"); - formulaEval = new XSSFFormulaEvaluator(wb); - cfe = new ConditionalFormattingEvaluator(wb, formulaEval); - - sheet = wb.getSheet("Sales Plan"); - getRulesFor(9,2); - assertNotEquals(0, rules.size(), "No rules for " + ref); - assertEquals("FFFFFF00", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), "wrong bg color for " + ref); - } - - @Test - void testRepeatedEval() { - wb = XSSFTestDataSamples.openSampleWorkbook("test_conditional_formatting.xlsx"); - formulaEval = new XSSFFormulaEvaluator(wb); - cfe = new ConditionalFormattingEvaluator(wb, formulaEval); - - sheet = wb.getSheetAt(0); - assertEquals(0, getRulesFor(2, 1).size(), "no rules should apply"); - - assertEquals(0, getRulesFor(2, 1).size(), "no rules should apply"); - - } - - @Test - void testCellValueIsWrongType() { - wb = XSSFTestDataSamples.openSampleWorkbook("conditional_formatting_cell_is.xlsx"); - formulaEval = new XSSFFormulaEvaluator(wb); - cfe = new ConditionalFormattingEvaluator(wb, formulaEval); - - sheet = wb.getSheetAt(1); - - assertEquals(1, getRulesFor(3, 1).size(), "wrong # of matching rules"); - } - - @Test - void testRangeCondition() { - wb = XSSFTestDataSamples.openSampleWorkbook("conditional_formatting_multiple_ranges.xlsx"); - formulaEval = new XSSFFormulaEvaluator(wb); - cfe = new ConditionalFormattingEvaluator(wb, formulaEval); - - sheet = wb.getSheetAt(0); - - assertEquals(0, getRulesFor(0, 0).size(), "wrong # of matching rules"); - assertEquals(0, getRulesFor(1, 0).size(), "wrong # of matching rules"); - assertEquals(0, getRulesFor(2, 0).size(), "wrong # of matching rules"); - assertEquals(1, getRulesFor(3, 0).size(), "wrong # of matching rules"); - assertEquals(0, getRulesFor(0, 1).size(), "wrong # of matching rules"); - assertEquals(0, getRulesFor(1, 1).size(), "wrong # of matching rules"); - assertEquals(1, getRulesFor(2, 1).size(), "wrong # of matching rules"); - assertEquals(1, getRulesFor(3, 1).size(), "wrong # of matching rules"); - assertEquals(1, getRulesFor(0, 3).size(), "wrong # of matching rules"); - assertEquals(0, getRulesFor(1, 3).size(), "wrong # of matching rules"); - assertEquals(1, getRulesFor(2, 3).size(), "wrong # of matching rules"); - assertEquals(0, getRulesFor(0, 6).size(), "wrong # of matching rules"); - assertEquals(0, getRulesFor(3, 6).size(), "wrong # of matching rules"); - assertEquals(0, getRulesFor(2, 6).size(), "wrong # of matching rules"); - } - - private List<EvaluationConditionalFormatRule> getRulesFor(int row, int col) { - ref = new CellReference(sheet.getSheetName(), row, col, false, false); - return rules = cfe.getConditionalFormattingForCell(ref); - } - - private String getColor(Color color) { - final XSSFColor c = XSSFColor.toXSSFColor(color); - return c.getARGBHex(); - } - - private double getTint(Color color) { - final XSSFColor c = XSSFColor.toXSSFColor(color); - return c.getTint(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java deleted file mode 100644 index 001ea8ebce..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java +++ /dev/null @@ -1,229 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.usermodel; - -import static org.apache.poi.sl.tests.SLCommonUtils.xslfOnly; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - -import org.apache.commons.codec.binary.Base64; -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.ClassIDPredefined; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.EntryUtils; -import org.apache.poi.poifs.filesystem.Ole10Native; -import org.apache.poi.poifs.filesystem.Ole10NativeException; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.sl.usermodel.AutoShape; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.ss.extractor.EmbeddedData; -import org.apache.poi.ss.extractor.EmbeddedExtractor; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.ObjectData; -import org.apache.poi.ss.usermodel.Shape; -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.XSSFObjectData; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -class TestEmbedOLEPackage { - private static byte[] samplePPT, samplePPTX, samplePNG; - - private static final POIDataSamples ssamples = POIDataSamples.getSpreadSheetInstance(); - - @BeforeAll - public static void init() throws IOException { - samplePPT = getSamplePPT(false); - samplePPTX = getSamplePPT(true); - samplePNG = ssamples.readFile("logoKarmokar4.png"); - } - - @Test - void embedPDF() throws IOException { - try (InputStream is = ssamples.openResourceAsStream("bug64512_embed.xlsx"); - XSSFWorkbook wb = new XSSFWorkbook(is)) { - List<XSSFObjectData> oleShapes = new ArrayList<>(); - List<Ole10Native> ole10s = new ArrayList<>(); - - final boolean digestMatch = - wb.getSheetAt(0).getDrawingPatriarch().getShapes().stream() - .map(s -> (XSSFObjectData)s) - .filter(oleShapes::add) - .map(TestEmbedOLEPackage::extractOle10Native) - .filter(ole10s::add) - .map(TestEmbedOLEPackage::digest) - .allMatch("FUJBVHTAZ0ly/TNDNmEj1gQ4a2TbZwDMVF4WUkDQLaM="::equals); - - assertEquals(2, oleShapes.size()); - assertEquals("Package", oleShapes.get(0).getOLE2ClassName()); - assertEquals("Package2", oleShapes.get(1).getOLE2ClassName()); - assertTrue(digestMatch); - - final String expLabel = "Apache_POI_project_logo_(2018).pdf"; - final String expFilenName = "C:\\Dell\\Apache_POI_project_logo_(2018).pdf"; - final String expCmd1 = "C:\\Users\\KIWIWI~1\\AppData\\Local\\Temp\\{84287F34-B79C-4F3A-9A92-6BB664586F48}\\Apache_POI_project_logo_(2018).pdf"; - final String expCmd2 = "C:\\Users\\KIWIWI~1\\AppData\\Local\\Temp\\{84287F34-B79C-4F3A-9A92-6BB664586F48}\\Apache_POI_project_logo_(2).pdf"; - - assertTrue(ole10s.stream().map(Ole10Native::getLabel).allMatch(expLabel::equals)); - assertTrue(ole10s.stream().map(Ole10Native::getFileName).allMatch(expFilenName::equals)); - assertEquals(expCmd1, ole10s.get(0).getCommand()); - assertEquals(expCmd2, ole10s.get(1).getCommand()); - - for (Ole10Native o : ole10s) { - assertEquals(o.getLabel(), o.getLabel2()); - assertEquals(o.getCommand(), o.getCommand2()); - assertEquals(o.getFileName(), o.getFileName2()); - } - - Ole10Native scratch = new Ole10Native(expLabel, expFilenName, expCmd1, ole10s.get(0).getDataBuffer()); - scratch.setLabel2(expLabel); - scratch.setFileName2(expFilenName); - scratch.setCommand2(expCmd1); - - try (POIFSFileSystem scratchFS = new POIFSFileSystem(); - POIFSFileSystem ole1FS = new POIFSFileSystem(new ByteArrayInputStream(oleShapes.get(0).getObjectData()))) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - scratch.writeOut(bos); - scratchFS.createDocument(new ByteArrayInputStream(bos.toByteArray()), Ole10Native.OLE10_NATIVE); - scratchFS.getRoot().setStorageClsid(ClassIDPredefined.OLE_V1_PACKAGE.getClassID()); - assertTrue(EntryUtils.areDirectoriesIdentical(ole1FS.getRoot(), scratchFS.getRoot())); - } - } - } - - private static Ole10Native extractOle10Native(XSSFObjectData objectData) { - try (InputStream is = objectData.getObjectPart().getInputStream(); - POIFSFileSystem poifs = new POIFSFileSystem(is)) { - return Ole10Native.createFromEmbeddedOleObject(poifs); - } catch (IOException | Ole10NativeException e) { - throw new AssertionError(e.getMessage(), e); - } - } - - private static String digest(Ole10Native ole10) { - MessageDigest sha = CryptoFunctions.getMessageDigest(HashAlgorithm.sha256); - byte[] digest = sha.digest(ole10.getDataBuffer()); - return Base64.encodeBase64String(digest); - } - - @Test - void embedXSSF() throws IOException { - Workbook wb1 = new XSSFWorkbook(); - addEmbeddedObjects(wb1); - - Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - validateEmbeddedObjects(wb2); - - wb2.close(); - wb1.close(); - } - - @Test - void embedHSSF() throws IOException { - assumeFalse(xslfOnly()); - - HSSFWorkbook wb1 = new HSSFWorkbook(); - addEmbeddedObjects(wb1); - Workbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - validateEmbeddedObjects(wb2); - - wb2.close(); - wb1.close(); - } - - static void validateEmbeddedObjects(Workbook wb) throws IOException { - boolean ooxml = wb.getClass().getName().toLowerCase(Locale.ROOT).contains("xssf"); - byte[] data = (ooxml) ? samplePPTX : samplePPT; - Iterator<Integer> shapeIds = Arrays.asList(1025,1026,2049).iterator(); - EmbeddedExtractor ee = new EmbeddedExtractor(); - for (Sheet sheet : wb) { - Drawing<? extends Shape> pat = sheet.getDrawingPatriarch(); - for (Shape shape : pat) { - assertTrue(shape instanceof ObjectData); - ObjectData od = (ObjectData)shape; - EmbeddedData ed = ee.extractOne((DirectoryNode)od.getDirectory()); - assertArrayEquals(data, ed.getEmbeddedData()); - assertArrayEquals(samplePNG, od.getPictureData().getData()); - assertEquals((int)shapeIds.next(), od.getShapeId()); - } - } - } - - static void addEmbeddedObjects(Workbook wb) throws IOException { - boolean ooxml = wb.getClass().getName().toLowerCase(Locale.ROOT).contains("xssf"); - int picIdx = wb.addPicture(samplePNG, Workbook.PICTURE_TYPE_PNG); - byte[] data = (ooxml) ? samplePPTX : samplePPT; - String ext = (ooxml) ? ".pptx" : ".ppt"; - - int oleIdx1a = wb.addOlePackage(data, "dummy1a"+ext, "dummy1a"+ext, "dummy1a"+ext); - int oleIdx1b = wb.addOlePackage(data, "dummy1b"+ext, "dummy1b"+ext, "dummy1b"+ext); - int oleIdx2 = wb.addOlePackage(data, "dummy2"+ext, "dummy2"+ext, "dummy2"+ext); - - Sheet sh1 = wb.createSheet(); - Drawing<?> pat1 = sh1.createDrawingPatriarch(); - ClientAnchor anchor1a = pat1.createAnchor(0, 0, 0, 0, 1, 1, 3, 6); - pat1.createObjectData(anchor1a, oleIdx1a, picIdx); - ClientAnchor anchor1b = pat1.createAnchor(0, 0, 0, 0, 1, 1+7, 3, 6+7); - pat1.createObjectData(anchor1b, oleIdx1b, picIdx); - - Sheet sh2 = wb.createSheet(); - Drawing<?> pat2 = sh2.createDrawingPatriarch(); - ClientAnchor anchor2 = pat2.createAnchor(0, 0, 0, 0, 1, 1, 3, 6); - pat2.createObjectData(anchor2, oleIdx2, picIdx); - } - - static byte[] getSamplePPT(boolean ooxml) throws IOException { - SlideShow<?,?> ppt = SlideShowFactory.create(ooxml); - Slide<?,?> slide = ppt.createSlide(); - - AutoShape<?,?> sh1 = slide.createAutoShape(); - sh1.setShapeType(ShapeType.STAR_32); - sh1.setAnchor(new java.awt.Rectangle(50, 50, 100, 200)); - sh1.setFillColor(java.awt.Color.red); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ppt.write(bos); - ppt.close(); - - return bos.toByteArray(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestXSSFBorderStyle.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestXSSFBorderStyle.java deleted file mode 100644 index d191c7ab7c..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestXSSFBorderStyle.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.usermodel; - -import org.apache.poi.ss.usermodel.BaseTestBorderStyle; -import org.apache.poi.xssf.XSSFITestDataProvider; - -/** - * @author Yegor Kozlov - */ -public final class TestXSSFBorderStyle extends BaseTestBorderStyle { - - public TestXSSFBorderStyle() { - super(XSSFITestDataProvider.instance); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestXSSFRangeCopier.java b/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestXSSFRangeCopier.java deleted file mode 100644 index 3ee318abdf..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/usermodel/TestXSSFRangeCopier.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.tests.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestRangeCopier; -import org.apache.poi.ss.usermodel.CellCopyPolicy; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFRangeCopier; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestXSSFRangeCopier extends BaseTestRangeCopier { - public TestXSSFRangeCopier() { - super(); - workbook = new XSSFWorkbook(); - testDataProvider = XSSFITestDataProvider.instance; - } - - @BeforeEach - void init() { - workbook = XSSFTestDataSamples.openSampleWorkbook("tile-range-test.xlsx"); - initSheets(); - rangeCopier = new XSSFRangeCopier(sheet1, sheet1); - transSheetRangeCopier = new XSSFRangeCopier(sheet1, sheet2); - } - - @AfterEach - void shutdown() throws IOException { - workbook.close(); - } - - @Test // XSSF only. HSSF version wouldn't be so simple. And also this test is contained in following, more complex tests, so it's not really important. - void copyRow() { - Row existingRow = sheet1.getRow(4); - XSSFRow newRow = (XSSFRow)sheet1.getRow(5); - CellCopyPolicy policy = new CellCopyPolicy(); - newRow.copyRowFrom(existingRow, policy); - assertEquals("$C2+B$2", newRow.getCell(1).getCellFormula()); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestSXSSFCellUtil.java b/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestSXSSFCellUtil.java deleted file mode 100644 index 0e2511f36d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestSXSSFCellUtil.java +++ /dev/null @@ -1,27 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.tests.util; - -import org.apache.poi.ss.util.BaseTestCellUtil; -import org.apache.poi.xssf.SXSSFITestDataProvider; - -class TestSXSSFCellUtil extends BaseTestCellUtil { - public TestSXSSFCellUtil() { - super(SXSSFITestDataProvider.instance); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestXSSFCellUtil.java b/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestXSSFCellUtil.java deleted file mode 100644 index 40f16dbe61..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestXSSFCellUtil.java +++ /dev/null @@ -1,27 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.tests.util; - -import org.apache.poi.ss.util.BaseTestCellUtil; -import org.apache.poi.xssf.XSSFITestDataProvider; - -class TestXSSFCellUtil extends BaseTestCellUtil { - public TestXSSFCellUtil() { - super(XSSFITestDataProvider.instance); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestXSSFPropertyTemplate.java b/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestXSSFPropertyTemplate.java deleted file mode 100644 index c6f9f59cc0..0000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/tests/util/TestXSSFPropertyTemplate.java +++ /dev/null @@ -1,138 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.tests.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BorderExtent; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -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.util.CellRangeAddress; -import org.apache.poi.ss.util.PropertyTemplate; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -class TestXSSFPropertyTemplate { - - @Test - void applyBorders() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - CellRangeAddress b2 = new CellRangeAddress(1, 1, 1, 1); - PropertyTemplate pt = new PropertyTemplate(); - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - pt.drawBorders(a1c3, BorderStyle.THIN, IndexedColors.RED.getIndex(), BorderExtent.ALL); - pt.applyBorders(sheet); - - for (Row row: sheet) { - for (Cell cell: row) { - CellStyle cs = cell.getCellStyle(); - assertEquals(BorderStyle.THIN, cs.getBorderTop()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderBottom()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderLeft()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderRight()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } - } - - pt.drawBorders(b2, BorderStyle.NONE, BorderExtent.ALL); - pt.applyBorders(sheet); - - for (Row row: sheet) { - for (Cell cell: row) { - CellStyle cs = cell.getCellStyle(); - if (cell.getColumnIndex() != 1 || row.getRowNum() == 0) { - assertEquals(BorderStyle.THIN, cs.getBorderTop()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderTop()); - } - if (cell.getColumnIndex() != 1 || row.getRowNum() == 2) { - assertEquals(BorderStyle.THIN, cs.getBorderBottom()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderBottom()); - } - if (cell.getColumnIndex() == 0 || row.getRowNum() != 1) { - assertEquals(BorderStyle.THIN, cs.getBorderLeft()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderLeft()); - } - if (cell.getColumnIndex() == 2 || row.getRowNum() != 1) { - assertEquals(BorderStyle.THIN, cs.getBorderRight()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderRight()); - } - } - } - - wb.close(); - } - - @Test - void clonePropertyTemplate() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, IndexedColors.RED.getIndex(), BorderExtent.ALL); - PropertyTemplate pt2 = new PropertyTemplate(pt); - assertNotSame(pt2, pt); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt2.getNumBorderColors(i, j)); - assertEquals(4, pt2.getNumBorderColors(i, j)); - } - } - - CellRangeAddress b2 = new CellRangeAddress(1,1,1,1); - pt2.drawBorders(b2, BorderStyle.THIN, BorderExtent.ALL); - - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - pt.applyBorders(sheet); - - for (Row row : sheet) { - for (Cell cell : row) { - CellStyle cs = cell.getCellStyle(); - assertEquals(BorderStyle.MEDIUM, cs.getBorderTop()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderBottom()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderLeft()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderRight()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } - } - - wb.close(); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/util/tests/TestIdentifierManager.java b/src/ooxml/testcases/org/apache/poi/util/tests/TestIdentifierManager.java deleted file mode 100644 index 71fe575c67..0000000000 --- a/src/ooxml/testcases/org/apache/poi/util/tests/TestIdentifierManager.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.util.tests; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -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 org.apache.poi.ooxml.util.IdentifierManager; -import org.junit.jupiter.api.Test; - -class TestIdentifierManager { - @Test - void testBasic() - { - IdentifierManager manager = new IdentifierManager(0L,100L); - assertEquals(101L,manager.getRemainingIdentifiers()); - assertEquals(0L,manager.reserveNew()); - assertEquals(100L,manager.getRemainingIdentifiers()); - assertEquals(1L,manager.reserve(0L)); - assertEquals(99L,manager.getRemainingIdentifiers()); - } - - @Test - void testLongLimits() { - long min = IdentifierManager.MIN_ID; - long max = IdentifierManager.MAX_ID; - IdentifierManager manager = new IdentifierManager(min,max); - assertTrue(max - min + 1 > 0, "Limits lead to a long variable overflow"); - assertTrue(manager.getRemainingIdentifiers() > 0, "Limits lead to a long variable overflow"); - assertEquals(min,manager.reserveNew()); - assertEquals(max,manager.reserve(max)); - assertEquals(max - min -1, manager.getRemainingIdentifiers()); - manager.release(max); - manager.release(min); - } - - @Test - void testReserve() { - IdentifierManager manager1 = new IdentifierManager(10L, 30L); - assertEquals(12L, manager1.reserve(12L)); - long reserve = manager1.reserve(12L); - assertNotEquals(12L, reserve, "Same id must be reserved twice!"); - assertTrue(manager1.release(12L)); - assertTrue(manager1.release(reserve)); - assertFalse(manager1.release(12L)); - assertFalse(manager1.release(reserve)); - - IdentifierManager manager2 = new IdentifierManager(0L, 2L); - assertEquals(0L, manager2.reserve(0L)); - assertEquals(1L, manager2.reserve(1L)); - assertEquals(2L, manager2.reserve(2L)); - assertThrows(IllegalStateException.class, () -> manager2.reserve(0L)); - assertThrows(IllegalStateException.class, () -> manager2.reserve(1L)); - assertThrows(IllegalStateException.class, () -> manager2.reserve(2L)); - } - - @Test - void testReserveNew() { - IdentifierManager manager = new IdentifierManager(10L,12L); - assertSame(10L,manager.reserveNew()); - assertSame(11L,manager.reserveNew()); - assertSame(12L,manager.reserveNew()); - assertThrows(IllegalStateException.class, manager::reserveNew); - } - - @Test - void testRelease() { - IdentifierManager manager = new IdentifierManager(10L,20L); - assertEquals(10L,manager.reserve(10L)); - assertEquals(11L,manager.reserve(11L)); - assertEquals(12L,manager.reserve(12L)); - assertEquals(13L,manager.reserve(13L)); - assertEquals(14L,manager.reserve(14L)); - - assertTrue(manager.release(10L)); - assertEquals(10L,manager.reserve(10L)); - assertTrue(manager.release(10L)); - - assertTrue(manager.release(11L)); - assertEquals(11L,manager.reserve(11L)); - assertTrue(manager.release(11L)); - assertFalse(manager.release(11L)); - assertFalse(manager.release(10L)); - - assertEquals(10L,manager.reserve(10L)); - assertEquals(11L,manager.reserve(11L)); - assertTrue(manager.release(12L)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/util/tests/TestTempFileThreaded.java b/src/ooxml/testcases/org/apache/poi/util/tests/TestTempFileThreaded.java deleted file mode 100644 index 678280e7b1..0000000000 --- a/src/ooxml/testcases/org/apache/poi/util/tests/TestTempFileThreaded.java +++ /dev/null @@ -1,184 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.util.tests; - -import static org.apache.poi.util.DefaultTempFileCreationStrategy.POIFILES; -import static org.apache.poi.util.TempFile.JAVA_IO_TMPDIR; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.util.TempFile; -import org.apache.poi.util.TempFileCreationStrategy; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestTempFileThreaded { - private static final int NUMBER_OF_THREADS = 10; - private static final int NUMBER_OF_TESTS = 200; - - private volatile Throwable exception; - private int[] executions; - - // the actual thread-safe temp-file strategy - private static TempFileCreationStrategy createTempFileCreationStrategy(File poiTempFileDirectory) { - return new TempFileCreationStrategy() { - @Override - public File createTempFile(String prefix, String suffix) throws IOException { - long threadId = Thread.currentThread().getId(); - File threadDir = new File(poiTempFileDirectory, Long.toString(threadId)); - if (!threadDir.exists()) { - if (!threadDir.mkdirs()) { - throw new IOException("mkdir of " + threadDir + " failed"); - } - } - - File file = File.createTempFile(prefix, suffix, threadDir); - file.deleteOnExit(); - return file; - } - - @Override - public File createTempDirectory(String prefix) { - throw new UnsupportedOperationException("createTempDirectory"); - } - }; - } - - @BeforeAll - public static void setUpClass() throws IOException { - String tmpDir = System.getProperty(JAVA_IO_TMPDIR); - if (tmpDir == null) { - throw new IOException("Systems temporary directory not defined - set the -D" + JAVA_IO_TMPDIR + " jvm property!"); - } - - TempFile.setTempFileCreationStrategy(createTempFileCreationStrategy(new File(new File(tmpDir, POIFILES), "TestTempFileThreaded"))); - } - - @BeforeEach - void setUp() { - // Initialize array to allow to summarize afterwards - executions = new int[NUMBER_OF_THREADS]; - } - - @Test - void runTest() throws Throwable { - List<Thread> threads = new LinkedList<>(); - - // start all threads - for (int i = 0; i < NUMBER_OF_THREADS; i++) { - Thread t = startThread(i, new TestRunnable()); - threads.add(t); - } - - // wait for all threads - for (int i = 0; i < NUMBER_OF_THREADS; i++) { - threads.get(i).join(); - } - - // report exceptions if there were any - if (exception != null) { - throw exception; - } - - // make sure the resulting number of executions is correct - for (int i = 0; i < NUMBER_OF_THREADS; i++) { - // check if enough items were performed - assertEquals(NUMBER_OF_TESTS, executions[i], "Thread " + i + " did not execute all iterations"); - } - } - - private static class TestRunnable { - Map<Integer, List<File>> files = new HashMap<>(); - - public TestRunnable() { - for (int i = 0; i < NUMBER_OF_THREADS; i++) { - files.put(i, new ArrayList<>()); - } - } - - void doEnd(int threadNum) { - for (File file : files.get(threadNum)) { - if (!file.exists()) { - throw new IllegalStateException("File " + file + " does not exist"); - } - if (!file.delete()) { - throw new IllegalStateException("Deletion of " + file + " failed"); - } - } - } - - void run(int threadNum, int iter) throws Exception { - try (SXSSFWorkbook wb = new SXSSFWorkbook()) { - SXSSFSheet sheet = wb.createSheet("test"); - - for (int i = 0; i < 100; i++) { - Row row = sheet.createRow(i); - for (int j = 0; j < 10; j++) { - Cell cell = row.createCell(j); - cell.setCellValue("123"); - } - } - - File file = TempFile.createTempFile("TestTempFile-" + threadNum + "-" + iter + "-", ".xlsx"); - try (OutputStream outputStream = new FileOutputStream(file)) { - wb.write(outputStream); - } - - files.get(threadNum).add(file); - } - } - } - - private Thread startThread(final int threadNum, final TestRunnable run) { - Thread t1 = new Thread(() -> { - try { - for (int iter = 0; iter < NUMBER_OF_TESTS && exception == null; iter++) { - // call the actual test-code - run.run(threadNum, iter); - - executions[threadNum]++; - } - - // do end-work here, we don't do this in a finally as we log - // Exception - // then anyway - run.doEnd(threadNum); - } catch (Throwable e) { - exception = e; - } - - }, "ThreadTestHelper-Thread " + threadNum + ": " + run.getClass().getName()); - - t1.start(); - - return t1; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestNecessaryOOXMLClasses.java b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestNecessaryOOXMLClasses.java deleted file mode 100644 index bc235f51b5..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestNecessaryOOXMLClasses.java +++ /dev/null @@ -1,193 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xddf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -import org.apache.poi.xddf.usermodel.chart.ErrorBarType; -import org.apache.poi.xddf.usermodel.chart.ErrorDirection; -import org.apache.poi.xddf.usermodel.chart.ErrorValueType; -import org.apache.poi.xddf.usermodel.chart.XDDFErrorBars; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.chart.*; -import org.openxmlformats.schemas.drawingml.x2006.main.*; - -// aim is to get these classes loaded and included in poi-ooxml-lite.jar -class TestNecessaryOOXMLClasses { - - @Test - void testProblemClasses() { - CTXYAdjustHandle ctxyAdjustHandle = CTXYAdjustHandle.Factory.newInstance(); - assertNotNull(ctxyAdjustHandle); - CTPolarAdjustHandle ctPolarAdjustHandle = CTPolarAdjustHandle.Factory.newInstance(); - assertNotNull(ctPolarAdjustHandle); - CTChartLines ctChartLines = CTChartLines.Factory.newInstance(); - assertNotNull(ctChartLines); - CTDashStop ctDashStop = CTDashStop.Factory.newInstance(); - assertNotNull(ctDashStop); - CTSurface ctSurface = CTSurface.Factory.newInstance(); - assertNotNull(ctSurface); - CTLegendEntry ctLegendEntry = CTLegendEntry.Factory.newInstance(); - assertNotNull(ctLegendEntry); - CTShape3D ctShape3D = CTShape3D.Factory.newInstance(); - assertNotNull(ctShape3D); - CTScene3D ctScene3D = CTScene3D.Factory.newInstance(); - assertNotNull(ctScene3D); - CTEffectContainer ctEffectContainer = CTEffectContainer.Factory.newInstance(); - assertNotNull(ctEffectContainer); - CTConnectionSite ctConnectionSite = CTConnectionSite.Factory.newInstance(); - assertNotNull(ctConnectionSite); - STLblAlgn stLblAlgn = STLblAlgn.Factory.newInstance(); - assertNotNull(stLblAlgn); - STBlackWhiteMode stBlackWhiteMode = STBlackWhiteMode.Factory.newInstance(); - assertNotNull(stBlackWhiteMode); - STRectAlignment stRectAlignment = STRectAlignment.Factory.newInstance(); - assertNotNull(stRectAlignment); - STTileFlipMode stTileFlipMode = STTileFlipMode.Factory.newInstance(); - assertNotNull(stTileFlipMode); - STPresetPatternVal stPresetPatternVal = STPresetPatternVal.Factory.newInstance(); - assertNotNull(stPresetPatternVal); - STOnOffStyleType stOnOffStyleType = STOnOffStyleType.Factory.newInstance(); - assertNotNull(stOnOffStyleType); - CTLineJoinBevel ctLineJoinBevel = CTLineJoinBevel.Factory.newInstance(); - assertNotNull(ctLineJoinBevel); - CTLineJoinMiterProperties ctLineJoinMiterProperties = CTLineJoinMiterProperties.Factory.newInstance(); - assertNotNull(ctLineJoinMiterProperties); - CTTileInfoProperties ctTileInfoProperties = CTTileInfoProperties.Factory.newInstance(); - assertNotNull(ctTileInfoProperties); - CTTableStyleTextStyle ctTableStyleTextStyle = CTTableStyleTextStyle.Factory.newInstance(); - assertNotNull(ctTableStyleTextStyle); - CTHeaderFooter ctHeaderFooter = CTHeaderFooter.Factory.newInstance(); - assertNotNull(ctHeaderFooter); - CTMarkerSize ctMarkerSize = CTMarkerSize.Factory.newInstance(); - assertNotNull(ctMarkerSize); - CTDLbls ctdLbls = CTDLbls.Factory.newInstance(); - assertNotNull(ctdLbls); - CTMarker ctMarker = CTMarker.Factory.newInstance(); - assertNotNull(ctMarker); - STMarkerStyle stMarkerStyle = STMarkerStyle.Factory.newInstance(); - assertNotNull(stMarkerStyle); - CTMarkerStyle ctMarkerStyle = CTMarkerStyle.Factory.newInstance(); - assertNotNull(ctMarkerStyle); - CTExternalData ctExternalData = CTExternalData.Factory.newInstance(); - assertNotNull(ctExternalData); - CTAxisUnit ctAxisUnit = CTAxisUnit.Factory.newInstance(); - assertNotNull(ctAxisUnit); - CTLblAlgn ctLblAlgn = CTLblAlgn.Factory.newInstance(); - assertNotNull(ctLblAlgn); - CTDashStopList ctDashStopList = CTDashStopList.Factory.newInstance(); - assertNotNull(ctDashStopList); - STDispBlanksAs stDashBlanksAs = STDispBlanksAs.Factory.newInstance(); - assertNotNull(stDashBlanksAs); - CTDispBlanksAs ctDashBlanksAs = CTDispBlanksAs.Factory.newInstance(); - assertNotNull(ctDashBlanksAs); - CTAreaChart ctAreaChart = CTAreaChart.Factory.newInstance(); - assertNotNull(ctAreaChart); - CTArea3DChart ctArea3DChart = CTArea3DChart.Factory.newInstance(); - assertNotNull(ctArea3DChart); - CTSurfaceChart ctSurfaceChart = CTSurfaceChart.Factory.newInstance(); - assertNotNull(ctSurfaceChart); - CTDoughnutChart ctDoughnutChart = CTDoughnutChart.Factory.newInstance(); - assertNotNull(ctDoughnutChart); - CTBar3DChart ctBar3DChart = CTBar3DChart.Factory.newInstance(); - assertNotNull(ctBar3DChart); - CTLine3DChart ctLine3DChart = CTLine3DChart.Factory.newInstance(); - assertNotNull(ctLine3DChart); - CTPie3DChart ctPie3DChart = CTPie3DChart.Factory.newInstance(); - assertNotNull(ctPie3DChart); - CTSurface3DChart ctSurface3DChart = CTSurface3DChart.Factory.newInstance(); - assertNotNull(ctSurface3DChart); - CTAreaSer ctAreaSer = CTAreaSer.Factory.newInstance(); - assertNotNull(ctAreaSer); - CTSurfaceSer ctSurfaceSer = CTSurfaceSer.Factory.newInstance(); - assertNotNull(ctSurfaceSer); - CTView3D ctView3D = CTView3D.Factory.newInstance(); - assertNotNull(ctView3D); - STShape stShape = STShape.Factory.newInstance(); - assertNotNull(stShape); - - STLblAlgn.Enum e1 = STLblAlgn.Enum.forString("ctr"); - assertNotNull(e1); - STBlackWhiteMode.Enum e2 = STBlackWhiteMode.Enum.forString("clr"); - assertNotNull(e2); - STRectAlignment.Enum e3 = STRectAlignment.Enum.forString("ctr"); - assertNotNull(e3); - STTileFlipMode.Enum e4 = STTileFlipMode.Enum.forString("xy"); - assertNotNull(e4); - STPresetPatternVal.Enum e5 = STPresetPatternVal.Enum.forString("horz"); - assertNotNull(e5); - STMarkerStyle.Enum e6 = STMarkerStyle.Enum.forString("circle"); - assertNotNull(e6); - STDispBlanksAs.Enum e7 = STDispBlanksAs.Enum.forString("span"); - assertNotNull(e7); - STShape.Enum e8 = STShape.Enum.forString("cone"); - assertNotNull(e8); - - - CTTextBulletTypefaceFollowText ctTextBulletTypefaceFollowText = CTTextBulletTypefaceFollowText.Factory.newInstance(); - assertNotNull(ctTextBulletTypefaceFollowText); - CTTextBulletSizeFollowText ctTextBulletSizeFollowText = CTTextBulletSizeFollowText.Factory.newInstance(); - assertNotNull(ctTextBulletSizeFollowText); - CTTextBulletColorFollowText ctTextBulletColorFollowText = CTTextBulletColorFollowText.Factory.newInstance(); - assertNotNull(ctTextBulletColorFollowText); - CTTextBlipBullet ctTextBlipBullet = CTTextBlipBullet.Factory.newInstance(); - assertNotNull(ctTextBlipBullet); - CTRotX ctRotX = CTRotX.Factory.newInstance(); - assertNotNull(ctRotX); - CTRotY ctRotY = CTRotY.Factory.newInstance(); - assertNotNull(ctRotY); - CTPerspective ctPerspective = CTPerspective.Factory.newInstance(); - assertNotNull(ctPerspective); - CTDepthPercent ctDepthPercent = CTDepthPercent.Factory.newInstance(); - assertNotNull(ctDepthPercent); - CTHPercent ctHPercent = CTHPercent.Factory.newInstance(); - assertNotNull(ctHPercent); - CTShape ctShape = CTShape.Factory.newInstance(); - assertNotNull(ctShape); - CTOverlap ctOverlap = CTOverlap.Factory.newInstance(); - assertNotNull(ctOverlap); - CTFirstSliceAng ctFirstSliceAng = CTFirstSliceAng.Factory.newInstance(); - assertNotNull(ctFirstSliceAng); - - assertNotNull(ErrorBarType.BOTH); - assertNotNull(ErrorValueType.CUSTOM); - assertNotNull(ErrorDirection.X); - XDDFErrorBars xeb = new XDDFErrorBars(); - assertNotNull(xeb); - assertNull(xeb.getErrorBarType()); - assertNull(xeb.getErrorDirection()); - assertNull(xeb.getErrorValueType()); - - assertNotNull(CTErrBarType.Factory.newInstance()); - assertNotNull(CTErrValType.Factory.newInstance()); - assertNotNull(CTErrDir.Factory.newInstance()); - assertNotNull(CTHoleSize.Factory.newInstance()); - assertNotNull(CTDPt.Factory.newInstance()); - - STErrBarType.Enum e9 = STErrBarType.Enum.forString("both"); - assertNotNull(e9); - STErrValType.Enum e10 = STErrValType.Enum.forString("percentage"); - assertNotNull(e10); - STErrDir.Enum e11 = STErrDir.Enum.forString("x"); - assertNotNull(e11); - CTErrBars bars = CTErrBars.Factory.newInstance(); - assertNotNull(bars); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestXDDFColor.java b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestXDDFColor.java deleted file mode 100644 index 7eb01c29a7..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/TestXDDFColor.java +++ /dev/null @@ -1,145 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xddf.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 java.io.IOException; - -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFTheme; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTScRgbColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSystemColor; -import org.openxmlformats.schemas.drawingml.x2006.main.STPresetColorVal; -import org.openxmlformats.schemas.drawingml.x2006.main.STSchemeColorVal; -import org.openxmlformats.schemas.drawingml.x2006.main.STSystemColorVal; -import org.xmlunit.builder.DiffBuilder; -import org.xmlunit.builder.Input; -import org.xmlunit.diff.Diff; - -class TestXDDFColor { - private static final String XMLNS = "xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"/>"; - - @Test - void testSchemeColor() throws IOException { - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFTheme theme = ppt.createSlide().getTheme(); - - XDDFColor color = XDDFColor.forColorContainer(getThemeColor(theme, STSchemeColorVal.ACCENT_2)); - assertNotNull(color); - // accent2 in theme1.xml is <a:srgbClr val="C0504D"/> - Diff d1 = DiffBuilder.compare(Input.fromString("<a:srgbClr val=\"C0504D\" " + XMLNS)) - .withTest(color.getColorContainer().toString()).build(); - assertFalse(d1.hasDifferences(), d1.toString()); - - color = XDDFColor.forColorContainer(getThemeColor(theme, STSchemeColorVal.LT_1)); - assertNotNull(color); - Diff d2 = DiffBuilder.compare(Input.fromString("<a:sysClr lastClr=\"FFFFFF\" val=\"window\" " + XMLNS)) - .withTest(color.getColorContainer().toString()).build(); - assertFalse(d2.hasDifferences(), d2.toString()); - - color = XDDFColor.forColorContainer(getThemeColor(theme, STSchemeColorVal.DK_1)); - assertNotNull(color); - Diff d3 = DiffBuilder.compare(Input.fromString("<a:sysClr lastClr=\"000000\" val=\"windowText\" " + XMLNS)) - .withTest(color.getColorContainer().toString()).build(); - assertFalse(d3.hasDifferences(), d3.toString()); - } - } - - private CTColor getThemeColor(XSLFTheme theme, STSchemeColorVal.Enum value) { - // find referenced CTColor in the theme - return theme.getCTColor(value.toString()); - } - - @Test - void testPreset() { - CTColor xml = CTColor.Factory.newInstance(); - xml.addNewPrstClr().setVal(STPresetColorVal.AQUAMARINE); - XDDFColor color = XDDFColor.forColorContainer(xml); - assertNotNull(color); - String expected = color.getXmlObject().toString(); - XDDFColor built = XDDFColor.from(PresetColor.AQUAMARINE); - assertEquals(expected, built.getXmlObject().toString()); - } - - @Test - void testSystemDefined() { - CTColor xml = CTColor.Factory.newInstance(); - CTSystemColor sys = xml.addNewSysClr(); - sys.setVal(STSystemColorVal.CAPTION_TEXT); - XDDFColor color = XDDFColor.forColorContainer(xml); - assertNotNull(color); - String expected = color.getXmlObject().toString(); - - XDDFColor built = new XDDFColorSystemDefined(sys, xml); - assertEquals(expected, built.getXmlObject().toString()); - - built = XDDFColor.from(SystemColor.CAPTION_TEXT); - assertEquals(expected, built.getXmlObject().toString()); - } - - @Test - void testRgbBinary() { - CTColor xml = CTColor.Factory.newInstance(); - CTSRgbColor color = xml.addNewSrgbClr(); - byte[] bs = new byte[]{-1, -1, -1}; - color.setVal(bs); - XDDFColor color2 = XDDFColor.forColorContainer(xml); - assertNotNull(color2); - String expected = color2.getXmlObject().toString(); - - XDDFColor built = XDDFColor.from(bs); - assertEquals(expected, built.getXmlObject().toString()); - assertEquals("FFFFFF", ((XDDFColorRgbBinary)built).toRGBHex()); - } - - @Test - void testRgbPercent() { - CTColor xml = CTColor.Factory.newInstance(); - CTScRgbColor color = xml.addNewScrgbClr(); - color.setR(0); - color.setG(0); - color.setB(0); - XDDFColor color2 = XDDFColor.forColorContainer(xml); - assertNotNull(color2); - String expected = color2.getXmlObject().toString(); - - XDDFColorRgbPercent built = (XDDFColorRgbPercent) XDDFColor.from(-1, -1, -1); - assertEquals(expected, built.getXmlObject().toString()); - assertEquals("000000", built.toRGBHex()); - - color.setR(100_000); - color.setG(100_000); - color.setB(100_000); - color2 = XDDFColor.forColorContainer(xml); - assertNotNull(color2); - expected = color2.getXmlObject().toString(); - - built = (XDDFColorRgbPercent) XDDFColor.from(654321, 654321, 654321); - assertEquals(expected, built.getXmlObject().toString()); - assertEquals("FFFFFF", built.toRGBHex()); - - built = (XDDFColorRgbPercent) XDDFColor.from(75000, 50000, 25000); - assertEquals("BF7F3F", built.toRGBHex()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFChart.java b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFChart.java deleted file mode 100644 index 45ff5d7747..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFChart.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xddf.usermodel.chart; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ooxml.POIXMLFactory; -import org.apache.poi.ooxml.POIXMLRelation; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTChartSpace; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -class TestXDDFChart { - @Test - void testConstruct() { - // minimal test to cause ooxml-lite to include all the classes in poi-ooxml-lite - XDDFChart xddfChart = newXDDFChart(); - - assertNotNull(xddfChart.getCTChartSpace()); - assertNotNull(xddfChart.getCTPlotArea()); - } - - @Test - void testSetExternalId() { - XDDFChart xddfChart = newXDDFChart(); - CTChartSpace ctChartSpace = xddfChart.getCTChartSpace(); - - xddfChart.setExternalId("rid1"); - assertEquals("rid1", ctChartSpace.getExternalData().getId()); - - xddfChart.setExternalId("rid2"); - assertEquals("rid2", ctChartSpace.getExternalData().getId()); - } - - @Test - public void test65016() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("65016.xlsx")) { - XSSFSheet splitSheet = wb.getSheet("Splits"); - - XDDFChart chart = newXDDFChart(); - XDDFChartLegend legend = chart.getOrAddLegend(); - legend.setPosition(LegendPosition.BOTTOM); - - // Use a category axis for the bottom axis. - XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); - XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); - leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); - - XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); - - // starting row 1 to include description - XDDFNumericalDataSource<Double> xs = XDDFDataSourcesFactory.fromNumericCellRange(splitSheet, - new CellRangeAddress(2, 100, 0, 0)); - XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromNumericCellRange(splitSheet, - new CellRangeAddress(2, 100, 1, 1)); - - XDDFLineChartData.Series series = (XDDFLineChartData.Series) data.addSeries(xs, ys1); - assertEquals(series.categoryData.getPointCount(), xs.getPointCount()); - - chart.plot(data); - - File file = TempFile.createTempFile("chart20201220", ".xlsx"); - try { - try (OutputStream out = new FileOutputStream(file)) { - wb.write(out); - } - } finally { - assertTrue(!file.exists() || file.delete()); - } - } - } - - private XDDFChart newXDDFChart() { - return new XDDFChart() { - @Override - protected POIXMLRelation getChartRelation() { - return null; - } - - @Override - protected POIXMLRelation getChartWorkbookRelation() { - return null; - } - - @Override - protected POIXMLFactory getChartFactory() { - return null; - } - }; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFChartExtensionList.java b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFChartExtensionList.java deleted file mode 100644 index f4bd59ec9a..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFChartExtensionList.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xddf.usermodel.chart; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.junit.jupiter.api.Test; - -class TestXDDFChartExtensionList { - - @Test - void getXmlObject() { - // minimal test to include generated classes in poi-ooxml-lite - XDDFChartExtensionList list = new XDDFChartExtensionList(); - assertNotNull(list.getXmlObject()); - - XDDFChartExtensionList list2 = new XDDFChartExtensionList(list.getXmlObject()); - assertEquals(list.getXmlObject(), list2.getXmlObject()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFChartRemoveSeries.java b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFChartRemoveSeries.java deleted file mode 100644 index ca5c40aaf1..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFChartRemoveSeries.java +++ /dev/null @@ -1,174 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xddf.usermodel.chart; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Locale; - -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Test case for bug 63153 - */ -class TestXDDFChartRemoveSeries { - final File resultDir = new File("build/custom-reports-test"); - String procName = null; - String fileName = null; - XSSFWorkbook workbook = null; - XSSFSheet sheet = null; - XDDFScatterChartData chartData = null; - XDDFChart chart = null; - final int MAX_NUM_SERIES = 1; - - public TestXDDFChartRemoveSeries() { - resultDir.mkdirs(); - } - - /** - * This creates a workbook with one worksheet, which contains a single - * scatter chart. - */ - @BeforeEach - void setup() { - final boolean bDebug = false; - workbook = new XSSFWorkbook(); - sheet = workbook.createSheet(); - - final XSSFDrawing xssfDrawing = sheet.createDrawingPatriarch(); - final XSSFClientAnchor anchor = xssfDrawing.createAnchor(0, 0, 0, 0, 1, 5, 20, 20); - if (bDebug) { - return; - } - chart = xssfDrawing.createChart(anchor); - final XDDFValueAxis bottomAxis = chart.createValueAxis(AxisPosition.BOTTOM); - final XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); - - // Initialize data data sources - - final Double dX[] = new Double[5]; - final Double dY1[] = new Double[5]; - final Double dY2[] = new Double[5]; - - for (int n = 0; n < 5; ++n) { - dX[n] = (double) n; - dY1[n] = 2.0 * n; - dY2[n] = (double) (n * n); - - } - - final XDDFNumericalDataSource<Double> xData = XDDFDataSourcesFactory.fromArray(dX, null); - final XDDFNumericalDataSource<Double> yData1 = XDDFDataSourcesFactory.fromArray(dY1, null); - final XDDFNumericalDataSource<Double> yData2 = XDDFDataSourcesFactory.fromArray(dY2, null); - - // Create the chartdata - - chartData = (XDDFScatterChartData) chart.createData(ChartTypes.SCATTER, bottomAxis, leftAxis); - - // Add the series - - chartData.addSeries(xData, yData1); - chartData.addSeries(xData, yData2); - } - - /** - * This method writes the workbook to resultDir/fileName. - */ - @AfterEach - void cleanup() throws IOException { - // Finish up - chart.plot(chartData); - final int index = workbook.getSheetIndex(sheet); - workbook.setSelectedTab(index); - workbook.setActiveSheet(index); - workbook.setFirstVisibleTab(index); - - final File file = new File(resultDir, fileName); - try (OutputStream fileOut = new FileOutputStream(file)) { - workbook.write(fileOut); - } - workbook.close(); - } - - /** - * Attempt to remove the first series by calling chartData.getSeries().remove(0). - * <p> - * This used to corrupt the workbook but the returned <code>List</code> is unmodifiable. - */ - @Test - void testRemoveSeries0() { - procName = "testRemoveSeries0"; - fileName = procName + ".xlsx"; - - assertThrows(UnsupportedOperationException.class, () -> chartData.getSeries().remove(0)); - assertEquals(2, chartData.getSeriesCount()); - } - - /** - * Remove the first series by calling chartData.removeSeries(0). - * <p> - * This will not corrupt the workbook. - */ - @Test - void testBugFixRemoveSeries0() { - procName = "testBugFixRemoveSeries0"; - fileName = procName + ".xlsx"; - - chartData.removeSeries(0); - assertEquals(1, chartData.getSeriesCount()); - } - - /** - * Remove the second series by calling chartData.removeSeries(1). - * <p> - * This will not corrupt the workbook. - */ - @Test - void testBugFixRemoveSeries1() { - procName = "testBugFixRemoveSeries1"; - fileName = procName + ".xlsx"; - - chartData.removeSeries(1); - assertEquals(1, chartData.getSeriesCount()); - } - - /** - * Do not remove any series from the chart. - */ - @Test - void testDontRemoveSeries() { - procName = "testDontRemoveSeries"; - fileName = procName + ".xlsx"; - - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> chartData.removeSeries(2)); - assertEquals("removeSeries(2): illegal index", e.getMessage()); - assertEquals(2, chartData.getSeriesCount()); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFDataSourcesFactory.java b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFDataSourcesFactory.java deleted file mode 100644 index 0cbb10b0f2..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/chart/TestXDDFDataSourcesFactory.java +++ /dev/null @@ -1,145 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xddf.usermodel.chart; - -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetBuilder; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link XDDFDataSourcesFactory}. - */ -class TestXDDFDataSourcesFactory { - - private static final Object[][] numericCells = { - {0.0, 1.0, 2.0, 3.0, 4.0}, - {0.0, "=B1*2", "=C1*2", "=D1*2", "=E1*2"} - }; - - private static final Object[][] stringCells = { - { 1, 2, 3, 4, 5}, - {"A", "B", "C", "D", "E"} - }; - - private static final Object[][] mixedCells = { - {1.0, "2.0", 3.0, "4.0", 5.0, "6.0"} - }; - - @Test - void testNumericArrayDataSource() { - Double[] doubles = new Double[]{1.0, 2.0, 3.0, 4.0, 5.0}; - XDDFDataSource<Double> doubleDataSource = XDDFDataSourcesFactory.fromArray(doubles, null); - assertTrue(doubleDataSource.isNumeric()); - assertFalse(doubleDataSource.isReference()); - assertDataSourceIsEqualToArray(doubleDataSource, doubles); - } - - @Test - void testStringArrayDataSource() { - String[] strings = new String[]{"one", "two", "three", "four", "five"}; - XDDFDataSource<String> stringDataSource = XDDFDataSourcesFactory.fromArray(strings, null); - assertFalse(stringDataSource.isNumeric()); - assertFalse(stringDataSource.isReference()); - assertDataSourceIsEqualToArray(stringDataSource, strings); - } - - @Test - void testNumericCellDataSource() { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, numericCells).build(); - CellRangeAddress numCellRange = CellRangeAddress.valueOf("A2:E2"); - XDDFDataSource<Double> numDataSource = XDDFDataSourcesFactory.fromNumericCellRange(sheet, numCellRange); - assertTrue(numDataSource.isReference()); - assertTrue(numDataSource.isNumeric()); - assertEquals(numericCells[0].length, numDataSource.getPointCount()); - for (int i = 0; i < numericCells[0].length; ++i) { - assertEquals(((Double) numericCells[0][i]) * 2, - numDataSource.getPointAt(i), 0.00001); - } - } - - @Test - void testStringCellDataSource() { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, stringCells).build(); - CellRangeAddress numCellRange = CellRangeAddress.valueOf("A2:E2"); - XDDFDataSource<String> numDataSource = XDDFDataSourcesFactory.fromStringCellRange(sheet, numCellRange); - assertTrue(numDataSource.isReference()); - assertFalse(numDataSource.isNumeric()); - assertEquals(numericCells[0].length, numDataSource.getPointCount()); - for (int i = 0; i < stringCells[1].length; ++i) { - assertEquals(stringCells[1][i], numDataSource.getPointAt(i)); - } - } - - @Test - void testMixedCellDataSource() { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, mixedCells).build(); - CellRangeAddress mixedCellRange = CellRangeAddress.valueOf("A1:F1"); - XDDFDataSource<String> strDataSource = XDDFDataSourcesFactory.fromStringCellRange(sheet, mixedCellRange); - XDDFDataSource<Double> numDataSource = XDDFDataSourcesFactory.fromNumericCellRange(sheet, mixedCellRange); - for (int i = 0; i < mixedCells[0].length; ++i) { - if (i % 2 == 0) { - assertNull(strDataSource.getPointAt(i)); - assertEquals(((Double) mixedCells[0][i]), - numDataSource.getPointAt(i), 0.00001); - } else { - assertNull(numDataSource.getPointAt(i)); - assertEquals(mixedCells[0][i], strDataSource.getPointAt(i)); - } - } - } - - @Test - void testIOBExceptionOnInvalidIndex() { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, numericCells).build(); - CellRangeAddress rangeAddress = CellRangeAddress.valueOf("A2:E2"); - XDDFDataSource<Double> numDataSource = XDDFDataSourcesFactory.fromNumericCellRange(sheet, rangeAddress); - IndexOutOfBoundsException exception = null; - try { - numDataSource.getPointAt(-1); - } catch (IndexOutOfBoundsException e) { - exception = e; - } - assertNotNull(exception); - - exception = null; - try { - numDataSource.getPointAt(numDataSource.getPointCount()); - } catch (IndexOutOfBoundsException e) { - exception = e; - } - assertNotNull(exception); - } - - private <T> void assertDataSourceIsEqualToArray(XDDFDataSource<T> ds, T[] array) { - assertEquals(ds.getPointCount(), array.length); - for (int i = 0; i < array.length; ++i) { - assertEquals(ds.getPointAt(i), array[i]); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/text/TestXDDFTextBodyProperties.java b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/text/TestXDDFTextBodyProperties.java deleted file mode 100644 index 1d98b42e44..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/text/TestXDDFTextBodyProperties.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xddf.usermodel.text; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.util.Units; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBodyProperties; - -class TestXDDFTextBodyProperties { - - @Test - void testProperties() throws IOException { - XDDFTextBody text = new XDDFTextBody(null); - text.initialize(); - XDDFBodyProperties body = text.getBodyProperties(); - CTTextBodyProperties props = body.getXmlObject(); - - body.setBottomInset(null); - assertFalse(props.isSetBIns()); - body.setBottomInset(3.6); - assertTrue(props.isSetBIns()); - assertEquals(Units.toEMU(3.6), props.getBIns()); - - body.setLeftInset(null); - assertFalse(props.isSetLIns()); - body.setLeftInset(3.6); - assertTrue(props.isSetLIns()); - assertEquals(Units.toEMU(3.6), props.getLIns()); - - body.setRightInset(null); - assertFalse(props.isSetRIns()); - body.setRightInset(3.6); - assertTrue(props.isSetRIns()); - assertEquals(Units.toEMU(3.6), props.getRIns()); - - body.setTopInset(null); - assertFalse(props.isSetTIns()); - body.setTopInset(3.6); - assertTrue(props.isSetTIns()); - assertEquals(Units.toEMU(3.6), props.getTIns()); - - body.setAutoFit(null); - assertFalse(props.isSetNoAutofit()); - assertFalse(props.isSetNormAutofit()); - assertFalse(props.isSetSpAutoFit()); - - body.setAutoFit(new XDDFNoAutoFit()); - assertTrue(props.isSetNoAutofit()); - assertFalse(props.isSetNormAutofit()); - assertFalse(props.isSetSpAutoFit()); - - body.setAutoFit(new XDDFNormalAutoFit()); - assertFalse(props.isSetNoAutofit()); - assertTrue(props.isSetNormAutofit()); - assertFalse(props.isSetSpAutoFit()); - - body.setAutoFit(new XDDFShapeAutoFit()); - assertFalse(props.isSetNoAutofit()); - assertFalse(props.isSetNormAutofit()); - assertTrue(props.isSetSpAutoFit()); - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/text/TestXDDFTextRun.java b/src/ooxml/testcases/org/apache/poi/xddf/usermodel/text/TestXDDFTextRun.java deleted file mode 100644 index 90c7759e6b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xddf/usermodel/text/TestXDDFTextRun.java +++ /dev/null @@ -1,165 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xddf.usermodel.text; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -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.io.InputStream; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFShape; -import org.apache.poi.xslf.usermodel.XSLFSlide; -import org.apache.poi.xslf.usermodel.XSLFTextShape; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFTextBox; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -class TestXDDFTextRun { - - @Test - void testTextRunPropertiesInSlide() throws IOException { - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - sh.addNewTextParagraph(); - - XDDFTextBody body = sh.getTextBody(); - body.initialize(); - XDDFTextParagraph para = body.getParagraph(0); - XDDFTextRun r = para.appendRegularRun("text"); - assertEquals(LocaleUtil.getUserLocale().toLanguageTag(), r.getLanguage().toLanguageTag()); - - assertNull(r.getCharacterSpacing()); - r.setCharacterSpacing(3.0); - assertEquals(3., r.getCharacterSpacing(), 0); - r.setCharacterSpacing(-3.0); - assertEquals(-3., r.getCharacterSpacing(), 0); - r.setCharacterSpacing(0.0); - assertEquals(0., r.getCharacterSpacing(), 0); - - assertEquals(11.0, r.getFontSize(), 0); - r.setFontSize(13.0); - assertEquals(13.0, r.getFontSize(), 0); - - assertFalse(r.isSuperscript()); - r.setSuperscript(0.8); - assertTrue(r.isSuperscript()); - r.setSuperscript(null); - assertFalse(r.isSuperscript()); - - assertFalse(r.isSubscript()); - r.setSubscript(0.7); - assertTrue(r.isSubscript()); - r.setSubscript(null); - assertFalse(r.isSubscript()); - - r.setBaseline(0.9); - assertTrue(r.isSuperscript()); - r.setBaseline(-0.6); - assertTrue(r.isSubscript()); - } - } - - @Test - void testTextRunPropertiesInSheet() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - - shape.addNewTextParagraph().addNewTextRun().setText("Line 1"); - - XDDFTextBody body = shape.getTextBody(); - XDDFTextParagraph para = body.getParagraph(1); - List<XDDFTextRun> runs = para.getTextRuns(); - assertEquals(1, runs.size()); - - XDDFTextRun run = runs.get(0); - assertEquals("Line 1", run.getText()); - - assertFalse(run.isStrikeThrough()); - run.setStrikeThrough(StrikeType.SINGLE_STRIKE); - assertTrue(run.isStrikeThrough()); - run.setStrikeThrough(StrikeType.NO_STRIKE); - assertFalse(run.isStrikeThrough()); - - assertFalse(run.isCapitals()); - run.setCapitals(CapsType.SMALL); - assertTrue(run.isCapitals()); - run.setCapitals(CapsType.NONE); - assertFalse(run.isCapitals()); - - assertFalse(run.isBold()); - run.setBold(true); - assertTrue(run.isBold()); - run.setBold(false); - assertFalse(run.isBold()); - - assertFalse(run.isItalic()); - run.setItalic(true); - assertTrue(run.isItalic()); - run.setItalic(false); - assertFalse(run.isItalic()); - - assertFalse(run.isUnderline()); - run.setUnderline(UnderlineType.WAVY_DOUBLE); - assertTrue(run.isUnderline()); - run.setUnderline(UnderlineType.NONE); - assertFalse(run.isUnderline()); - - assertNotNull(run.getText()); - } - } - - @Test - void testDefaultRunProperties() throws IOException { - // bug #63290 - POIDataSamples pds = POIDataSamples.getSlideShowInstance(); - try (InputStream is = pds.openResourceAsStream("bug63290.pptx"); - XMLSlideShow ppt = new XMLSlideShow(is)) { - XSLFSlide slide = ppt.getSlides().get(0); - for (XSLFShape shape : slide.getShapes()) { - if (shape instanceof XSLFTextShape) { - XSLFTextShape text = (XSLFTextShape) shape; - XDDFTextParagraph paragraph = text.getTextBody().getParagraph(0); - XDDFTextRun defaultRun = paragraph.getTextRuns().get(0); - assertEquals("DefaultRunProperties", defaultRun.getText().trim()); - XDDFTextRun explicitRun = paragraph.getTextRuns().get(1); - assertEquals("ExplicitRunProperties", explicitRun.getText().trim()); - assertEquals(defaultRun.getDirty(), explicitRun.getDirty()); - assertEquals(defaultRun.getFontSize(), explicitRun.getFontSize()); - assertEquals(defaultRun.getLanguage(), explicitRun.getLanguage()); - assertEquals(defaultRun.getSpellError(), explicitRun.getSpellError()); - assertNotEquals(defaultRun.getFontColor(), explicitRun.getFontColor()); - } - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xdgf/extractor/TestXDGFVisioExtractor.java b/src/ooxml/testcases/org/apache/poi/xdgf/extractor/TestXDGFVisioExtractor.java deleted file mode 100644 index adc76e554a..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xdgf/extractor/TestXDGFVisioExtractor.java +++ /dev/null @@ -1,99 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xdgf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xdgf.usermodel.XmlVisioDocument; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestXDGFVisioExtractor { - - private static final POIDataSamples SAMPLES = POIDataSamples.getDiagramInstance(); - private OPCPackage pkg; - private XmlVisioDocument xml; - - @BeforeEach - void setUp() throws Exception { - pkg = OPCPackage.open(SAMPLES.openResourceAsStream("test_text_extraction.vsdx")); - xml = new XmlVisioDocument(pkg); - } - - @AfterEach - void closeResources() throws IOException { - if(xml != null) { - xml.close(); - } - pkg.close(); - } - - @Test - void testGetSimpleText() throws IOException { - new XDGFVisioExtractor(xml).close(); - new XDGFVisioExtractor(pkg).close(); - - XDGFVisioExtractor extractor = new XDGFVisioExtractor(xml); - extractor.getText(); - - String text = extractor.getText(); - String expected = "Text here\nText there\nText, text, everywhere!\nRouter here\n"; - assertEquals(expected, text); - - extractor.close(); - } - - - //the point of this is to trigger the addition of - //some common visio classes -- ConnectsType - @Test - void testVisioConnects() throws IOException { - InputStream is = SAMPLES.openResourceAsStream("60489.vsdx"); - XmlVisioDocument document = new XmlVisioDocument(is); - is.close(); - XDGFVisioExtractor extractor = new XDGFVisioExtractor(document); - String text = extractor.getText(); - assertContains(text, "Arrears"); - extractor.close(); - } - - /** - * Some confusion on PolylineTo vs PolyLineTo, both should be handled. - * Previously failed with: - * org.apache.poi.ooxml.POIXMLException: Invalid 'Row_Type' name 'PolylineTo' - * at org.apache.poi.xdgf.util.ObjectFactory.load - * at org.apache.poi.xdgf.usermodel.section.geometry.GeometryRowFactory.load - */ - @Test - void testPolylineTo() throws IOException { - InputStream is = SAMPLES.openResourceAsStream("60973.vsdx"); - XmlVisioDocument document = new XmlVisioDocument(is); - is.close(); - XDGFVisioExtractor extractor = new XDGFVisioExtractor(document); - String text = extractor.getText(); - assertContains(text, "42 U"); - assertContains(text, "Access VLANS"); - extractor.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xdgf/usermodel/section/TestCombinedIterator.java b/src/ooxml/testcases/org/apache/poi/xdgf/usermodel/section/TestCombinedIterator.java deleted file mode 100644 index 5679c28cd9..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xdgf/usermodel/section/TestCombinedIterator.java +++ /dev/null @@ -1,160 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Iterator; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.junit.jupiter.api.Test; - -class TestCombinedIterator { - - void testIteration(CombinedIterable<String> iterable, String... expected) { - - Iterator<String> iter = iterable.iterator(); - - for (String element : expected) { - assertTrue(iter.hasNext()); - assertEquals(element, iter.next()); - } - - assertFalse(iter.hasNext()); - } - - @Test - void testNullMaster() { - - SortedMap<Long, String> base = new TreeMap<>(); - base.put(1L, "B1"); - base.put(2L, "B2"); - base.put(3L, "B3"); - - testIteration(new CombinedIterable<>(base, null), "B1", "B2", - "B3"); - } - - @Test - void testNoMatchesBaseFirst() { - - SortedMap<Long, String> base = new TreeMap<>(); - base.put(1L, "B1"); - base.put(2L, "B2"); - base.put(3L, "B3"); - - SortedMap<Long, String> master = new TreeMap<>(); - master.put(4L, "M4"); - master.put(5L, "M5"); - master.put(6L, "M6"); - - testIteration(new CombinedIterable<>(base, master), "B1", "B2", - "B3", "M4", "M5", "M6"); - } - - @Test - void testNoMatchesMasterFirst() { - - SortedMap<Long, String> base = new TreeMap<>(); - base.put(4L, "B4"); - base.put(5L, "B5"); - base.put(6L, "B6"); - - SortedMap<Long, String> master = new TreeMap<>(); - master.put(1L, "M1"); - master.put(2L, "M2"); - master.put(3L, "M3"); - - testIteration(new CombinedIterable<>(base, master), "M1", "M2", - "M3", "B4", "B5", "B6"); - } - - @Test - void testInterleaved1() { - - SortedMap<Long, String> base = new TreeMap<>(); - base.put(1L, "B1"); - base.put(3L, "B3"); - base.put(5L, "B5"); - - SortedMap<Long, String> master = new TreeMap<>(); - master.put(2L, "M2"); - master.put(4L, "M4"); - master.put(6L, "M6"); - - testIteration(new CombinedIterable<>(base, master), "B1", "M2", - "B3", "M4", "B5", "M6"); - } - - @Test - void testInterleaved2() { - - SortedMap<Long, String> base = new TreeMap<>(); - base.put(1L, "B1"); - base.put(2L, "B2"); - base.put(5L, "B5"); - base.put(6L, "B6"); - - SortedMap<Long, String> master = new TreeMap<>(); - master.put(3L, "M3"); - master.put(4L, "M4"); - master.put(7L, "M7"); - master.put(8L, "M8"); - - testIteration(new CombinedIterable<>(base, master), "B1", "B2", - "M3", "M4", "B5", "B6", "M7", "M8"); - } - - @Test - void testAllMatching() { - - SortedMap<Long, String> base = new TreeMap<>(); - base.put(1L, "B1"); - base.put(2L, "B2"); - base.put(3L, "B3"); - - SortedMap<Long, String> master = new TreeMap<>(); - master.put(1L, "M1"); - master.put(2L, "M2"); - master.put(3L, "M3"); - - testIteration(new CombinedIterable<>(base, master), "B1", "B2", - "B3"); - } - - @Test - void testAllMatching2() { - - SortedMap<Long, String> base = new TreeMap<>(); - base.put(1L, "B1"); - base.put(2L, "B2"); - base.put(3L, "B3"); - - SortedMap<Long, String> master = new TreeMap<>(); - master.put(1L, "M1"); - master.put(2L, "M2"); - master.put(3L, "M3"); - master.put(4L, "M4"); - - testIteration(new CombinedIterable<>(base, master), "B1", "B2", - "B3", "M4"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/TestNecessaryOOXMLClasses.java b/src/ooxml/testcases/org/apache/poi/xslf/TestNecessaryOOXMLClasses.java deleted file mode 100644 index 307348f011..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/TestNecessaryOOXMLClasses.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.util.Arrays; -import java.util.List; -import java.util.function.Supplier; - -import org.apache.xmlbeans.XmlObject; -import org.junit.jupiter.api.Test; - -// aim is to get these classes loaded and included in poi-ooxml-lite.jar -class TestNecessaryOOXMLClasses { - - @Test - void testProblemClasses() { - List<Supplier<XmlObject>> sup = Arrays.asList( - org.openxmlformats.schemas.presentationml.x2006.main.STPlaceholderSize.Factory::newInstance, - org.openxmlformats.schemas.presentationml.x2006.main.CTHeaderFooter.Factory::newInstance - ); - - for (Supplier<XmlObject> xo : sup) { - assertNotNull(xo.get()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFBugs.java b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFBugs.java deleted file mode 100644 index acbf365046..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFBugs.java +++ /dev/null @@ -1,1083 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.sl.draw.DrawTextParagraph.HYPERLINK_HREF; -import static org.apache.poi.sl.draw.DrawTextParagraph.HYPERLINK_LABEL; -import static org.apache.poi.xslf.XSLFTestDataSamples.openSampleDocument; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.text.AttributedCharacterIterator; -import java.text.AttributedCharacterIterator.Attribute; -import java.text.CharacterIterator; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.ooxml.POIXMLDocumentPart; -import org.apache.poi.ooxml.POIXMLDocumentPart.RelationPart; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.extractor.SlideShowExtractor; -import org.apache.poi.sl.usermodel.Hyperlink; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.PaintStyle.TexturePaint; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.sl.usermodel.PictureShape; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.sl.usermodel.TextShape; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NullPrintStream; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFAutoShape; -import org.apache.poi.xslf.usermodel.XSLFGroupShape; -import org.apache.poi.xslf.usermodel.XSLFHyperlink; -import org.apache.poi.xslf.usermodel.XSLFNotes; -import org.apache.poi.xslf.usermodel.XSLFObjectShape; -import org.apache.poi.xslf.usermodel.XSLFPictureData; -import org.apache.poi.xslf.usermodel.XSLFPictureShape; -import org.apache.poi.xslf.usermodel.XSLFRelation; -import org.apache.poi.xslf.usermodel.XSLFShape; -import org.apache.poi.xslf.usermodel.XSLFSlide; -import org.apache.poi.xslf.usermodel.XSLFSlideLayout; -import org.apache.poi.xslf.usermodel.XSLFSlideMaster; -import org.apache.poi.xslf.usermodel.XSLFTable; -import org.apache.poi.xslf.usermodel.XSLFTableCell; -import org.apache.poi.xslf.usermodel.XSLFTableRow; -import org.apache.poi.xslf.usermodel.XSLFTextBox; -import org.apache.poi.xslf.usermodel.XSLFTextParagraph; -import org.apache.poi.xslf.usermodel.XSLFTextRun; -import org.apache.poi.xslf.util.DummyGraphics2d; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.ThrowingSupplier; -import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; - -class TestXSLFBugs { - private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - - private static boolean xslfOnly; - - @BeforeAll - public static void checkHslf() { - try { - Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); - } catch (Exception e) { - xslfOnly = true; - } - } - - @Test - void bug62929() throws Exception { - try (XMLSlideShow ss1 = openSampleDocument("missing-blip-fill.pptx")) { - assertEquals(1, ss1.getSlides().size()); - - XSLFSlide slide = ss1.getSlides().get(0); - - assertEquals(slide.getShapes().size(), 1); - - XSLFPictureShape picture = (XSLFPictureShape) slide.getShapes().get(0); - - assertEquals(picture.getShapeId(), 662); - assertFalse(picture.isExternalLinkedPicture()); - assertNull(picture.getPictureData()); - assertNull(picture.getPictureLink()); - assertNull(picture.getClipping()); - } - } - - @Test - void bug62736() throws Exception { - XMLSlideShow ss1 = openSampleDocument("bug62736.pptx"); - - assertEquals(1, ss1.getSlides().size()); - - XSLFSlide slide0 = ss1.getSlides().get(0); - - assertEquals(slide0.getShapes().size(), 4); - - 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); - - List<XSLFPictureShape> pictures = new ArrayList<>(); - for (XSLFShape shape : slide0.getShapes()) { - if (shape instanceof XSLFPictureShape) { - pictures.add((XSLFPictureShape) shape); - } - } - - assertEquals(pictures.size(), 2); - assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png"); - assertEquals(pictures.get(1).getPictureData().getFileName(), "image1.png"); - // blipId is rId2 of both pictures - - // remove just the first picture - slide0.removeShape(pictures.get(0)); - - assertEquals(slide0.getShapes().size(), 3); - - 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); - - // Save and re-load - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss1); - ss1.close(); - assertEquals(1, ss2.getSlides().size()); - - slide0 = ss2.getSlides().get(0); - - 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); - - pictures.clear(); - for (XSLFShape shape : slide0.getShapes()) { - if (shape instanceof XSLFPictureShape) { - pictures.add((XSLFPictureShape) shape); - } - } - - assertEquals(pictures.size(), 1); - assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png"); - - slide0.removeShape(pictures.get(0)); - - assertEquals(slide0.getShapes().size(), 2); - - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); - assertNull(slide0.getRelationById("rId2")); - assertEquals(slide0.getRelations().size(), 1); - - // Save and re-load - XMLSlideShow ss3 = XSLFTestDataSamples.writeOutAndReadBack(ss2); - ss2.close(); - assertEquals(1, ss3.getSlides().size()); - - slide0 = ss3.getSlides().get(0); - - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); - assertEquals(slide0.getShapes().size(), 2); - ss3.close(); - } - - @Test - void bug61589() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (XMLSlideShow src = new XMLSlideShow(); - XMLSlideShow dest = new XMLSlideShow()) { - XSLFSlide slide = src.createSlide(); - XSLFSlide slide2 = src.createSlide(); - - XSLFTextBox shape = slide.createTextBox(); - shape.setAnchor(new Rectangle2D.Double(100, 100, 400, 100)); - XSLFTextParagraph p = shape.addNewTextParagraph(); - - XSLFTextRun r = p.addNewTextRun(); - p.addLineBreak(); - r.setText("Apache POI"); - r.createHyperlink().setAddress("https://poi.apache.org"); - // create hyperlink pointing to a page, which isn't available at the time of importing the content - r = p.addNewTextRun(); - r.setText("Slide 2"); - r.createHyperlink().linkToSlide(slide2); - - shape = slide2.createTextBox(); - shape.setAnchor(new Rectangle2D.Double(100, 100, 400, 100)); - shape.setText("slide 2"); - - dest.createSlide().importContent(slide); - dest.createSlide().importContent(slide2); - - dest.write(bos); - } - - try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray()))) { - XSLFSlide slide = ppt.getSlides().get(0); - XSLFTextBox shape = (XSLFTextBox) slide.getShapes().get(0); - XSLFTextParagraph p = shape.getTextParagraphs().get(1); - XSLFHyperlink h1 = p.getTextRuns().get(0).getHyperlink(); - assertNotNull(h1); - assertEquals("https://poi.apache.org", h1.getAddress()); - XSLFHyperlink h2 = p.getTextRuns().get(2).getHyperlink(); - assertNotNull(h2); - // relative url will be resolved to an absolute url, therefore this doesn't equals to "slide2.xml" - assertEquals("/ppt/slides/slide2.xml", h2.getAddress()); - RelationPart sldRef = slide.getRelationPartById(h2.getXmlObject().getId()); - assertTrue(sldRef.getDocumentPart() instanceof XSLFSlide); - } - } - - @Test - void bug62587() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (XMLSlideShow ppt = new XMLSlideShow()) { - Slide<?, ?> slide = ppt.createSlide(); - XSLFPictureData pd = ppt.addPicture(slTests.getFile("wrench.emf"), PictureType.EMF); - PictureShape<?, ?> ps = slide.createPicture(pd); - ps.setAnchor(new Rectangle2D.Double(100, 100, 100, 100)); - ppt.write(bos); - } - - Object[][] pics = { - {"santa.wmf", PictureType.WMF, XSLFRelation.IMAGE_WMF}, - {"tomcat.png", PictureType.PNG, XSLFRelation.IMAGE_PNG}, - {"clock.jpg", PictureType.JPEG, XSLFRelation.IMAGE_JPEG} - }; - - try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray()))) { - XSLFSlide s1 = ppt.getSlides().get(0); - - for (Object[] p : pics) { - XSLFSlide s2 = ppt.createSlide(); - s2.importContent(s1); - - XSLFPictureData pd = ppt.addPicture(slTests.getFile((String) p[0]), (PictureType) p[1]); - XSLFPictureShape ps = (XSLFPictureShape) s2.getShapes().get(0); - Rectangle2D anchor = ps.getAnchor(); - s2.removeShape(ps); - ps = s2.createPicture(pd); - ps.setAnchor(anchor); - } - - bos.reset(); - ppt.write(bos); - } - - try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray()))) { - for (XSLFSlide sl : ppt.getSlides()) { - List<RelationPart> rels = sl.getRelationParts(); - assertEquals(2, rels.size()); - RelationPart rel0 = rels.get(0); - assertEquals("rId1", rel0.getRelationship().getId()); - assertEquals(XSLFRelation.SLIDE_LAYOUT.getRelation(), rel0.getRelationship().getRelationshipType()); - RelationPart rel1 = rels.get(1); - assertEquals("rId2", rel1.getRelationship().getId()); - assertEquals(XSLFRelation.IMAGES.getRelation(), rel1.getRelationship().getRelationshipType()); - } - } - } - - - @Test - void bug60499() throws IOException, InvalidFormatException { - InputStream is = slTests.openResourceAsStream("bug60499.pptx"); - byte[] buf = IOUtils.toByteArray(is); - is.close(); - - PackagePartName ppn = PackagingURIHelper.createPartName("/ppt/media/image1.png"); - - XMLSlideShow ppt1 = new XMLSlideShow(new ByteArrayInputStream(buf)); - XSLFSlide slide1 = ppt1.getSlides().get(0); - - Optional<XSLFShape> shapeToDelete1 = - slide1.getShapes().stream().filter(s -> s instanceof XSLFPictureShape).findFirst(); - - assertTrue(shapeToDelete1.isPresent()); - slide1.removeShape(shapeToDelete1.get()); - assertTrue(slide1.getRelationParts().stream() - .allMatch(rp -> "rId1,rId3".contains(rp.getRelationship().getId()))); - - assertNotNull(ppt1.getPackage().getPart(ppn)); - ppt1.close(); - - XMLSlideShow ppt2 = new XMLSlideShow(new ByteArrayInputStream(buf)); - XSLFSlide slide2 = ppt2.getSlides().get(0); - - Optional<XSLFShape> shapeToDelete2 = - slide2.getShapes().stream().filter(s -> s instanceof XSLFPictureShape).skip(1).findFirst(); - assertTrue(shapeToDelete2.isPresent()); - slide2.removeShape(shapeToDelete2.get()); - assertTrue(slide2.getRelationParts().stream() - .allMatch(rp -> "rId1,rId2".contains(rp.getRelationship().getId()))); - assertNotNull(ppt2.getPackage().getPart(ppn)); - ppt2.close(); - - XMLSlideShow ppt3 = new XMLSlideShow(new ByteArrayInputStream(buf)); - XSLFSlide slide3 = ppt3.getSlides().get(0); - slide3.getShapes().stream() - .filter(s -> s instanceof XSLFPictureShape) - .collect(Collectors.toList()) - .forEach(slide3::removeShape); - assertNull(ppt3.getPackage().getPart(ppn)); - ppt3.close(); - } - - @Test - void bug51187() throws Exception { - XMLSlideShow ss1 = openSampleDocument("51187.pptx"); - - assertEquals(1, ss1.getSlides().size()); - - // Check the relations on it - // Note - rId3 is a self reference - XSLFSlide slide0 = ss1.getSlides().get(0); - - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); - assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); - assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); - assertRelation(slide0, "/ppt/media/image1.png", "rId4"); - - // Save and re-load - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss1); - ss1.close(); - assertEquals(1, ss2.getSlides().size()); - - slide0 = ss2.getSlides().get(0); - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); - assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); - // TODO Fix this - assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); - assertRelation(slide0, "/ppt/media/image1.png", "rId4"); - - ss2.close(); - } - - private static void assertRelation(XSLFSlide slide, String exp, String rId) { - POIXMLDocumentPart pd = (rId != null) ? slide.getRelationById(rId) : slide; - assertNotNull(pd); - assertEquals(exp, pd.getPackagePart().getPartName().getName()); - } - - /** - * Slide relations with anchors in them - */ - @Test - void tika705() throws Exception { - XMLSlideShow ss = openSampleDocument("with_japanese.pptx"); - - // Should have one slide - assertEquals(1, ss.getSlides().size()); - XSLFSlide slide = ss.getSlides().get(0); - - // Check the relations from this - Collection<RelationPart> rels = slide.getRelationParts(); - - // Should have 6 relations: - // 1 external hyperlink (skipped from list) - // 4 internal hyperlinks - // 1 slide layout - assertEquals(5, rels.size()); - int layouts = 0; - int hyperlinks = 0; - for (RelationPart p : rels) { - if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { - hyperlinks++; - } else if (p.getDocumentPart() instanceof XSLFSlideLayout) { - layouts++; - } - } - assertEquals(1, layouts); - assertEquals(4, hyperlinks); - - // Hyperlinks should all be to #_ftn1 or #ftnref1 - for (RelationPart p : rels) { - if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { - URI target = p.getRelationship().getTargetURI(); - String frag = target.getFragment(); - assertTrue(frag.equals("_ftn1") || frag.equals("_ftnref1"), "Invalid target " + frag + " on " + target); - } - } - ss.close(); - } - - /** - * A slideshow can have more than one rID pointing to a given - * slide, eg presentation.xml rID1 -> slide1.xml, but slide1.xml - * rID2 -> slide3.xml - */ - @Test - void bug54916() throws IOException { - try (XMLSlideShow ss = openSampleDocument("OverlappingRelations.pptx")) { - XSLFSlide slide; - - // Should find 4 slides - assertEquals(4, ss.getSlides().size()); - - // Check the text, to see we got them in order - slide = ss.getSlides().get(0); - assertContains(getSlideText(ss, slide), "POI cannot read this"); - - slide = ss.getSlides().get(1); - assertContains(getSlideText(ss, slide), "POI can read this"); - assertContains(getSlideText(ss, slide), "Has a relationship to another slide"); - - slide = ss.getSlides().get(2); - assertContains(getSlideText(ss, slide), "POI can read this"); - - slide = ss.getSlides().get(3); - assertContains(getSlideText(ss, slide), "POI can read this"); - } - } - - /** - * When the picture is not embedded but inserted only as a "link to file", - * there is no data available and XSLFPictureShape.getPictureData() - * gives a NPE, see bug #56812 - */ - @Test - void bug56812() throws Exception { - XMLSlideShow ppt = openSampleDocument("56812.pptx"); - - int internalPictures = 0; - int externalPictures = 0; - for (XSLFSlide slide : ppt.getSlides()) { - for (XSLFShape shape : slide.getShapes()) { - assertNotNull(shape); - - if (shape instanceof XSLFPictureShape) { - XSLFPictureShape picture = (XSLFPictureShape) shape; - if (picture.isExternalLinkedPicture()) { - externalPictures++; - - assertNotNull(picture.getPictureLink()); - } else { - internalPictures++; - - XSLFPictureData data = picture.getPictureData(); - assertNotNull(data); - assertNotNull(data.getFileName()); - } - } - } - } - - assertEquals(2, internalPictures); - assertEquals(1, externalPictures); - ppt.close(); - } - - private String getSlideText(XMLSlideShow ppt, XSLFSlide slide) throws IOException { - try (SlideShowExtractor<XSLFShape, XSLFTextParagraph> extr = new SlideShowExtractor<>(ppt)) { - // do not auto-close the slideshow - extr.setCloseFilesystem(false); - extr.setSlidesByDefault(true); - extr.setNotesByDefault(false); - extr.setMasterByDefault(false); - return extr.getText(slide); - } - } - - @Test - void bug57250() throws Exception { - XMLSlideShow ss = new XMLSlideShow(); - for (String s : new String[]{"Slide1", "Slide2"}) { - ss.createSlide().createTextBox().setText(s); - } - validateSlides(ss, false, "Slide1", "Slide2"); - - XSLFSlide slide = ss.createSlide(); - slide.createTextBox().setText("New slide"); - validateSlides(ss, true, "Slide1", "Slide2", "New slide"); - - // Move backward - ss.setSlideOrder(slide, 0); - validateSlides(ss, true, "New slide", "Slide1", "Slide2"); - - // Move forward - ss.setSlideOrder(slide, 1); - validateSlides(ss, true, "Slide1", "New slide", "Slide2"); - - // Move to end - ss.setSlideOrder(slide, 0); - ss.setSlideOrder(slide, 2); - validateSlides(ss, true, "Slide1", "Slide2", "New slide"); - ss.close(); - } - - /** - * When working with >9 images, make sure the sorting ensures - * that image10.foo isn't between image1.foo and image2.foo - */ - @Test - void test57552() throws Exception { - XMLSlideShow ss = new XMLSlideShow(); - for (String s : new String[]{"Slide1", "Slide2"}) { - ss.createSlide().createTextBox().setText(s); - } - - // Slide starts with just layout relation - XSLFSlide slide = ss.getSlides().get(0); - assertEquals(0, ss.getPictureData().size()); - assertEquals(1, slide.getShapes().size()); - - assertEquals(1, slide.getRelations().size()); - - final XSLFRelation expected = XSLFRelation.SLIDE_LAYOUT; - final POIXMLDocumentPart relation = slide.getRelations().get(0); - - assertEquals(expected.getContentType(), relation.getPackagePart().getContentType()); - assertEquals(expected.getFileName(expected.getFileNameIndex(relation)), relation.getPackagePart().getPartName().getName()); - - // Some dummy pictures - byte[][] pics = new byte[15][3]; - for (int i = 0; i < pics.length; i++) { - Arrays.fill(pics[i], (byte) i); - } - - // Add a few pictures - addPictures(ss, slide, pics, 0, 10); - - // Re-fetch the pictures and check - for (int i = 0; i < 10; i++) { - XSLFPictureShape shape = (XSLFPictureShape) slide.getShapes().get(i + 1); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[i], shape.getPictureData().getData()); - } - - // Add past 10 - addPictures(ss, slide, pics, 10, 15); - - // Check all pictures - for (int i = 0; i < 15; i++) { - XSLFPictureShape shape = (XSLFPictureShape) slide.getShapes().get(i + 1); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[i], shape.getPictureData().getData()); - } - - // Add a duplicate, check the right one is picked - XSLFPictureData data = ss.addPicture(pics[3], PictureType.JPEG); - assertEquals(3, data.getIndex()); - assertEquals(15, ss.getPictureData().size()); - - XSLFPictureShape shape = slide.createPicture(data); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[3], shape.getPictureData().getData()); - assertEquals(17, slide.getShapes().size()); - - - // Save and re-load - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss); - slide = ss2.getSlides().get(0); - - // Check the 15 individual ones added - for (int i = 0; i < 15; i++) { - shape = (XSLFPictureShape) slide.getShapes().get(i + 1); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[i], shape.getPictureData().getData()); - } - - // Check the duplicate - shape = (XSLFPictureShape) slide.getShapes().get(16); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[3], shape.getPictureData().getData()); - - // Add another duplicate - data = ss2.addPicture(pics[5], PictureType.JPEG); - assertEquals(5, data.getIndex()); - assertEquals(15, ss2.getPictureData().size()); - - shape = slide.createPicture(data); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[5], shape.getPictureData().getData()); - assertEquals(18, slide.getShapes().size()); - - ss2.close(); - ss.close(); - } - - private void addPictures(XMLSlideShow ss, XSLFSlide slide, byte[][] pics, int start, int end) { - for (int i = start; i < end; i++) { - XSLFPictureData data = ss.addPicture(pics[i], PictureType.JPEG); - assertEquals(i, data.getIndex()); - assertEquals(i + 1, ss.getPictureData().size()); - - XSLFPictureShape shape = slide.createPicture(data); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[i], shape.getPictureData().getData()); - assertEquals(i + 2, slide.getShapes().size()); - } - } - - private void validateSlides(XMLSlideShow ss, boolean saveAndReload, String... slideTexts) throws IOException { - if (saveAndReload) { - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss); - validateSlides(ss, slideTexts); - ss2.close(); - } else { - validateSlides(ss, slideTexts); - } - } - - private void validateSlides(XMLSlideShow ss, String... slideTexts) throws IOException { - assertEquals(slideTexts.length, ss.getSlides().size()); - - for (int i = 0; i < slideTexts.length; i++) { - XSLFSlide slide = ss.getSlides().get(i); - assertContains(getSlideText(ss, slide), slideTexts[i]); - } - } - - @Test - void bug58205() throws IOException { - XMLSlideShow ss = openSampleDocument("themes.pptx"); - - int i = 1; - for (XSLFSlideMaster sm : ss.getSlideMasters()) { - assertEquals("rId" + (i++), ss.getRelationId(sm)); - } - - ss.close(); - } - - @Test - void bug55791a() throws IOException { - XMLSlideShow ppt = openSampleDocument("45541_Footer.pptx"); - removeAndCreateSlide(ppt); - ppt.close(); - } - - @Test - void bug55791b() throws IOException { - XMLSlideShow ppt = openSampleDocument("SampleShow.pptx"); - removeAndCreateSlide(ppt); - ppt.close(); - } - - private void removeAndCreateSlide(XMLSlideShow ppt) { - assertTrue(ppt.getSlides().size() > 1); - ppt.removeSlide(1); - assertNotNull(ppt.createSlide()); - } - - @Test - void blibFillAlternateContent() throws IOException { - XMLSlideShow ppt = openSampleDocument("2411-Performance_Up.pptx"); - XSLFPictureShape ps = (XSLFPictureShape) ppt.getSlides().get(4).getShapes().get(0); - assertNotNull(ps.getPictureData()); - ppt.close(); - } - - @Test - void bug59434() throws IOException { - String url1 = "https://poi.apache.org/changes.html"; - String url2 = "https://poi.apache.org/faq.html"; - XMLSlideShow ppt1 = new XMLSlideShow(); - PictureData pd1 = ppt1.addPicture(slTests.readFile("tomcat.png"), PictureType.PNG); - PictureData pd2 = ppt1.addPicture(slTests.readFile("santa.wmf"), PictureType.WMF); - XSLFSlide slide = ppt1.createSlide(); - XSLFPictureShape ps1 = slide.createPicture(pd1); - ps1.setAnchor(new Rectangle2D.Double(20, 20, 100, 100)); - XSLFHyperlink hl1 = ps1.createHyperlink(); - hl1.linkToUrl(url1); - XSLFPictureShape ps2 = slide.createPicture(pd2); - ps2.setAnchor(new Rectangle2D.Double(120, 120, 100, 100)); - XSLFHyperlink hl2 = ps2.createHyperlink(); - hl2.linkToUrl(url2); - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - slide = ppt2.getSlides().get(0); - ps1 = (XSLFPictureShape) slide.getShapes().get(0); - ps2 = (XSLFPictureShape) slide.getShapes().get(1); - assertEquals(url1, ps1.getHyperlink().getAddress()); - assertEquals(url2, ps2.getHyperlink().getAddress()); - - ppt2.close(); - } - - @Test - void bug58217() throws IOException { - Color fillColor = new Color(1f, 1f, 0f, 0.1f); - Color lineColor = new Color(25.3f / 255f, 1f, 0f, 0.4f); - Color textColor = new Color(1f, 1f, 0f, 0.6f); - - XMLSlideShow ppt1 = new XMLSlideShow(); - XSLFSlide sl = ppt1.createSlide(); - XSLFAutoShape as = sl.createAutoShape(); - as.setShapeType(ShapeType.STAR_10); - as.setAnchor(new Rectangle2D.Double(100, 100, 300, 300)); - as.setFillColor(fillColor); - as.setLineColor(lineColor); - as.setText("Alpha"); - as.setVerticalAlignment(VerticalAlignment.MIDDLE); - as.setHorizontalCentered(true); - XSLFTextRun tr = as.getTextParagraphs().get(0).getTextRuns().get(0); - tr.setFontSize(32d); - tr.setFontColor(textColor); - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - sl = ppt2.getSlides().get(0); - as = (XSLFAutoShape) sl.getShapes().get(0); - checkColor(fillColor, as.getFillStyle().getPaint()); - checkColor(lineColor, as.getStrokeStyle().getPaint()); - checkColor(textColor, as.getTextParagraphs().get(0).getTextRuns().get(0).getFontColor()); - ppt2.close(); - } - - private static void checkColor(Color expected, PaintStyle actualStyle) { - assertTrue(actualStyle instanceof SolidPaint); - SolidPaint ps = (SolidPaint) actualStyle; - Color actual = DrawPaint.applyColorTransform(ps.getSolidColor()); - float[] expRGB = expected.getRGBComponents(null); - float[] actRGB = actual.getRGBComponents(null); - assertArrayEquals(expRGB, actRGB, 0.0001f); - } - - @Test - void bug55714() throws IOException { - XMLSlideShow srcPptx = openSampleDocument("pptx2svg.pptx"); - XMLSlideShow newPptx = new XMLSlideShow(); - XSLFSlide srcSlide = srcPptx.getSlides().get(0); - XSLFSlide newSlide = newPptx.createSlide(); - - XSLFSlideLayout srcSlideLayout = srcSlide.getSlideLayout(); - XSLFSlideLayout newSlideLayout = newSlide.getSlideLayout(); - newSlideLayout.importContent(srcSlideLayout); - - XSLFSlideMaster srcSlideMaster = srcSlide.getSlideMaster(); - XSLFSlideMaster newSlideMaster = newSlide.getSlideMaster(); - newSlideMaster.importContent(srcSlideMaster); - - newSlide.importContent(srcSlide); - XMLSlideShow rwPptx = XSLFTestDataSamples.writeOutAndReadBack(newPptx); - - PaintStyle ps = rwPptx.getSlides().get(0).getBackground().getFillStyle().getPaint(); - assertTrue(ps instanceof TexturePaint); - - rwPptx.close(); - newPptx.close(); - srcPptx.close(); - } - - @Test - void bug59273() throws IOException { - XMLSlideShow ppt = openSampleDocument("bug59273.potx"); - ppt.getPackage().replaceContentType( - XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType(), - XSLFRelation.MAIN.getContentType() - ); - - XMLSlideShow rwPptx = XSLFTestDataSamples.writeOutAndReadBack(ppt); - OPCPackage pkg = rwPptx.getPackage(); - int size = pkg.getPartsByContentType(XSLFRelation.MAIN.getContentType()).size(); - assertEquals(1, size); - size = pkg.getPartsByContentType(XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType()).size(); - assertEquals(0, size); - - rwPptx.close(); - ppt.close(); - } - - - @Test - void bug60373() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide sl = ppt.createSlide(); - XSLFTable t = sl.createTable(); - XSLFTableRow r = t.addRow(); - bug60373_addCell(r); - bug60373_addCell(r); - r = t.addRow(); - XSLFTableCell c = bug60373_addCell(r); - // call getTextHeight, when table is not fully populated - double th = c.getTextHeight(); - assertTrue(th > 10); - ppt.close(); - } - - private static XSLFTableCell bug60373_addCell(XSLFTableRow r) { - XSLFTableCell cell = r.addCell(); - XSLFTextParagraph p = cell.addNewTextParagraph(); - XSLFTextRun tr = p.addNewTextRun(); - tr.setText("t"); - return cell; - } - - @Test - void bug60715() throws IOException { - try (XMLSlideShow ppt = openSampleDocument("bug60715.pptx")) { - assertDoesNotThrow((ThrowingSupplier<XSLFSlide>) ppt::createSlide); - } - } - - @Test - void bug60662() throws IOException { - XMLSlideShow src = new XMLSlideShow(); - XSLFSlide sl = src.createSlide(); - XSLFGroupShape gs = sl.createGroup(); - gs.setAnchor(new Rectangle2D.Double(100, 100, 100, 100)); - gs.setInteriorAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - XSLFAutoShape as = gs.createAutoShape(); - as.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - as.setShapeType(ShapeType.STAR_24); - as.setFillColor(Color.YELLOW); - CTShape csh = (CTShape) as.getXmlObject(); - CTOuterShadowEffect shadow = csh.getSpPr().addNewEffectLst().addNewOuterShdw(); - shadow.setDir(270000); - shadow.setDist(100000); - shadow.addNewSrgbClr().setVal(new byte[]{0x00, (byte) 0xFF, 0x00}); - - XMLSlideShow dst = new XMLSlideShow(); - XSLFSlide sl2 = dst.createSlide(); - sl2.importContent(sl); - XSLFGroupShape gs2 = (XSLFGroupShape) sl2.getShapes().get(0); - XSLFAutoShape as2 = (XSLFAutoShape) gs2.getShapes().get(0); - CTShape csh2 = (CTShape) as2.getXmlObject(); - assertTrue(csh2.getSpPr().isSetEffectLst()); - - dst.close(); - src.close(); - } - - @Test - void test60810() throws IOException { - XMLSlideShow ppt = openSampleDocument("60810.pptx"); - for (XSLFSlide slide : ppt.getSlides()) { - XSLFNotes notesSlide = ppt.getNotesSlide(slide); - assertNotNull(notesSlide); - } - - ppt.close(); - } - - @Test - void test60042() throws IOException { - try (XMLSlideShow ppt = openSampleDocument("60042.pptx")) { - ppt.removeSlide(0); - ppt.createSlide(); - assertEquals(2, ppt.getSlides().size()); - } - } - - @Test - void test61515() throws IOException { - try (XMLSlideShow ppt = openSampleDocument("61515.pptx")) { - ppt.removeSlide(0); - assertEquals(1, ppt.createSlide().getRelations().size()); - try (XMLSlideShow saved = XSLFTestDataSamples.writeOutAndReadBack(ppt)) { - assertEquals(1, saved.getSlides().size()); - XSLFSlide slide = saved.getSlides().get(0); - assertEquals(1, slide.getRelations().size()); - } - } - } - - @Test - void testAptia() throws IOException { - try (XMLSlideShow ppt = openSampleDocument("aptia.pptx"); - XMLSlideShow saved = XSLFTestDataSamples.writeOutAndReadBack(ppt)) { - assertEquals(ppt.getSlides().size(), saved.getSlides().size()); - } - } - - @Disabled - @Test - void testDivinoRevelado() throws IOException { - try (XMLSlideShow ppt = openSampleDocument("Divino_Revelado.pptx"); - XMLSlideShow saved = XSLFTestDataSamples.writeOutAndReadBack(ppt)) { - assertEquals(ppt.getSlides().size(), saved.getSlides().size()); - } - } - - @Test - void bug62051() throws IOException { - final Function<List<XSLFShape>, int[]> ids = (shapes) -> - shapes.stream().mapToInt(Shape::getShapeId).toArray(); - - try (final XMLSlideShow ppt = new XMLSlideShow()) { - final XSLFSlide slide = ppt.createSlide(); - final List<XSLFShape> shapes = new ArrayList<>(); - shapes.add(slide.createAutoShape()); - final XSLFGroupShape g1 = slide.createGroup(); - shapes.add(g1); - final XSLFGroupShape g2 = g1.createGroup(); - shapes.add(g2); - shapes.add(g2.createAutoShape()); - shapes.add(slide.createAutoShape()); - shapes.add(g2.createAutoShape()); - shapes.add(g1.createAutoShape()); - assertArrayEquals(new int[]{2, 3, 4, 5, 6, 7, 8}, ids.apply(shapes)); - g1.removeShape(g2); - shapes.remove(5); - shapes.remove(3); - shapes.remove(2); - shapes.add(g1.createAutoShape()); - assertArrayEquals(new int[]{2, 3, 6, 8, 4}, ids.apply(shapes)); - - } - } - - @Test - void bug63200() throws Exception { - try (XMLSlideShow ss1 = openSampleDocument("63200.pptx")) { - assertEquals(1, ss1.getSlides().size()); - - XSLFSlide slide = ss1.getSlides().get(0); - - assertEquals(slide.getShapes().size(), 1); - XSLFGroupShape group = (XSLFGroupShape) slide.getShapes().get(0); - assertEquals(group.getShapes().size(), 2); - XSLFAutoShape oval = (XSLFAutoShape) group.getShapes().get(0); - XSLFAutoShape arrow = (XSLFAutoShape) group.getShapes().get(1); - assertNull(oval.getFillColor()); - assertNull(arrow.getFillColor()); - } - } - - @Test - void alternateContent() throws Exception { - try (XMLSlideShow ppt = openSampleDocument("alterman_security.pptx")) { - XSLFSlideMaster slide = ppt.getSlideMasters().get(0); - XSLFObjectShape os = (XSLFObjectShape) slide.getShapes().get(0); - // ctOleObject is nested in AlternateContent in this file - // if there are casting errors, we would fail early and wouldn't reach this point anyway - assertNotNull(os.getCTOleObject()); - // accessing the picture data of the AlternateContent fallback part - XSLFPictureData picData = os.getPictureData(); - assertNotNull(picData); - } - - try (XMLSlideShow ppt = openSampleDocument("2411-Performance_Up.pptx")) { - XSLFSlide slide = ppt.getSlides().get(4); - XSLFPictureShape ps = (XSLFPictureShape) slide.getShapes().get(0); - assertEquals("image4.png", ps.getPictureData().getFileName()); - assertEquals("Picture 5", ps.getShapeName()); - } - } - - - @Test - void bug57796() throws IOException { - assumeFalse(xslfOnly); - - try (SlideShow<?, ?> ppt = SlideShowFactory.create(slTests.getFile("WithLinks.ppt"))) { - Slide<?, ?> slide = ppt.getSlides().get(0); - TextShape<?, ?> shape = (TextShape<?, ?>) slide.getShapes().get(1); - TextRun r = shape.getTextParagraphs().get(1).getTextRuns().get(0); - Hyperlink<?, ?> hlRun = r.getHyperlink(); - assertNotNull(hlRun); - assertEquals("http://jakarta.apache.org/poi/", hlRun.getAddress()); - assertEquals("http://jakarta.apache.org/poi/", hlRun.getLabel()); - assertEquals(HyperlinkType.URL, hlRun.getType()); - - final List<Object> strings = new ArrayList<>(); - - DummyGraphics2d dgfx = new DummyGraphics2d(new NullPrintStream()) { - @Override - public void drawString(AttributedCharacterIterator iterator, float x, float y) { - // For the test file, common sl draws textruns one by one and not mixed - // so we evaluate the whole iterator - Map<Attribute, Object> attributes = null; - StringBuilder sb = new StringBuilder(); - - for (char c = iterator.first(); - c != CharacterIterator.DONE; - c = iterator.next()) { - sb.append(c); - attributes = iterator.getAttributes(); - } - - if ("Jakarta HSSF".equals(sb.toString())) { - // this is a test for a manually modified ppt, for real hyperlink label - // one would need to access the screen tip record - Attribute[] obj = {HYPERLINK_HREF, HYPERLINK_LABEL}; - assertNotNull(attributes); - Stream.of(obj).map(attributes::get).forEach(strings::add); - } - } - }; - - ppt.getSlides().get(1).draw(dgfx); - assertEquals(2, strings.size()); - assertEquals("http://jakarta.apache.org/poi/hssf/", strings.get(0)); - assertEquals("Open Jakarta POI HSSF module test ", strings.get(1)); - } - } - - - @Test - void bug59056() throws IOException { - assumeFalse(xslfOnly); - - final double[][] clips = { - { 50.999999999999986, 51.0, 298.0, 98.0 }, - { 51.00000000000003, 51.0, 298.0, 98.0 }, - { 51.0, 51.0, 298.0, 98.0 }, - { 250.02000796164992, 93.10370370370373, 78.61839367617523, 55.89629629629627 }, - { 79.58198774450841, 53.20887318960063, 109.13118501448272, 9.40935058567127 }, - }; - - DummyGraphics2d dgfx = new DummyGraphics2d(new NullPrintStream()) { - int idx = 0; - @Override - public void clip(java.awt.Shape s) { - assertTrue(s instanceof Rectangle2D); - Rectangle2D r = (Rectangle2D)s; - - double[] clip = clips[idx++]; - assertEquals(clip[0], r.getX(), 0.5); - assertEquals(clip[1], r.getY(), 0.5); - assertEquals(clip[2], r.getWidth(), 0.5); - assertEquals(clip[3], r.getHeight(), 0.5); - } - }; - - Rectangle2D box = new Rectangle2D.Double(51, 51, 298, 98); - DrawFactory df = DrawFactory.getInstance(dgfx); - - try (SlideShow<?,?> ppt = SlideShowFactory.create(slTests.getFile("54541_cropped_bitmap.ppt"))) { - ppt.getSlides().get(0).getShapes().forEach(shape -> df.drawShape(dgfx, shape, box)); - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java deleted file mode 100644 index 1d948dc6ee..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java +++ /dev/null @@ -1,159 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; -import java.io.IOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ooxml.POIXMLProperties.CoreProperties; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFAutoShape; -import org.apache.poi.xslf.usermodel.XSLFBackground; -import org.apache.poi.xslf.usermodel.XSLFRelation; -import org.apache.poi.xslf.usermodel.XSLFSlide; -import org.apache.poi.xslf.usermodel.XSLFSlideShow; -import org.apache.xmlbeans.XmlException; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdListEntry; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMasterIdListEntry; - -import static org.junit.jupiter.api.Assertions.*; - -class TestXSLFSlideShow { - private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - private OPCPackage pack; - - @BeforeEach - void setUp() throws Exception { - pack = OPCPackage.open(slTests.openResourceAsStream("sample.pptx")); - } - - @AfterEach - void tearDown() throws IOException { - pack.close(); - } - - @Test - void testContainsMainContentType() throws Exception { - boolean found = false; - for(PackagePart part : pack.getParts()) { - if(part.getContentType().equals(XSLFRelation.MAIN.getContentType())) { - found = true; - } - } - assertTrue(found); - } - - @Test - void testOpen() throws IOException, OpenXML4JException, XmlException { - // With the finalized uri, should be fine - XSLFSlideShow xml = new XSLFSlideShow(pack); - // Check the core - assertNotNull(xml.getPresentation()); - - // Check it has some slides - assertNotEquals(0, xml.getSlideReferences().sizeOfSldIdArray()); - assertNotEquals(0, xml.getSlideMasterReferences().sizeOfSldMasterIdArray()); - - xml.close(); - } - - @Test - void testSlideBasics() throws IOException, OpenXML4JException, XmlException { - XSLFSlideShow xml = new XSLFSlideShow(pack); - - // Should have 1 master - assertEquals(1, xml.getSlideMasterReferences().sizeOfSldMasterIdArray()); - - // Should have three sheets - assertEquals(2, xml.getSlideReferences().sizeOfSldIdArray()); - - // Check they're as expected - CTSlideIdListEntry[] slides = xml.getSlideReferences().getSldIdArray(); - - assertEquals(256, slides[0].getId()); - assertEquals(257, slides[1].getId()); - assertEquals("rId2", slides[0].getId2()); - assertEquals("rId3", slides[1].getId2()); - - // Now get those objects - assertNotNull(xml.getSlide(slides[0])); - assertNotNull(xml.getSlide(slides[1])); - - // And check they have notes as expected - assertNotNull(xml.getNotes(slides[0])); - assertNotNull(xml.getNotes(slides[1])); - - // And again for the master - CTSlideMasterIdListEntry[] masters = xml.getSlideMasterReferences().getSldMasterIdArray(); - - // see SlideAtom.USES_MASTER_SLIDE_ID - assertEquals(0x80000000L, masters[0].getId()); - assertEquals("rId1", masters[0].getId2()); - assertNotNull(xml.getSlideMaster(masters[0])); - - xml.close(); - } - - @Test - void testMetadataBasics() throws IOException, OpenXML4JException, XmlException { - XSLFSlideShow xml = new XSLFSlideShow(pack); - - assertNotNull(xml.getProperties().getCoreProperties()); - assertNotNull(xml.getProperties().getExtendedProperties()); - - CTProperties props = xml.getProperties().getExtendedProperties().getUnderlyingProperties(); - assertEquals("Microsoft Office PowerPoint", props.getApplication()); - assertEquals(0, props.getCharacters()); - assertEquals(0, props.getLines()); - - CoreProperties cprops = xml.getProperties().getCoreProperties(); - assertNull(cprops.getTitle()); - assertFalse(cprops.getUnderlyingProperties().getSubjectProperty().isPresent()); - - xml.close(); - } - - @Test - void testMasterBackground() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFBackground b = ppt.getSlideMasters().get(0).getBackground(); - b.setFillColor(Color.RED); - - XSLFSlide sl = ppt.createSlide(); - XSLFAutoShape as = sl.createAutoShape(); - as.setAnchor(new Rectangle2D.Double(100,100,100,100)); - as.setShapeType(ShapeType.CLOUD); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt); - ppt.close(); - - XSLFBackground b2 = ppt2.getSlideMasters().get(0).getBackground(); - assertEquals(Color.RED, b2.getFillColor()); - - ppt2.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/XSLFTestDataSamples.java b/src/ooxml/testcases/org/apache/poi/xslf/XSLFTestDataSamples.java deleted file mode 100644 index 72ed16f94b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/XSLFTestDataSamples.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xslf.usermodel.XMLSlideShow; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * @author Yegor Kozlov - */ -public class XSLFTestDataSamples { - - public static XMLSlideShow openSampleDocument(String sampleName) { - InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream(sampleName); - try { - return new XMLSlideShow(OPCPackage.open(is)); - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - try { - is.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - public static XMLSlideShow writeOutAndReadBack(XMLSlideShow doc) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - try { - doc.write(baos); - } catch (IOException e) { - throw new RuntimeException(e); - } - - InputStream bais; - bais = new ByteArrayInputStream(baos.toByteArray()); - try { - return new XMLSlideShow(OPCPackage.open(bais)); - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - try { - baos.close(); - bais.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java b/src/ooxml/testcases/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java deleted file mode 100644 index 5e5f0ed4cb..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java +++ /dev/null @@ -1,328 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.POITestCase.assertNotContained; -import static org.apache.poi.POITestCase.assertStartsWith; -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.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.sl.extractor.SlideShowExtractor; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFShape; -import org.apache.poi.xslf.usermodel.XSLFTextParagraph; -import org.junit.jupiter.api.Test; - -/** - * Tests for XSLFPowerPointExtractor - */ -class TestXSLFPowerPointExtractor { - private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - - /** - * Get text out of the simple file - */ - @Test - void testGetSimpleText() throws IOException { - try (XMLSlideShow xmlA = openPPTX("sample.pptx"); - SlideShowExtractor<XSLFShape, XSLFTextParagraph> extractor = new SlideShowExtractor<>(xmlA)) { - - extractor.getText(); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check Basics - assertStartsWith(text, "Lorem ipsum dolor sit amet\n"); - assertContains(text, "amet\n"); - - // Our placeholder master text - // This shouldn't show up in the output - // String masterText = - // "Click to edit Master title style\n" + - // "Click to edit Master subtitle style\n" + - // "\n\n\n\n\n\n" + - // "Click to edit Master title style\n" + - // "Click to edit Master text styles\n" + - // "Second level\n" + - // "Third level\n" + - // "Fourth level\n" + - // "Fifth level\n"; - - // Just slides, no notes - extractor.setSlidesByDefault(true); - extractor.setNotesByDefault(false); - extractor.setMasterByDefault(false); - text = extractor.getText(); - String slideText = - "Lorem ipsum dolor sit amet\n" + - "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + - "\n" + - "Lorem ipsum dolor sit amet\n" + - "Lorem\n" + - "ipsum\n" + - "dolor\n" + - "sit\n" + - "amet\n" + - "\n"; - assertEquals(slideText, text); - - // Just notes, no slides - extractor.setSlidesByDefault(false); - extractor.setNotesByDefault(true); - text = extractor.getText(); - assertEquals("\n1\n\n2\n", text); - - // Both - extractor.setSlidesByDefault(true); - extractor.setNotesByDefault(true); - text = extractor.getText(); - String bothText = - "Lorem ipsum dolor sit amet\n" + - "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + - "\n\n1\n" + - "Lorem ipsum dolor sit amet\n" + - "Lorem\n" + - "ipsum\n" + - "dolor\n" + - "sit\n" + - "amet\n" + - "\n\n2\n"; - assertEquals(bothText, text); - - // With Slides and Master Text - extractor.setSlidesByDefault(true); - extractor.setNotesByDefault(false); - extractor.setMasterByDefault(true); - text = extractor.getText(); - String smText = - "Lorem ipsum dolor sit amet\n" + - "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + - "\n" + - "Lorem ipsum dolor sit amet\n" + - "Lorem\n" + - "ipsum\n" + - "dolor\n" + - "sit\n" + - "amet\n" + - "\n"; - assertEquals(smText, text); - - // With Slides, Notes and Master Text - extractor.setSlidesByDefault(true); - extractor.setNotesByDefault(true); - extractor.setMasterByDefault(true); - text = extractor.getText(); - String snmText = - "Lorem ipsum dolor sit amet\n" + - "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + - "\n\n1\n" + - "Lorem ipsum dolor sit amet\n" + - "Lorem\n" + - "ipsum\n" + - "dolor\n" + - "sit\n" + - "amet\n" + - "\n\n2\n"; - assertEquals(snmText, text); - - // Via set defaults - extractor.setSlidesByDefault(false); - extractor.setNotesByDefault(true); - text = extractor.getText(); - assertEquals("\n1\n\n2\n", text); - } - } - - @Test - void testGetComments() throws IOException { - try (XMLSlideShow xml = openPPTX("45545_Comment.pptx"); - SlideShowExtractor<XSLFShape, XSLFTextParagraph> extractor = new SlideShowExtractor<>(xml)) { - extractor.setCommentsByDefault(true); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check comments are there - assertContains(text, "testdoc"); - assertContains(text, "test phrase"); - - // Check the authors came through too - assertContains(text, "XPVMWARE01"); - } - } - - @Test - void testGetMasterText() throws Exception { - try (XMLSlideShow xml = openPPTX("WithMaster.pptx"); - SlideShowExtractor<XSLFShape, XSLFTextParagraph> extractor = new SlideShowExtractor<>(xml)) { - extractor.setSlidesByDefault(true); - extractor.setNotesByDefault(false); - extractor.setMasterByDefault(true); - - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check master text is there - assertContains(text, "Footer from the master slide"); - - // Theme text shouldn't show up - // String themeText = - // "Theme Master Title\n" + - // "Theme Master first level\n" + - // "And the 2nd level\n" + - // "Our 3rd level goes here\n" + - // "And onto the 4th, such fun....\n" + - // "Finally is the Fifth level\n"; - - // Check the whole text - String wholeText = - "First page title\n" + - "First page subtitle\n" + - "This text comes from the Master Slide\n" + - "\n" + - "2nd page subtitle\n" + - "Footer from the master slide\n" + - "This text comes from the Master Slide\n"; - assertEquals(wholeText, text); - } - } - - @Test - void testTable() throws Exception { - try (XMLSlideShow xml = openPPTX("present1.pptx"); - SlideShowExtractor<XSLFShape, XSLFTextParagraph> extractor = new SlideShowExtractor<>(xml)) { - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check comments are there - assertContains(text, "TEST"); - } - } - - /** - * Test that we can get the text from macro enabled, - * template, theme, slide enabled etc formats, as - * well as from the normal file - */ - @Test - void testDifferentSubformats() throws Exception { - String[] extensions = new String[] { - "pptx", "pptm", "ppsm", "ppsx", "thmx", - // "xps" - Doesn't have a core document - }; - for(String extension : extensions) { - String filename = "testPPT." + extension; - - try (XMLSlideShow xml = openPPTX(filename); - SlideShowExtractor<XSLFShape, XSLFTextParagraph> extractor = new SlideShowExtractor<>(xml)) { - - String text = extractor.getText(); - if (extension.equals("thmx")) { - // Theme file doesn't have any textual content - assertEquals(0, text.length(), filename); - continue; - } - - assertTrue(text.length() > 0, filename); - assertContains(filename, text, "Attachment Test"); - assertContains(filename, text, "This is a test file data with the same content"); - assertContains(filename, text, "content parsing"); - assertContains(filename, text, "Different words to test against"); - assertContains(filename, text, "Mystery"); - } - } - } - - @Test - void test45541() throws IOException { - // extract text from a powerpoint that has a header in the notes-element - final File headerFile = slTests.getFile("45541_Header.pptx"); - //noinspection rawtypes - try (final SlideShowExtractor extr = (SlideShowExtractor) ExtractorFactory.createExtractor(headerFile)) { - String text = extr.getText(); - assertNotNull(text); - assertFalse(text.contains("testdoc"), "Had: " + text); - - extr.setSlidesByDefault(false); - extr.setNotesByDefault(true); - - text = extr.getText(); - assertContains(text, "testdoc"); - assertNotNull(text); - } - - // extract text from a powerpoint that has a footer in the master-slide - final File footerFile = slTests.getFile("45541_Footer.pptx"); - //noinspection rawtypes - try (SlideShowExtractor extr = (SlideShowExtractor)ExtractorFactory.createExtractor(footerFile)) { - String text = extr.getText(); - assertNotContained(text, "testdoc"); - - extr.setSlidesByDefault(false); - extr.setNotesByDefault(true); - text = extr.getText(); - assertNotContained(text, "testdoc"); - - extr.setSlidesByDefault(false); - extr.setNotesByDefault(false); - extr.setMasterByDefault(true); - text = extr.getText(); - assertNotContained(text, "testdoc"); - } - } - - - @Test - void bug54570() throws IOException { - try (XMLSlideShow xml = openPPTX("bug54570.pptx"); - SlideShowExtractor<XSLFShape, XSLFTextParagraph> extractor = new SlideShowExtractor<>(xml)) { - String text = extractor.getText(); - assertNotNull(text); - } - } - - private XMLSlideShow openPPTX(String file) throws IOException { - try (InputStream is = slTests.openResourceAsStream(file)) { - return new XMLSlideShow(is); - } - } - - @Test - void setSlTests() throws IOException { - try (XMLSlideShow xml = openPPTX("aascu.org_hbcu_leadershipsummit_cooper_.pptx")) { - SlideShowExtractor<XSLFShape, XSLFTextParagraph> extractor = new SlideShowExtractor<>(xml); - assertNotNull(extractor); - extractor.setSlidesByDefault(true); - extractor.setNotesByDefault(true); - extractor.setMasterByDefault(true); - - assertNotNull(extractor.getText()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestPPTX2PNG.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestPPTX2PNG.java deleted file mode 100644 index 4226b28095..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestPPTX2PNG.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import static java.util.Arrays.asList; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Function; -import java.util.stream.Stream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.xslf.util.PPTX2PNG; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Test class for testing PPTX2PNG utility which renders .ppt and .pptx slideshows - */ -@SuppressWarnings("ConstantConditions") -class TestPPTX2PNG { - private static boolean xslfOnly; - private static final POIDataSamples samples = POIDataSamples.getSlideShowInstance(); - private static final File basedir = null; - - private static final String files = - "bug64693.pptx, 53446.ppt, alterman_security.ppt, alterman_security.pptx, KEY02.pptx, themes.pptx, " + - "backgrounds.pptx, layouts.pptx, sample.pptx, shapes.pptx, 54880_chinese.ppt, keyframes.pptx," + - "customGeo.pptx, customGeo.ppt, wrench.emf, santa.wmf, missing-moveto.ppt, " + - "64716_image1.wmf, 64716_image2.wmf, 64716_image3.wmf, 54542_cropped_bitmap.pptx"; - - private static final String svgFiles = - "bug64693.pptx"; - - private static final String pdfFiles = - "alterman_security.ppt"; - - @BeforeAll - public static void checkHslf() { - try { - Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); - } catch (Exception e) { - xslfOnly = true; - } - } - - public static Stream<Arguments> data() { - Function<String, Stream<Arguments>> fun = (basedir == null) - ? (f) -> Stream.of(Arguments.of(f)) - : (f) -> Stream.of(basedir.listFiles(p -> p.getName().matches(f))).map(File::getName).map(Arguments::of); - - return Stream.of(files.split(", ?")).flatMap(fun); - } - - // use filename instead of File object to omit full pathname in test name - @ParameterizedTest - @MethodSource("data") - void render(String pptFile) throws Exception { - assumeFalse(xslfOnly && pptFile.matches(".*\\.(ppt|emf|wmf)$"), "ignore HSLF (.ppt) / HEMF (.emf) / HWMF (.wmf) files in no-scratchpad run"); - PPTX2PNG.main(getArgs(pptFile, "null")); - if (svgFiles.contains(pptFile)) { - PPTX2PNG.main(getArgs(pptFile, "svg")); - } - if (pdfFiles.contains(pptFile)) { - PPTX2PNG.main(getArgs(pptFile, "pdf")); - } - } - - private String[] getArgs(String pptFile, String format) throws IOException { - File tmpDir = new File("build/tmp/"); - - // fix maven build errors - if (!tmpDir.exists()) { - assertTrue(tmpDir.mkdirs()); - } - - final List<String> args = new ArrayList<>(asList( - "-format", format, // png,gif,jpg,svg,pdf or null for test - "-slide", "-1", // -1 for all - "-outdir", tmpDir.getCanonicalPath(), - "-outpat", "${basename}-${slideno}-${ext}.${format}", - // "-dump", new File("build/tmp/", pptFile+".json").getCanonicalPath(), - "-dump", "null", - "-quiet", - // "-charset", "GBK", - // "-emfHeaderBounds", - // "-textAsShapes", - "-fixside", "long", - "-scale", "800" - )); - - if ("bug64693.pptx".equals(pptFile)) { - args.addAll(asList( - "-charset", "GBK" - )); - } - - args.add((basedir == null ? samples.getFile(pptFile) : new File(basedir, pptFile)).getAbsolutePath()); - - return args.toArray(new String[0]); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java deleted file mode 100644 index 520f62fb04..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java +++ /dev/null @@ -1,201 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.usermodel.BaseTestSlideShow; -import org.apache.poi.sl.usermodel.SlideShow; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.presentationml.x2006.main.CTNotesMasterIdListEntry; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdListEntry; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMasterIdListEntry; - -class TestXMLSlideShow extends BaseTestSlideShow<XSLFShape, XSLFTextParagraph> { - private OPCPackage pack; - - @Override - public XMLSlideShow createSlideShow() { - return new XMLSlideShow(); - } - - @BeforeEach - void setUp() throws Exception { - pack = OPCPackage.open(slTests.openResourceAsStream("sample.pptx")); - } - - @AfterEach - void tearDown() { - pack.revert(); - } - - @Test - void testContainsMainContentType() throws Exception { - boolean found = false; - for (PackagePart part : pack.getParts()) { - if (part.getContentType().equals(XSLFRelation.MAIN.getContentType())) { - found = true; - } - } - assertTrue(found); - } - - @Test - void testOpen() throws Exception { - // With the finalised uri, should be fine - XMLSlideShow xml = new XMLSlideShow(pack); - // Check the core - assertNotNull(xml.getCTPresentation()); - - // Check it has some slides - assertFalse(xml.getSlides().isEmpty()); - assertFalse(xml.getSlideMasters().isEmpty()); - - xml.close(); - } - - @SuppressWarnings("deprecation") - @Test - void testSlideBasics() throws IOException { - XMLSlideShow xml = new XMLSlideShow(pack); - - // Should have 1 master - assertEquals(1, xml.getSlideMasters().size()); - - // Should have two sheets - assertEquals(2, xml.getSlides().size()); - - // Check they're as expected - CTSlideIdListEntry[] slides = xml.getCTPresentation().getSldIdLst().getSldIdArray(); - - assertEquals(256, slides[0].getId()); - assertEquals(257, slides[1].getId()); - assertEquals("rId2", slides[0].getId2()); - assertEquals("rId3", slides[1].getId2()); - - // Now get those objects - assertNotNull(xml.getSlides().get(0)); - assertNotNull(xml.getSlides().get(1)); - - // And check they have notes as expected - assertNotNull(xml.getSlides().get(0).getNotes()); - assertNotNull(xml.getSlides().get(1).getNotes()); - - // Next up look for the slide master - CTSlideMasterIdListEntry[] masters = xml.getCTPresentation().getSldMasterIdLst().getSldMasterIdArray(); - - // see SlideAtom.USES_MASTER_SLIDE_ID - assertEquals(0x80000000L, masters[0].getId()); - assertEquals("rId1", masters[0].getId2()); - assertNotNull(xml.getSlideMasters().get(0)); - - // Finally look for the notes master - CTNotesMasterIdListEntry notesMaster = - xml.getCTPresentation().getNotesMasterIdLst().getNotesMasterId(); - assertNotNull(notesMaster); - - assertNotNull(xml.getNotesMaster()); - - xml.close(); - } - - @Test - void testMetadataBasics() throws IOException { - XMLSlideShow xml = new XMLSlideShow(pack); - - assertNotNull(xml.getProperties().getCoreProperties()); - assertNotNull(xml.getProperties().getExtendedProperties()); - - assertEquals("Microsoft Office PowerPoint", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); - assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters()); - assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); - - assertNull(xml.getProperties().getCoreProperties().getTitle()); - assertFalse(xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().isPresent()); - - xml.close(); - } - - @Test - void testComments() throws Exception { - // Default sample file has none - XMLSlideShow xml = new XMLSlideShow(pack); - - assertNull(xml.getCommentAuthors()); - - for (XSLFSlide slide : xml.getSlides()) { - assertTrue(slide.getComments().isEmpty()); - } - - // Try another with comments - XMLSlideShow xmlComments = new XMLSlideShow(slTests.openResourceAsStream("45545_Comment.pptx")); - - // Has one author - assertNotNull(xmlComments.getCommentAuthors()); - assertEquals(1, xmlComments.getCommentAuthors().getCTCommentAuthorsList().sizeOfCmAuthorArray()); - assertEquals("XPVMWARE01", xmlComments.getCommentAuthors().getAuthorById(0).getName()); - - // First two slides have comments - int i = -1; - for (XSLFSlide slide : xmlComments.getSlides()) { - i++; - - if (i == 0) { - assertNotNull(slide.getCommentsPart()); - assertEquals(1, slide.getCommentsPart().getNumberOfComments()); - assertEquals("testdoc", slide.getCommentsPart().getCommentAt(0).getText()); - assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId()); - } else if (i == 1) { - assertNotNull(slide.getComments()); - assertEquals(1, slide.getCommentsPart().getNumberOfComments()); - assertEquals("test phrase", slide.getCommentsPart().getCommentAt(0).getText()); - assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId()); - } else { - assertNull(slide.getCommentsPart()); - assertTrue(slide.getComments().isEmpty()); - } - } - - xmlComments.close(); - xml.close(); - } - - @Override - public XMLSlideShow reopen(SlideShow<XSLFShape, XSLFTextParagraph> show) throws IOException { - BufAccessBAOS bos = new BufAccessBAOS(); - show.write(bos); - return new XMLSlideShow(new ByteArrayInputStream(bos.getBuf())); - } - - private static class BufAccessBAOS extends ByteArrayOutputStream { - byte[] getBuf() { - return buf; - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFAutoShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFAutoShape.java deleted file mode 100644 index 330f6629e7..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFAutoShape.java +++ /dev/null @@ -1,313 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.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.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.TextParagraph.TextAlign; -import org.apache.poi.sl.usermodel.TextShape.TextAutofit; -import org.apache.poi.sl.usermodel.TextShape.TextDirection; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.util.Units; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextStrikeType; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType; - -class TestXSLFAutoShape { - @Test - void testTextBodyProperies() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFAutoShape shape = slide.createAutoShape(); - shape.addNewTextParagraph().addNewTextRun().setText("POI"); - - // default margins from slide master - assertEquals(3.6, shape.getBottomInset(), 0); - assertEquals(3.6, shape.getTopInset(), 0); - assertEquals(7.2, shape.getLeftInset(), 0); - assertEquals(7.2, shape.getRightInset(), 0); - - shape.setBottomInset(1.0); - assertEquals(1.0, shape.getBottomInset(), 0); - shape.setTopInset(2.0); - assertEquals(2.0, shape.getTopInset(), 0); - shape.setLeftInset(3.0); - assertEquals(3.0, shape.getLeftInset(), 0); - shape.setRightInset(4.0); - assertEquals(4.0, shape.getRightInset(), 0); - - shape.setBottomInset(0.0); - assertEquals(0.0, shape.getBottomInset(), 0); - shape.setTopInset(0.0); - assertEquals(0.0, shape.getTopInset(), 0); - shape.setLeftInset(0.0); - assertEquals(0.0, shape.getLeftInset(), 0); - shape.setRightInset(0.0); - assertEquals(0.0, shape.getRightInset(), 0); - - // unset to defauls - shape.setBottomInset(-1); - assertEquals(3.6, shape.getBottomInset(), 0); - shape.setTopInset(-1); - assertEquals(3.6, shape.getTopInset(), 0); - shape.setLeftInset(-1); - assertEquals(7.2, shape.getLeftInset(), 0); - shape.setRightInset(-1); - assertEquals(7.2, shape.getRightInset(), 0); - - // shape - assertTrue(shape.getWordWrap()); - shape.setWordWrap(false); - assertFalse(shape.getWordWrap()); - shape.setWordWrap(true); - assertTrue(shape.getWordWrap()); - - // shape - assertEquals(TextAutofit.NORMAL, shape.getTextAutofit()); - shape.setTextAutofit(TextAutofit.NONE); - assertEquals(TextAutofit.NONE, shape.getTextAutofit()); - shape.setTextAutofit(TextAutofit.SHAPE); - assertEquals(TextAutofit.SHAPE, shape.getTextAutofit()); - shape.setTextAutofit(TextAutofit.NORMAL); - assertEquals(TextAutofit.NORMAL, shape.getTextAutofit()); - - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - shape.setVerticalAlignment(VerticalAlignment.BOTTOM); - assertEquals(VerticalAlignment.BOTTOM, shape.getVerticalAlignment()); - shape.setVerticalAlignment(VerticalAlignment.MIDDLE); - assertEquals(VerticalAlignment.MIDDLE, shape.getVerticalAlignment()); - shape.setVerticalAlignment(null); - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - shape.setTextDirection(TextDirection.VERTICAL); - assertEquals(TextDirection.VERTICAL, shape.getTextDirection()); - shape.setTextDirection(null); - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - - ppt.close(); - } - - @Test - void testTextParagraph() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - assertTrue(slide.getShapes().isEmpty()); - - XSLFAutoShape shape = slide.createAutoShape(); - assertEquals(0, shape.getTextParagraphs().size()); - XSLFTextParagraph p = shape.addNewTextParagraph(); - assertEquals(1, shape.getTextParagraphs().size()); - - assertNull(p.getIndent()); - assertEquals(0, p.getLeftMargin(), 0); - assertNull(p.getLineSpacing()); - assertNull(p.getSpaceAfter()); - assertNull(p.getSpaceBefore()); - assertEquals(0, p.getIndentLevel()); - - p.setIndent(2.0); - assertEquals(2.0, p.getIndent(), 0); - assertTrue(p.getXmlObject().getPPr().isSetIndent()); - p.setIndent(null); - assertNull(p.getIndent()); - assertFalse(p.getXmlObject().getPPr().isSetIndent()); - p.setIndent(10.0); - assertEquals(10., p.getIndent(), 0); - assertTrue(p.getXmlObject().getPPr().isSetIndent()); - - - assertFalse(p.getXmlObject().getPPr().isSetLvl()); - p.setIndentLevel(1); - assertEquals(1, p.getIndentLevel()); - assertTrue(p.getXmlObject().getPPr().isSetLvl()); - p.setIndentLevel(2); - assertEquals(2, p.getIndentLevel()); - - p.setLeftMargin(2.0); - assertEquals(2.0, p.getLeftMargin(), 0); - assertTrue(p.getXmlObject().getPPr().isSetMarL()); - p.setLeftMargin(10.0); - assertEquals(10., p.getLeftMargin(), 0); - assertEquals(Units.toEMU(10), p.getXmlObject().getPPr().getMarL()); - - - assertFalse(p.getXmlObject().getPPr().isSetSpcAft()); - p.setSpaceAfter(200d); - assertEquals(200000, p.getXmlObject().getPPr().getSpcAft().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcAft().isSetSpcPts()); - p.setSpaceAfter(100d); - assertEquals(100000, p.getXmlObject().getPPr().getSpcAft().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcAft().isSetSpcPts()); - p.setSpaceAfter(-20d); - assertEquals(2000, p.getXmlObject().getPPr().getSpcAft().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcAft().isSetSpcPct()); - p.setSpaceAfter(-10d); - assertEquals(1000, p.getXmlObject().getPPr().getSpcAft().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcAft().isSetSpcPct()); - - assertFalse(p.getXmlObject().getPPr().isSetSpcBef()); - p.setSpaceBefore(200d); - assertEquals(200000, p.getXmlObject().getPPr().getSpcBef().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcBef().isSetSpcPts()); - p.setSpaceBefore(100d); - assertEquals(100000, p.getXmlObject().getPPr().getSpcBef().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcBef().isSetSpcPts()); - p.setSpaceBefore(-20d); - assertEquals(2000, p.getXmlObject().getPPr().getSpcBef().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcBef().isSetSpcPct()); - p.setSpaceBefore(-10d); - assertEquals(1000, p.getXmlObject().getPPr().getSpcBef().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcBef().isSetSpcPct()); - - assertFalse(p.getXmlObject().getPPr().isSetLnSpc()); - p.setLineSpacing(200d); - assertEquals(200000, p.getXmlObject().getPPr().getLnSpc().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getLnSpc().isSetSpcPts()); - p.setLineSpacing(100d); - assertEquals(100000, p.getXmlObject().getPPr().getLnSpc().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getLnSpc().isSetSpcPts()); - p.setLineSpacing(-20d); - assertEquals(2000, p.getXmlObject().getPPr().getLnSpc().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getLnSpc().isSetSpcPct()); - p.setLineSpacing(-10d); - assertEquals(1000, p.getXmlObject().getPPr().getLnSpc().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getLnSpc().isSetSpcPct()); - - // align is set in autoshape prototype - assertTrue(p.getXmlObject().getPPr().isSetAlgn()); - assertEquals(TextAlign.LEFT, p.getTextAlign()); - p.setTextAlign(TextAlign.LEFT); - assertTrue(p.getXmlObject().getPPr().isSetAlgn()); - assertEquals(TextAlign.LEFT, p.getTextAlign()); - p.setTextAlign(TextAlign.RIGHT); - assertEquals(TextAlign.RIGHT, p.getTextAlign()); - p.setTextAlign(TextAlign.JUSTIFY); - assertEquals(TextAlign.JUSTIFY, p.getTextAlign()); - p.setTextAlign(null); - assertEquals(TextAlign.LEFT, p.getTextAlign()); - assertFalse(p.getXmlObject().getPPr().isSetAlgn()); - - ppt.close(); - } - - @Test - void testTextRun() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFAutoShape shape = slide.createAutoShape(); - assertEquals(0, shape.getTextParagraphs().size()); - XSLFTextParagraph p = shape.addNewTextParagraph(); - assertEquals(1, shape.getTextParagraphs().size()); - assertEquals(0, p.getTextRuns().size()); - XSLFTextRun r = p.addNewTextRun(); - CTTextCharacterProperties rPr = r.getRPr(false); - assertNotNull(rPr); - assertEquals(1, p.getTextRuns().size()); - assertSame(r, p.getTextRuns().get(0)); - - - assertEquals(18.0, r.getFontSize(), 0); // default font size for text boxes - assertFalse(rPr.isSetSz()); - r.setFontSize(10.0); - assertEquals(1000, rPr.getSz()); - r.setFontSize(12.5); - assertEquals(1250, rPr.getSz()); - r.setFontSize(null); - assertFalse(rPr.isSetSz()); - - assertFalse(rPr.isSetLatin()); - assertEquals("Calibri", r.getFontFamily()); // comes from the slide master - r.setFontFamily(null); - assertEquals("Calibri", r.getFontFamily()); // comes from the slide master - r.setFontFamily("Arial"); - assertEquals("Arial", r.getFontFamily()); - assertEquals("Arial", rPr.getLatin().getTypeface()); - r.setFontFamily("Symbol"); - assertEquals("Symbol", r.getFontFamily()); - assertEquals("Symbol", rPr.getLatin().getTypeface()); - r.setFontFamily(null); - assertEquals("Calibri", r.getFontFamily()); // comes from the slide master - assertFalse(rPr.isSetLatin()); - - assertFalse(r.isStrikethrough()); - assertFalse(rPr.isSetStrike()); - r.setStrikethrough(true); - assertTrue(r.isStrikethrough()); - assertEquals(STTextStrikeType.SNG_STRIKE, rPr.getStrike()); - - assertFalse(r.isBold()); - assertFalse(rPr.isSetB()); - r.setBold(true); - assertTrue(r.isBold()); - assertTrue(rPr.getB()); - - assertFalse(r.isItalic()); - assertFalse(rPr.isSetI()); - r.setItalic(true); - assertTrue(r.isItalic()); - assertTrue(rPr.getI()); - - assertFalse(r.isUnderlined()); - assertFalse(rPr.isSetU()); - r.setUnderlined(true); - assertTrue(r.isUnderlined()); - assertEquals(STTextUnderlineType.SNG, rPr.getU()); - - r.setText("Apache"); - assertEquals("Apache", r.getRawText()); - r.setText("POI"); - assertEquals("POI", r.getRawText()); - r.setText(null); - assertNull(r.getRawText()); - - ppt.close(); - } - - @Test - void testShapeType() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFAutoShape shape = slide.createAutoShape(); - assertEquals(ShapeType.RECT, shape.getShapeType()); - - shape.setShapeType(ShapeType.TRIANGLE); - assertEquals(ShapeType.TRIANGLE, shape.getShapeType()); - - for(ShapeType tp : ShapeType.values()) { - if (tp.ooxmlId == -1 || tp == ShapeType.SEAL) { - continue; - } - shape.setShapeType(tp); - assertEquals(tp, shape.getShapeType()); - } - - ppt.close(); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFBackground.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFBackground.java deleted file mode 100644 index 907a37a80d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFBackground.java +++ /dev/null @@ -1,158 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.presentationml.x2006.main.CTBackgroundProperties; -import org.openxmlformats.schemas.presentationml.x2006.main.impl.CTBackgroundImpl; - -import java.awt.*; -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.*; - -class TestXSLFBackground { - @Test - void testNoFillBackground() throws IOException { - XMLSlideShow pptx = new XMLSlideShow(); - XSLFSlide slide = pptx.createSlide(); - - slide.getBackground().setFillColor(null); - - CTBackgroundImpl bg = (CTBackgroundImpl) slide.getBackground().getXmlObject(); - CTBackgroundProperties bgPr = bg.getBgPr(); - - assertFalse(bgPr.isSetBlipFill()); - assertFalse(bgPr.isSetGradFill()); - assertFalse(bgPr.isSetGrpFill()); - assertFalse(bgPr.isSetPattFill()); - assertFalse(bgPr.isSetSolidFill()); - assertTrue(bgPr.isSetNoFill()); - - pptx.close(); - } - - @Test - void testSolidFillBackground() throws IOException { - XMLSlideShow pptx = new XMLSlideShow(); - XSLFSlide slide = pptx.createSlide(); - - Color color = Color.RED; - - slide.getBackground().setFillColor(color); - - CTBackgroundImpl bg = (CTBackgroundImpl) slide.getBackground().getXmlObject(); - CTBackgroundProperties bgPr = bg.getBgPr(); - - assertFalse(bgPr.isSetBlipFill()); - assertFalse(bgPr.isSetGradFill()); - assertFalse(bgPr.isSetGrpFill()); - assertFalse(bgPr.isSetPattFill()); - assertTrue(bgPr.isSetSolidFill()); - assertFalse(bgPr.isSetNoFill()); - - assertEquals(slide.getBackground().getFillColor(), color); - - pptx.close(); - } - - @Test - void testBlipFillBackground() throws IOException { - XMLSlideShow pptx = XSLFTestDataSamples.openSampleDocument("pptx2svg.pptx"); - XSLFSlide slide = pptx.getSlides().get(0); - - Color color = Color.WHITE; - - CTBackgroundImpl bg = (CTBackgroundImpl) slide.getBackground().getXmlObject(); - CTBackgroundProperties bgPr = bg.getBgPr(); - - assertTrue(bgPr.isSetBlipFill()); - assertFalse(bgPr.isSetGradFill()); - assertFalse(bgPr.isSetGrpFill()); - assertFalse(bgPr.isSetPattFill()); - assertFalse(bgPr.isSetSolidFill()); - assertFalse(bgPr.isSetNoFill()); - - slide.getBackground().setFillColor(color); - - assertFalse(bgPr.isSetBlipFill()); - assertFalse(bgPr.isSetGradFill()); - assertFalse(bgPr.isSetGrpFill()); - assertFalse(bgPr.isSetPattFill()); - assertTrue(bgPr.isSetSolidFill()); - assertFalse(bgPr.isSetNoFill()); - - assertEquals(slide.getBackground().getFillColor(), color); - - slide.getBackground().setFillColor(null); - - assertFalse(bgPr.isSetBlipFill()); - assertFalse(bgPr.isSetGradFill()); - assertFalse(bgPr.isSetGrpFill()); - assertFalse(bgPr.isSetPattFill()); - assertFalse(bgPr.isSetSolidFill()); - assertTrue(bgPr.isSetNoFill()); - - assertNull(slide.getBackground().getFillColor()); - - pptx.close(); - } - - @Test - void testGradFillBackground() throws IOException { - XMLSlideShow pptx = XSLFTestDataSamples.openSampleDocument("themes.pptx"); - XSLFSlide slide = pptx.getSlides().get(9); - - Color color = Color.GREEN; - - CTBackgroundImpl bg = (CTBackgroundImpl) slide.getBackground().getXmlObject(); - CTBackgroundProperties bgPr = bg.getBgPr(); - - assertFalse(bgPr.isSetBlipFill()); - assertTrue(bgPr.isSetGradFill()); - assertFalse(bgPr.isSetGrpFill()); - assertFalse(bgPr.isSetPattFill()); - assertFalse(bgPr.isSetSolidFill()); - assertFalse(bgPr.isSetNoFill()); - - slide.getBackground().setFillColor(color); - - assertFalse(bgPr.isSetBlipFill()); - assertFalse(bgPr.isSetGradFill()); - assertFalse(bgPr.isSetGrpFill()); - assertFalse(bgPr.isSetPattFill()); - assertTrue(bgPr.isSetSolidFill()); - assertFalse(bgPr.isSetNoFill()); - - assertEquals(slide.getBackground().getFillColor(), color); - - slide.getBackground().setFillColor(null); - - assertFalse(bgPr.isSetBlipFill()); - assertFalse(bgPr.isSetGradFill()); - assertFalse(bgPr.isSetGrpFill()); - assertFalse(bgPr.isSetPattFill()); - assertFalse(bgPr.isSetSolidFill()); - assertTrue(bgPr.isSetNoFill()); - - assertNull(slide.getBackground().getFillColor()); - - pptx.close(); - } -} - diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFChart.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFChart.java deleted file mode 100644 index c9608359bb..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFChart.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xslf.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.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ooxml.POIXMLDocumentPart; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xddf.usermodel.chart.AxisCrossBetween; -import org.apache.poi.xddf.usermodel.chart.AxisCrosses; -import org.apache.poi.xddf.usermodel.chart.AxisOrientation; -import org.apache.poi.xddf.usermodel.chart.AxisPosition; -import org.apache.poi.xddf.usermodel.chart.AxisTickMark; -import org.apache.poi.xddf.usermodel.chart.BarDirection; -import org.apache.poi.xddf.usermodel.chart.BarGrouping; -import org.apache.poi.xddf.usermodel.chart.Grouping; -import org.apache.poi.xddf.usermodel.chart.LayoutMode; -import org.apache.poi.xddf.usermodel.chart.LayoutTarget; -import org.apache.poi.xddf.usermodel.chart.LegendPosition; -import org.apache.poi.xddf.usermodel.chart.RadarStyle; -import org.apache.poi.xddf.usermodel.chart.ScatterStyle; -import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFChartLegend; -import org.apache.poi.xddf.usermodel.chart.XDDFDataSource; -import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory; -import org.apache.poi.xddf.usermodel.chart.XDDFLineChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFManualLayout; -import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource; -import org.apache.poi.xddf.usermodel.chart.XDDFPieChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFRadarChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFScatterChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * a modified version from POI-examples - */ -class TestXSLFChart { - @Test - void testFillPieChartTemplate() throws IOException { - XMLSlideShow pptx = XSLFTestDataSamples.openSampleDocument("pie-chart.pptx"); - XSLFChart chart = findChart(pptx.getSlides().get(0)); - List<XDDFChartData> data = findChartData(chart); - - XDDFPieChartData pie = (XDDFPieChartData) data.get(0); - XDDFPieChartData.Series firstSeries = (XDDFPieChartData.Series) pie.getSeries(0); - firstSeries.setExplosion(25L); - assertEquals(Long.valueOf(25), firstSeries.getExplosion()); - - fillChartData(chart, pie); - pptx.close(); - } - - @Test - void testFillBarChartTemplate() throws IOException { - XMLSlideShow pptx = XSLFTestDataSamples.openSampleDocument("bar-chart.pptx"); - XSLFSlide slide = pptx.getSlides().get(0); - // duplicate slide and chart before applying "destructive" tests to it - XSLFChart chart2 = findChart(pptx.createSlide().importContent(slide)); - XSLFChart chart = findChart(slide); - - List<XDDFChartData> data = findChartData(chart); - XDDFBarChartData bar = (XDDFBarChartData) data.get(0); - assertEquals(BarDirection.BAR, bar.getBarDirection()); - assertEquals(BarGrouping.CLUSTERED, bar.getBarGrouping()); - assertEquals(Integer.valueOf(100), bar.getGapWidth()); - fillChartData(chart, bar); - - XDDFBarChartData column = (XDDFBarChartData) findChartData(chart2).get(0); - column.setBarDirection(BarDirection.COL); - assertEquals(BarDirection.COL, column.getBarDirection()); - column.getCategoryAxis().setOrientation(AxisOrientation.MIN_MAX); - column.getValueAxes().get(0).setPosition(AxisPosition.BOTTOM); - fillChartData(chart2, column); - - pptx.close(); - } - - @Test - void testFillLineChartTemplate() throws IOException { - XMLSlideShow pptx = XSLFTestDataSamples.openSampleDocument("line-chart.pptx"); - XSLFChart chart = findChart(pptx.getSlides().get(0)); - List<XDDFChartData> data = findChartData(chart); - - XDDFLineChartData line = (XDDFLineChartData) data.get(0); - assertEquals(Grouping.STANDARD, line.getGrouping()); - line.setGrouping(Grouping.PERCENT_STACKED); - assertEquals(Grouping.PERCENT_STACKED, line.getGrouping()); - - fillChartData(chart, line); - pptx.close(); - } - - @Test - void testFillRadarChartTemplate() throws IOException { - XMLSlideShow pptx = XSLFTestDataSamples.openSampleDocument("radar-chart.pptx"); - XSLFChart chart = findChart(pptx.getSlides().get(0)); - List<XDDFChartData> data = findChartData(chart); - - XDDFRadarChartData radar = (XDDFRadarChartData) data.get(0); - assertEquals(RadarStyle.MARKER, radar.getStyle()); - radar.setStyle(RadarStyle.FILLED); - assertEquals(RadarStyle.FILLED, radar.getStyle()); - - fillChartData(chart, radar); - pptx.close(); - } - - @Test - void testFillScatterChartTemplate() throws IOException { - XMLSlideShow pptx = XSLFTestDataSamples.openSampleDocument("scatter-chart.pptx"); - XSLFChart chart = findChart(pptx.getSlides().get(0)); - List<XDDFChartData> data = findChartData(chart); - - XDDFScatterChartData scatter = (XDDFScatterChartData) data.get(0); - assertEquals(ScatterStyle.LINE_MARKER, scatter.getStyle()); - scatter.setStyle(ScatterStyle.SMOOTH); - assertEquals(ScatterStyle.SMOOTH, scatter.getStyle()); - - fillChartData(chart, scatter); - pptx.close(); - } - - private void fillChartData(XSLFChart chart, XDDFChartData data) { - final int numOfPoints = 3; - final String[] categories = {"First", "Second", "Third"}; - final Integer[] values = {1, 3, 4}; - - final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0)); - final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 1, 1)); - - final XDDFChartData.Series series = data.getSeries(0); - final XDDFDataSource<?> categoryData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange); - final XDDFNumericalDataSource<Integer> valuesData = XDDFDataSourcesFactory.fromArray(values, valuesDataRange); - series.replaceData(categoryData, valuesData); - final String title = "Apache POI"; - series.setTitle(title, chart.setSheetTitle(title, 0)); - chart.plot(data); - } - - private XSLFChart findChart(XSLFSlide slide) { - // find chart in the slide - XSLFChart chart = null; - for(POIXMLDocumentPart part : slide.getRelations()){ - if(part instanceof XSLFChart){ - chart = (XSLFChart) part; - break; - } - } - - if(chart == null) { - throw new IllegalStateException("chart not found in the template"); - } - - checkLegendOperations(chart); - return chart; - } - - private List<XDDFChartData> findChartData(XSLFChart chart) { - List<XDDFChartData> data = chart.getChartSeries(); - assertNotNull(data); - assertEquals(1, data.size()); - - XDDFChartData firstSeries = data.get(0); - assertNotNull(firstSeries); - if (firstSeries instanceof XDDFScatterChartData) { - assertNull(firstSeries.getCategoryAxis()); - assertEquals(2, firstSeries.getValueAxes().size()); - checkAxisOperations(firstSeries.getValueAxes().get(0)); - checkAxisOperations(firstSeries.getValueAxes().get(1)); - } else if (!(firstSeries instanceof XDDFPieChartData)) { - assertNotNull(firstSeries.getCategoryAxis()); - assertEquals(1, firstSeries.getValueAxes().size()); - checkAxisOperations(firstSeries.getValueAxes().get(0)); - } - - return data; - } - - private void checkLegendOperations(XSLFChart chart) { - XDDFChartLegend legend = chart.getOrAddLegend(); - assertFalse(legend.isOverlay()); - legend.setOverlay(true); - assertTrue(legend.isOverlay()); - legend.setPosition(LegendPosition.TOP_RIGHT); - assertEquals(LegendPosition.TOP_RIGHT, legend.getPosition()); - - XDDFManualLayout layout = legend.getOrAddManualLayout(); - assertNotNull(layout.getTarget()); - assertNotNull(layout.getXMode()); - assertNotNull(layout.getYMode()); - assertNotNull(layout.getHeightMode()); - assertNotNull(layout.getWidthMode()); - /* - * According to interface, 0.0 should be returned for - * uninitialized double properties. - */ - assertEquals(0.0, layout.getX(), 0.0); - assertEquals(0.0, layout.getY(), 0.0); - assertEquals(0.0, layout.getWidthRatio(), 0.0); - assertEquals(0.0, layout.getHeightRatio(), 0.0); - - final double newRatio = 1.1; - final double newCoordinate = 0.3; - final LayoutMode nonDefaultMode = LayoutMode.FACTOR; - final LayoutTarget nonDefaultTarget = LayoutTarget.OUTER; - - layout.setWidthRatio(newRatio); - assertEquals(layout.getWidthRatio(), newRatio, 0.0); - - layout.setHeightRatio(newRatio); - assertEquals(layout.getHeightRatio(), newRatio, 0.0); - - layout.setX(newCoordinate); - assertEquals(layout.getX(), newCoordinate, 0.0); - - layout.setY(newCoordinate); - assertEquals(layout.getY(), newCoordinate, 0.0); - - layout.setXMode(nonDefaultMode); - assertSame(layout.getXMode(), nonDefaultMode); - - layout.setYMode(nonDefaultMode); - assertSame(layout.getYMode(), nonDefaultMode); - - layout.setWidthMode(nonDefaultMode); - assertSame(layout.getWidthMode(), nonDefaultMode); - - layout.setHeightMode(nonDefaultMode); - assertSame(layout.getHeightMode(), nonDefaultMode); - - layout.setTarget(nonDefaultTarget); - assertSame(layout.getTarget(), nonDefaultTarget); - } - - private void checkAxisOperations(XDDFValueAxis axis) { - axis.setCrossBetween(AxisCrossBetween.MIDPOINT_CATEGORY); - assertEquals(AxisCrossBetween.MIDPOINT_CATEGORY, axis.getCrossBetween()); - - axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(AxisCrosses.AUTO_ZERO, axis.getCrosses()); - - final String numberFormat = "General"; - axis.setNumberFormat(numberFormat); - assertEquals(numberFormat, axis.getNumberFormat()); - - axis.setPosition(AxisPosition.BOTTOM); - assertEquals(AxisPosition.BOTTOM, axis.getPosition()); - - axis.setMajorTickMark(AxisTickMark.NONE); - assertEquals(AxisTickMark.NONE, axis.getMajorTickMark()); - - axis.setMajorTickMark(AxisTickMark.IN); - assertEquals(AxisTickMark.IN, axis.getMajorTickMark()); - - axis.setMajorTickMark(AxisTickMark.OUT); - assertEquals(AxisTickMark.OUT, axis.getMajorTickMark()); - - axis.setMajorTickMark(AxisTickMark.CROSS); - assertEquals(AxisTickMark.CROSS, axis.getMajorTickMark()); - - axis.setMinorTickMark(AxisTickMark.NONE); - assertEquals(AxisTickMark.NONE, axis.getMinorTickMark()); - - axis.setMinorTickMark(AxisTickMark.IN); - assertEquals(AxisTickMark.IN, axis.getMinorTickMark()); - - axis.setMinorTickMark(AxisTickMark.OUT); - assertEquals(AxisTickMark.OUT, axis.getMinorTickMark()); - - axis.setMinorTickMark(AxisTickMark.CROSS); - assertEquals(AxisTickMark.CROSS, axis.getMinorTickMark()); - - axis.setVisible(true); - assertTrue(axis.isVisible()); - - axis.setVisible(false); - assertFalse(axis.isVisible()); - - final double EPSILON = 1E-7; - axis.setLogBase(Math.E); - assertTrue(Math.abs(axis.getLogBase() - Math.E) < EPSILON); - - final double newValue = 10.0; - - axis.setMinimum(newValue); - assertTrue(Math.abs(axis.getMinimum() - newValue) < EPSILON); - - axis.setMaximum(newValue); - assertTrue(Math.abs(axis.getMaximum() - newValue) < EPSILON); - - IllegalArgumentException iae = null; - try { - axis.setLogBase(0.0); - } catch (IllegalArgumentException e) { - iae = e; - } - assertNotNull(iae); - - iae = null; - try { - axis.setLogBase(30000.0); - } catch (IllegalArgumentException e) { - iae = e; - } - assertNotNull(iae); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFColor.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFColor.java deleted file mode 100644 index a872ecca1b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFColor.java +++ /dev/null @@ -1,185 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.awt.Color; -import java.io.IOException; - -import org.apache.poi.sl.usermodel.PresetColor; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTHslColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSystemColor; -import org.openxmlformats.schemas.drawingml.x2006.main.STPresetColorVal; -import org.openxmlformats.schemas.drawingml.x2006.main.STSchemeColorVal; -import org.openxmlformats.schemas.drawingml.x2006.main.STSystemColorVal; - -class TestXSLFColor { - - @Test - void testGetters() { - CTColor xml = CTColor.Factory.newInstance(); - CTSRgbColor c = xml.addNewSrgbClr(); - c.setVal(new byte[]{(byte)0xFF, 0, 0}); - - XSLFColor color = new XSLFColor(xml, null, null, null); - - assertEquals(-1, color.getAlpha()); - c.addNewAlpha().setVal(50000); - assertEquals(50, color.getAlpha()); - - assertEquals(-1, color.getAlphaMod()); - c.addNewAlphaMod().setVal(50000); - assertEquals(50, color.getAlphaMod()); - - assertEquals(-1, color.getAlphaOff()); - c.addNewAlphaOff().setVal(50000); - assertEquals(50, color.getAlphaOff()); - - assertEquals(-1, color.getLumMod()); - c.addNewLumMod().setVal(50000); - assertEquals(50, color.getLumMod()); - - assertEquals(-1, color.getLumOff()); - c.addNewLumOff().setVal(50000); - assertEquals(50, color.getLumOff()); - - assertEquals(-1, color.getSat()); - c.addNewSat().setVal(50000); - assertEquals(50, color.getSat()); - - assertEquals(-1, color.getSatMod()); - c.addNewSatMod().setVal(50000); - assertEquals(50, color.getSatMod()); - - assertEquals(-1, color.getSatOff()); - c.addNewSatOff().setVal(50000); - assertEquals(50, color.getSatOff()); - - assertEquals(-1, color.getRed()); - c.addNewRed().setVal(50000); - assertEquals(50, color.getRed()); - - assertEquals(-1, color.getGreen()); - c.addNewGreen().setVal(50000); - assertEquals(50, color.getGreen()); - - assertEquals(-1, color.getBlue()); - c.addNewBlue().setVal(50000); - assertEquals(50, color.getRed()); - - assertEquals(-1, color.getShade()); - c.addNewShade().setVal(50000); - assertEquals(50, color.getShade()); - - assertEquals(-1, color.getTint()); - c.addNewTint().setVal(50000); - assertEquals(50, color.getTint()); - } - - @Test - void testHSL() { - CTColor xml = CTColor.Factory.newInstance(); - CTHslColor c = xml.addNewHslClr(); - c.setHue2(14400000); - c.setSat2(100000); - c.setLum2(50000); - - XSLFColor color = new XSLFColor(xml, null, null, null); - assertEquals(Color.BLUE, color.getColor()); - } - - @Test - void testSRgb() { - CTColor xml = CTColor.Factory.newInstance(); - xml.addNewSrgbClr().setVal(new byte[]{ (byte)0xFF, (byte)0xFF, 0}); - - XSLFColor color = new XSLFColor(xml, null, null, null); - assertEquals(new Color(0xFF, 0xFF, 0), color.getColor()); - } - - @Test - void testSchemeColor() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSheet slide = ppt.createSlide(); - XSLFTheme theme = slide.getTheme(); - - CTColor xml = CTColor.Factory.newInstance(); - xml.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_2); - - XSLFColor color = new XSLFColor(xml, theme, null, slide); - // accent2 is theme1.xml is <a:srgbClr val="C0504D"/> - assertEquals(Color.decode("0xC0504D"), color.getColor()); - - xml = CTColor.Factory.newInstance(); - xml.addNewSchemeClr().setVal(STSchemeColorVal.LT_1); - color = new XSLFColor(xml, theme, null, slide); - // <a:sysClr val="window" lastClr="FFFFFF"/> - assertEquals(Color.decode("0xFFFFFF"), color.getColor()); - - xml = CTColor.Factory.newInstance(); - xml.addNewSchemeClr().setVal(STSchemeColorVal.DK_1); - color = new XSLFColor(xml, theme, null, slide); - // <a:sysClr val="windowText" lastClr="000000"/> - assertEquals(Color.decode("0x000000"), color.getColor()); - - ppt.close(); - } - - @Test - void testPresetColor() { - CTColor xml = CTColor.Factory.newInstance(); - xml.addNewPrstClr().setVal(STPresetColorVal.AQUAMARINE); - XSLFColor color = new XSLFColor(xml, null, null, null); - assertEquals(new Color(127, 255, 212), color.getColor()); - - - for(PresetColor pc : PresetColor.values()) { - if (pc.ooxmlId == null) continue; - xml = CTColor.Factory.newInstance(); - STPresetColorVal.Enum preVal = STPresetColorVal.Enum.forString(pc.ooxmlId); - STSystemColorVal.Enum sysVal = STSystemColorVal.Enum.forString(pc.ooxmlId); - assertTrue(preVal != null || sysVal != null, pc.ooxmlId); - if (preVal != null) { - xml.addNewPrstClr().setVal(preVal); - } else { - xml.addNewSysClr().setVal(sysVal); - } - color = new XSLFColor(xml, null, null, null); - assertEquals(pc.color, color.getColor()); - } - } - - @Test - void testSys() { - CTColor xml = CTColor.Factory.newInstance(); - CTSystemColor sys = xml.addNewSysClr(); - sys.setVal(STSystemColorVal.CAPTION_TEXT); - XSLFColor color = new XSLFColor(xml, null, null, null); - assertEquals(Color.black, color.getColor()); - - xml = CTColor.Factory.newInstance(); - sys = xml.addNewSysClr(); - sys.setLastClr(new byte[]{(byte)0xFF, 0, 0}); - color = new XSLFColor(xml, null, null, null); - assertEquals(Color.red, color.getColor()); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFConnectorShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFConnectorShape.java deleted file mode 100644 index d7afa7ef0b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFConnectorShape.java +++ /dev/null @@ -1,166 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.apache.poi.xslf.usermodel.TestXSLFSimpleShape.getSpPr; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.sl.usermodel.LineDecoration.DecorationShape; -import org.apache.poi.sl.usermodel.LineDecoration.DecorationSize; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTConnection; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualConnectorProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndLength; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndType; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndWidth; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTConnector; - -class TestXSLFConnectorShape { - - @Test - void testLineDecorations() throws IOException { - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - - XSLFConnectorShape shape = slide.createConnector(); - assertEquals(1, slide.getShapes().size()); - - assertFalse(getSpPr(shape).getLn().isSetHeadEnd()); - assertFalse(getSpPr(shape).getLn().isSetTailEnd()); - - // line decorations - assertEquals(DecorationShape.NONE, shape.getLineHeadDecoration()); - assertEquals(DecorationShape.NONE, shape.getLineTailDecoration()); - shape.setLineHeadDecoration(null); - shape.setLineTailDecoration(null); - assertEquals(DecorationShape.NONE, shape.getLineHeadDecoration()); - assertEquals(DecorationShape.NONE, shape.getLineTailDecoration()); - assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetType()); - assertFalse(getSpPr(shape).getLn().getTailEnd().isSetType()); - - shape.setLineHeadDecoration(DecorationShape.ARROW); - shape.setLineTailDecoration(DecorationShape.DIAMOND); - assertEquals(DecorationShape.ARROW, shape.getLineHeadDecoration()); - assertEquals(DecorationShape.DIAMOND, shape.getLineTailDecoration()); - assertEquals(STLineEndType.ARROW, getSpPr(shape).getLn().getHeadEnd().getType()); - assertEquals(STLineEndType.DIAMOND, getSpPr(shape).getLn().getTailEnd().getType()); - - shape.setLineHeadDecoration(DecorationShape.DIAMOND); - shape.setLineTailDecoration(DecorationShape.ARROW); - assertEquals(DecorationShape.DIAMOND, shape.getLineHeadDecoration()); - assertEquals(DecorationShape.ARROW, shape.getLineTailDecoration()); - assertEquals(STLineEndType.DIAMOND, getSpPr(shape).getLn().getHeadEnd().getType()); - assertEquals(STLineEndType.ARROW, getSpPr(shape).getLn().getTailEnd().getType()); - - // line end width - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth()); - shape.setLineHeadWidth(null); - shape.setLineHeadWidth(null); - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth()); - assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetW()); - assertFalse(getSpPr(shape).getLn().getTailEnd().isSetW()); - shape.setLineHeadWidth(DecorationSize.LARGE); - shape.setLineTailWidth(DecorationSize.MEDIUM); - assertEquals(DecorationSize.LARGE, shape.getLineHeadWidth()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth()); - assertEquals(STLineEndWidth.LG, getSpPr(shape).getLn().getHeadEnd().getW()); - assertEquals(STLineEndWidth.MED, getSpPr(shape).getLn().getTailEnd().getW()); - shape.setLineHeadWidth(DecorationSize.MEDIUM); - shape.setLineTailWidth(DecorationSize.LARGE); - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth()); - assertEquals(DecorationSize.LARGE, shape.getLineTailWidth()); - assertEquals(STLineEndWidth.MED, getSpPr(shape).getLn().getHeadEnd().getW()); - assertEquals(STLineEndWidth.LG, getSpPr(shape).getLn().getTailEnd().getW()); - - // line end length - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength()); - shape.setLineHeadLength(null); - shape.setLineTailLength(null); - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength()); - assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetLen()); - assertFalse(getSpPr(shape).getLn().getTailEnd().isSetLen()); - shape.setLineHeadLength(DecorationSize.LARGE); - shape.setLineTailLength(DecorationSize.MEDIUM); - assertEquals(DecorationSize.LARGE, shape.getLineHeadLength()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength()); - assertEquals(STLineEndLength.LG, getSpPr(shape).getLn().getHeadEnd().getLen()); - assertEquals(STLineEndLength.MED, getSpPr(shape).getLn().getTailEnd().getLen()); - shape.setLineHeadLength(DecorationSize.MEDIUM); - shape.setLineTailLength(DecorationSize.LARGE); - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength()); - assertEquals(DecorationSize.LARGE, shape.getLineTailLength()); - assertEquals(STLineEndLength.MED, getSpPr(shape).getLn().getHeadEnd().getLen()); - assertEquals(STLineEndLength.LG, getSpPr(shape).getLn().getTailEnd().getLen()); - } - } - - @Test - void testAddConnector() throws IOException { - try (XMLSlideShow pptx = new XMLSlideShow()) { - XSLFSlide slide = pptx.createSlide(); - - XSLFAutoShape rect1 = slide.createAutoShape(); - rect1.setShapeType(ShapeType.RECT); - rect1.setAnchor(new Rectangle2D.Double(100, 100, 100, 100)); - rect1.setFillColor(Color.blue); - - XSLFAutoShape rect2 = slide.createAutoShape(); - rect2.setShapeType(ShapeType.RECT); - rect2.setAnchor(new Rectangle2D.Double(300, 300, 100, 100)); - rect2.setFillColor(Color.red); - - - XSLFConnectorShape connector1 = slide.createConnector(); - Rectangle2D r1 = new Rectangle2D.Double(200, 150, 100, 200); - connector1.setAnchor(r1); - - CTConnector ctConnector = (CTConnector) connector1.getXmlObject(); - ctConnector.getSpPr().getPrstGeom().setPrst(STShapeType.BENT_CONNECTOR_3); - CTNonVisualConnectorProperties cx = ctConnector.getNvCxnSpPr().getCNvCxnSpPr(); - // connection start - CTConnection stCxn = cx.addNewStCxn(); - stCxn.setId(rect1.getShapeId()); - // side of the rectangle to attach the connector: left=1, bottom=2,right=3, top=4 - stCxn.setIdx(2); - - CTConnection end = cx.addNewEndCxn(); - end.setId(rect2.getShapeId()); - // side of the rectangle to attach the connector: left=1, bottom=2,right=3, top=4 - end.setIdx(3); - - try (XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(pptx)) { - XSLFSlide s1 = ppt2.getSlides().get(0); - List<XSLFShape> shapes = s1.getShapes(); - XSLFConnectorShape c1 = (XSLFConnectorShape)shapes.get(2); - assertEquals(r1, c1.getAnchor()); - } - } - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFExamples.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFExamples.java deleted file mode 100644 index 02640c0efe..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFExamples.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.awt.Rectangle; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.apache.xmlbeans.XmlCursor; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTHyperlink; -import org.openxmlformats.schemas.presentationml.x2006.main.CTApplicationNonVisualDrawingProps; -import org.openxmlformats.schemas.presentationml.x2006.main.CTExtension; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlide; -import org.openxmlformats.schemas.presentationml.x2006.main.CTTLCommonMediaNodeData; -import org.openxmlformats.schemas.presentationml.x2006.main.CTTLCommonTimeNodeData; -import org.openxmlformats.schemas.presentationml.x2006.main.CTTimeNodeList; -import org.openxmlformats.schemas.presentationml.x2006.main.STTLTimeIndefinite; -import org.openxmlformats.schemas.presentationml.x2006.main.STTLTimeNodeFillType; -import org.openxmlformats.schemas.presentationml.x2006.main.STTLTimeNodeRestartType; -import org.openxmlformats.schemas.presentationml.x2006.main.STTLTimeNodeType; - -/** - * Reimplement and test examples classes so the necessary XmlBeans schema objects are included - * in the lite schema - */ -class TestXSLFExamples { - @Test - void LinkVideoToPptx() throws IOException, URISyntaxException { - String videoFileName = "file_example_MP4_640_3MG.mp4"; - File previewJpg = POIDataSamples.getDocumentInstance().getFile("abstract1.jpg"); - - try (XMLSlideShow pptx = new XMLSlideShow()) { - XSLFSlide slide1 = pptx.createSlide(); - - PackagePart pp = slide1.getPackagePart(); - URI mp4uri = new URI("./" + videoFileName); - PackageRelationship prsEmbed1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.microsoft.com/office/2007/relationships/media"); - PackageRelationship prsExec1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video"); - - - XSLFPictureData snap = pptx.addPicture(previewJpg, PictureData.PictureType.JPEG); - XSLFPictureShape pic1 = slide1.createPicture(snap); - pic1.setAnchor(new Rectangle(100, 100, 500, 400)); - - CTPicture xpic1 = (CTPicture) pic1.getXmlObject(); - CTHyperlink link1 = xpic1.getNvPicPr().getCNvPr().addNewHlinkClick(); - link1.setId(""); - link1.setAction("ppaction://media"); - - - CTApplicationNonVisualDrawingProps nvPr = xpic1.getNvPicPr().getNvPr(); - nvPr.addNewVideoFile().setLink(prsExec1.getId()); - CTExtension ext = nvPr.addNewExtLst().addNewExt(); - ext.setUri("{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}"); - - String p14Ns = "http://schemas.microsoft.com/office/powerpoint/2010/main"; - XmlCursor cur = ext.newCursor(); - cur.toEndToken(); - cur.beginElement(new QName(p14Ns, "media", "p14")); - cur.insertNamespace("p14", p14Ns); - cur.insertAttributeWithValue(new QName(CORE_PROPERTIES_ECMA376_NS, "link"), prsEmbed1.getId()); - cur.dispose(); - - - CTSlide xslide = slide1.getXmlObject(); - CTTimeNodeList ctnl; - if (!xslide.isSetTiming()) { - CTTLCommonTimeNodeData ctn = xslide.addNewTiming().addNewTnLst().addNewPar().addNewCTn(); - ctn.setDur(STTLTimeIndefinite.INDEFINITE); - ctn.setRestart(STTLTimeNodeRestartType.NEVER); - ctn.setNodeType(STTLTimeNodeType.TM_ROOT); - ctnl = ctn.addNewChildTnLst(); - } else { - ctnl = xslide.getTiming().getTnLst().getParArray(0).getCTn().getChildTnLst(); - } - CTTLCommonMediaNodeData cmedia = ctnl.addNewVideo().addNewCMediaNode(); - cmedia.setVol(80000); - CTTLCommonTimeNodeData ctn = cmedia.addNewCTn(); - ctn.setFill(STTLTimeNodeFillType.HOLD); - ctn.setDisplay(false); - ctn.addNewStCondLst().addNewCond().setDelay(STTLTimeIndefinite.INDEFINITE); - cmedia.addNewTgtEl().addNewSpTgt().setSpid(pic1.getShapeId()); - - try (XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(pptx)) { - XSLFShape sh = ppt2.getSlides().get(0).getShapes().get(0); - assertTrue(sh instanceof XSLFPictureShape); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFFreeformShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFFreeformShape.java deleted file mode 100644 index 6f57d11790..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFFreeformShape.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - - -import org.apache.poi.sl.draw.SLGraphics; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Line2D; -import java.awt.geom.Path2D; -import java.awt.geom.PathIterator; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.IOException; - -import static org.apache.poi.xslf.usermodel.TestXSLFSimpleShape.getSpPr; -import static org.junit.jupiter.api.Assertions.assertEquals; - -class TestXSLFFreeformShape { - - @Test - void testSetPath() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - XSLFFreeformShape shape1 = slide.createFreeform(); - // comples path consisting of a rectangle and an ellipse inside it - Path2D.Double path1 = new Path2D.Double(new Rectangle2D.Double(150, 150, 300, 300)); - path1.append(new Ellipse2D.Double(200, 200, 100, 50), false); - shape1.setPath(path1); - - Path2D.Double path2 = shape1.getPath(); - - // YK: how to compare the original path1 and the value returned by XSLFFreeformShape.getPath() ? - // one way is to create another XSLFFreeformShape from path2 and compare the resulting xml - assertEquals(path1.getBounds2D(), path2.getBounds2D()); - - XSLFFreeformShape shape2 = slide.createFreeform(); - shape2.setPath(path2); - - assertEquals(getSpPr(shape1).getCustGeom().toString(), getSpPr(shape2).getCustGeom().toString()); - - ppt.close(); - } - - @Test - void testZeroWidth() throws IOException { - // see #61633 - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - XSLFFreeformShape shape1 = slide.createFreeform(); - Path2D.Double path1 = new Path2D.Double(new Line2D.Double(100, 150, 100, 300)); - shape1.setPath(path1); - shape1.setLineColor(Color.BLUE); - shape1.setLineWidth(1); - - BufferedImage img = new BufferedImage(300, 300, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = img.createGraphics(); - try { - // previously we used Mockito here, but since JDK 11 mocking the Graphics2D does - // not work any longer - Graphics2D graphicsMock = new SLGraphics(new XSLFGroupShape(CTGroupShape.Factory.newInstance(), slide)) { - boolean called; - - @Override - public void draw(Shape shape) { - if(called) { - throw new IllegalStateException("Should only be called once, but was called a second time"); - } - called = true; - - if(!(shape instanceof Path2D.Double)) { - throw new IllegalStateException("Expecting a shape of type Path2D.Double, but had " + shape.getClass()); - } - - Path2D.Double actual = (Path2D.Double) shape; - PathIterator pi = actual.getPathIterator(new AffineTransform()); - comparePoint(pi, PathIterator.SEG_MOVETO, 100, 150); - pi.next(); - comparePoint(pi, PathIterator.SEG_LINETO, 100, 300); - - super.draw(shape); - } - }; - slide.draw(graphicsMock); - } finally { - graphics.dispose(); - } - } - } - - private void comparePoint(PathIterator pi, int type, double x0, double y0) { - double[] points = new double[6]; - int piType = pi.currentSegment(points); - assertEquals(type, piType); - assertEquals(x0, points[0], 0); - assertEquals(y0, points[1], 0); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFGroupShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFGroupShape.java deleted file mode 100644 index 547da5f71c..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFGroupShape.java +++ /dev/null @@ -1,108 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.awt.Dimension; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; - -class TestXSLFGroupShape { - - @Test - void testCreateShapes() throws Exception { - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - - ppt.setPageSize(new Dimension(792, 612)); - - XSLFGroupShape group = slide.createGroup(); - assertEquals(1, slide.getShapes().size()); - - Rectangle2D interior = new Rectangle2D.Double(-10, -10, 20, 20); - group.setInteriorAnchor(interior); - assertEquals(interior, group.getInteriorAnchor()); - - Rectangle2D anchor = new Rectangle2D.Double(0, 0, 792, 612); - group.setAnchor(anchor); - assertEquals(anchor, group.getAnchor()); - - assertTrue(group.getShapes().isEmpty()); - - XSLFTextBox shape1 = group.createTextBox(); - assertEquals(1, group.getShapes().size()); - assertSame(shape1, group.getShapes().get(0)); - assertEquals(3, shape1.getShapeId()); - - XSLFAutoShape shape2 = group.createAutoShape(); - assertEquals(2, group.getShapes().size()); - assertSame(shape1, group.getShapes().get(0)); - assertSame(shape2, group.getShapes().get(1)); - assertEquals(4, shape2.getShapeId()); - - XSLFConnectorShape shape3 = group.createConnector(); - assertEquals(3, group.getShapes().size()); - assertSame(shape3, group.getShapes().get(2)); - assertEquals(5, shape3.getShapeId()); - - XSLFGroupShape shape4 = group.createGroup(); - assertEquals(4, group.getShapes().size()); - assertSame(shape4, group.getShapes().get(3)); - assertEquals(6, shape4.getShapeId()); - - group.removeShape(shape2); - assertEquals(3, group.getShapes().size()); - assertSame(shape1, group.getShapes().get(0)); - assertSame(shape3, group.getShapes().get(1)); - assertSame(shape4, group.getShapes().get(2)); - - group.removeShape(shape3); - assertEquals(2, group.getShapes().size()); - assertSame(shape1, group.getShapes().get(0)); - assertSame(shape4, group.getShapes().get(1)); - - group.removeShape(shape1); - group.removeShape(shape4); - assertTrue(group.getShapes().isEmpty()); - } - } - - @Test - void testRemoveShapes() throws Exception { - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - - XSLFGroupShape group1 = slide.createGroup(); - group1.createTextBox(); - XSLFGroupShape group2 = slide.createGroup(); - group2.createTextBox(); - XSLFGroupShape group3 = slide.createGroup(); - slide.removeShape(group1); - slide.removeShape(group2); - slide.removeShape(group3); - - try (XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt)) { - assertEquals(0, ppt2.getSlides().get(0).getShapes().size()); - } - } - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFHyperlink.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFHyperlink.java deleted file mode 100644 index 90fcf71568..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFHyperlink.java +++ /dev/null @@ -1,180 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; - -class TestXSLFHyperlink { - - @Test - void testRead() throws IOException{ - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - - XSLFSlide slide = ppt.getSlides().get(4); - List<XSLFShape> shapes = slide.getShapes(); - XSLFTable tbl = (XSLFTable)shapes.get(0); - XSLFTableCell cell1 = tbl.getRows().get(1).getCells().get(0); - assertEquals("Web Page", cell1.getText()); - XSLFHyperlink link1 = cell1.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(link1); - assertEquals("http://poi.apache.org/", link1.getAddress()); - - XSLFTableCell cell2 = tbl.getRows().get(2).getCells().get(0); - assertEquals("Place in this document", cell2.getText()); - XSLFHyperlink link2 = cell2.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(link2); - assertEquals("/ppt/slides/slide2.xml", link2.getAddress()); - - XSLFTableCell cell3 = tbl.getRows().get(3).getCells().get(0); - assertEquals("Email", cell3.getText()); - XSLFHyperlink link3 = cell3.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(link3); - assertEquals("mailto:dev@poi.apache.org?subject=Hi%20There", link3.getAddress()); - - ppt.close(); - } - - @Test - void testCreate() throws IOException, InvalidFormatException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide1 = ppt.createSlide(); - XSLFSlide slide2 = ppt.createSlide(); - - int numRel = slide1.getPackagePart().getRelationships().size(); - assertEquals(1, numRel); - XSLFTextBox sh1 = slide1.createTextBox(); - XSLFTextRun r1 = sh1.addNewTextParagraph().addNewTextRun(); - r1.setText("Web Page"); - XSLFHyperlink link1 = r1.createHyperlink(); - link1.setAddress("http://poi.apache.org/"); - assertEquals("http://poi.apache.org/", link1.getAddress()); - assertEquals(numRel + 1, slide1.getPackagePart().getRelationships().size()); - - String id1 = link1.getXmlObject().getId(); - assertNotNull(id1); - PackageRelationship rel1 = slide1.getPackagePart().getRelationship(id1); - assertNotNull(rel1); - assertEquals(id1, rel1.getId()); - assertEquals(TargetMode.EXTERNAL, rel1.getTargetMode()); - assertEquals(XSLFRelation.HYPERLINK.getRelation(), rel1.getRelationshipType()); - - XSLFTextBox sh2 = slide1.createTextBox(); - XSLFTextRun r2 = sh2.addNewTextParagraph().addNewTextRun(); - r2.setText("Place in this document"); - XSLFHyperlink link2 = r2.createHyperlink(); - link2.linkToSlide(slide2); - assertEquals("/ppt/slides/slide2.xml", link2.getAddress()); - assertEquals(numRel + 2, slide1.getPackagePart().getRelationships().size()); - - String id2 = link2.getXmlObject().getId(); - assertNotNull(id2); - PackageRelationship rel2 = slide1.getPackagePart().getRelationship(id2); - assertNotNull(rel2); - assertEquals(id2, rel2.getId()); - assertEquals(TargetMode.INTERNAL, rel2.getTargetMode()); - assertEquals(XSLFRelation.SLIDE.getRelation(), rel2.getRelationshipType()); - - ppt.close(); - } - - - @Test - void bug47291() throws IOException { - Rectangle2D anchor = new Rectangle2D.Double(100,100,100,100); - XMLSlideShow ppt1 = new XMLSlideShow(); - XSLFSlide slide1 = ppt1.createSlide(); - XSLFTextBox tb1 = slide1.createTextBox(); - tb1.setAnchor(anchor); - XSLFTextRun r1 = tb1.setText("page1"); - XSLFHyperlink hl1 = r1.createHyperlink(); - hl1.linkToEmail("dev@poi.apache.org"); - XSLFTextBox tb2 = ppt1.createSlide().createTextBox(); - tb2.setAnchor(anchor); - XSLFTextRun r2 = tb2.setText("page2"); - XSLFHyperlink hl2 = r2.createHyperlink(); - hl2.linkToLastSlide(); - XSLFSlide sl3 = ppt1.createSlide(); - XSLFTextBox tb3 = sl3.createTextBox(); - tb3.setAnchor(anchor); - tb3.setText("text1 "); - tb3.appendText("lin\u000bk", false); - tb3.appendText(" text2", false); - List<XSLFTextRun> tb3runs = tb3.getTextParagraphs().get(0).getTextRuns(); - tb3runs.get(1).createHyperlink().linkToSlide(slide1); // "lin" - tb3runs.get(3).createHyperlink().linkToSlide(slide1); // "k" - XSLFTextBox tb4 = ppt1.createSlide().createTextBox(); - tb4.setAnchor(anchor); - XSLFTextRun r4 = tb4.setText("page4"); - XSLFHyperlink hl4 = r4.createHyperlink(); - hl4.linkToUrl("http://poi.apache.org"); - XSLFTextBox tb5 = ppt1.createSlide().createTextBox(); - tb5.setAnchor(anchor); - tb5.setText("page5"); - XSLFHyperlink hl5 = tb5.createHyperlink(); - hl5.linkToFirstSlide(); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - - List<XSLFSlide> slides = ppt2.getSlides(); - tb1 = (XSLFTextBox)slides.get(0).getShapes().get(0); - hl1 = tb1.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(hl1); - assertEquals("dev@poi.apache.org", hl1.getLabel()); - assertEquals(HyperlinkType.EMAIL, hl1.getType()); - - tb2 = (XSLFTextBox)slides.get(1).getShapes().get(0); - hl2 = tb2.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(hl2); - assertEquals("lastslide", hl2.getXmlObject().getAction().split("=")[1]); - assertEquals(HyperlinkType.DOCUMENT, hl2.getType()); - - tb3 = (XSLFTextBox)slides.get(2).getShapes().get(0); - XSLFHyperlink hl3 = tb3.getTextParagraphs().get(0).getTextRuns().get(1).getHyperlink(); - assertNotNull(hl3); - hl3 = tb3.getTextParagraphs().get(0).getTextRuns().get(3).getHyperlink(); - assertNotNull(hl3); - assertEquals("/ppt/slides/slide1.xml", hl3.getAddress()); - assertEquals(HyperlinkType.DOCUMENT, hl3.getType()); - - tb4 = (XSLFTextBox)slides.get(3).getShapes().get(0); - hl4 = tb4.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(hl4); - assertEquals("http://poi.apache.org", hl4.getLabel()); - assertEquals(HyperlinkType.URL, hl4.getType()); - - tb5 = (XSLFTextBox)slides.get(4).getShapes().get(0); - hl5 = tb5.getHyperlink(); - assertNotNull(hl5); - assertEquals("firstslide", hl5.getXmlObject().getAction().split("=")[1]); - assertEquals(HyperlinkType.DOCUMENT, hl5.getType()); - - ppt2.close(); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFNotes.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFNotes.java deleted file mode 100644 index 526abab2c9..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFNotes.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.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 java.io.IOException; - -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; - -class TestXSLFNotes { - - @Test - void createNewNote() throws IOException { - - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide1 = ppt.createSlide(); - - assertNull(ppt.getNotesMaster()); - assertNull(slide1.getNotes()); - - XSLFNotes notesSlide = ppt.getNotesSlide(slide1); - assertNotNull(ppt.getNotesMaster()); - assertNotNull(notesSlide); - - String note = null; - for (XSLFTextShape shape : notesSlide.getPlaceholders()) { - if (shape.getTextType() == Placeholder.BODY) { - shape.setText("New Note"); - note = shape.getText(); - break; - } - } - assertNotNull(note); - assertEquals("New Note", note); - - ppt.close(); - } - - @Test - void addNote() throws IOException { - - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("sample.pptx"); - - XSLFSlide slide = ppt.createSlide(); - XSLFNotes notesSlide = ppt.getNotesSlide(slide); - assertNotNull(notesSlide); - - String note = null; - for (XSLFTextShape shape : notesSlide.getPlaceholders()) { - if (shape.getTextType() == Placeholder.BODY) { - shape.setText("New Note"); - note = shape.getText(); - break; - } - } - assertNotNull(note); - assertEquals("New Note", note); - - ppt.close(); - } - - @Test - void replaceNotes() throws IOException { - - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("sample.pptx"); - - for (XSLFSlide slide : ppt.getSlides()) { - assertNotNull(slide.getNotes()); - - XSLFNotes notesSlide = ppt.getNotesSlide(slide); - assertNotNull(notesSlide); - - String note = null; - for (XSLFTextShape shape : notesSlide.getPlaceholders()) { - if (shape.getTextType() == Placeholder.BODY) { - shape.setText("New Note"); - note = shape.getText(); - break; - } - } - assertNotNull(note); - assertEquals("New Note", note); - } - - ppt.close(); - } - - @Test - void importNotes() throws IOException { - - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("sample.pptx"); - XMLSlideShow newShow = new XMLSlideShow(); - - for (XSLFSlide slide : ppt.getSlides()) { - XSLFNotes slideNotes = slide.getNotes(); - assertNotNull(slideNotes); - XSLFNotes notesSlide = ppt.getNotesSlide(slide); - assertNotNull(notesSlide); - assertEquals(notesSlide, slideNotes); - - XSLFSlide newSlide = newShow.createSlide().importContent(slide); - XSLFNotes newNotes = newSlide.getNotes(); - assertNotNull(newNotes); - } - - ppt.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java deleted file mode 100644 index 0df21b2720..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java +++ /dev/null @@ -1,295 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.imageio.IIOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.apache.poi.xslf.util.PPTX2PNG; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture; - -class TestXSLFPictureShape { - private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - @Test - void testCreate() throws Exception { - XMLSlideShow ppt1 = new XMLSlideShow(); - assertEquals(0, ppt1.getPictureData().size()); - byte[] data1 = new byte[100]; - for(int i = 0;i < 100;i++) { data1[i] = (byte)i; } - XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG); - assertEquals(0, pdata1.getIndex()); - assertEquals(1, ppt1.getPictureData().size()); - - XSLFSlide slide = ppt1.createSlide(); - XSLFPictureShape shape1 = slide.createPicture(pdata1); - assertNotNull(shape1.getPictureData()); - assertArrayEquals(data1, shape1.getPictureData().getData()); - - byte[] data2 = new byte[200]; - for(int i = 0;i < 200;i++) { data2[i] = (byte)i; } - XSLFPictureData pdata2 = ppt1.addPicture(data2, PictureType.PNG); - XSLFPictureShape shape2 = slide.createPicture(pdata2); - assertNotNull(shape2.getPictureData()); - assertEquals(1, pdata2.getIndex()); - assertEquals(2, ppt1.getPictureData().size()); - assertArrayEquals(data2, shape2.getPictureData().getData()); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - List<XSLFPictureData> pics = ppt2.getPictureData(); - assertEquals(2, pics.size()); - assertArrayEquals(data1, pics.get(0).getData()); - assertArrayEquals(data2, pics.get(1).getData()); - - List<XSLFShape> shapes = ppt2.getSlides().get(0).getShapes(); - assertArrayEquals(data1, ((XSLFPictureShape) shapes.get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((XSLFPictureShape) shapes.get(1)).getPictureData().getData()); - ppt2.close(); - } - - @Test - void testCreateMultiplePictures() throws Exception { - XMLSlideShow ppt1 = new XMLSlideShow(); - XSLFSlide slide1 = ppt1.createSlide(); - XSLFGroupShape group1 = slide1.createGroup(); - - - int pictureIndex = 0; - // first add 20 images to the slide - for (int i = 0; i < 20; i++, pictureIndex++) { - byte[] data = new byte[]{(byte)pictureIndex}; - XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG); - assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19 - XSLFPictureShape picture = slide1.createPicture(elementData); - // POI saves images as image1.png, image2.png, etc. - String fileName = "image" + (elementData.getIndex()+1) + ".png"; - assertEquals(fileName, picture.getPictureData().getFileName()); - assertArrayEquals(data, picture.getPictureData().getData()); - } - - // and then add next 20 images to a group - for (int i = 0; i < 20; i++, pictureIndex++) { - byte[] data = new byte[]{(byte)pictureIndex}; - XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG); - XSLFPictureShape picture = group1.createPicture(elementData); - // POI saves images as image1.png, image2.png, etc. - assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19 - String fileName = "image" + (pictureIndex + 1) + ".png"; - assertEquals(fileName, picture.getPictureData().getFileName()); - assertArrayEquals(data, picture.getPictureData().getData()); - } - - // serialize, read back and check that all images are there - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - // pictures keyed by file name - Map<String, XSLFPictureData> pics = new HashMap<>(); - for(XSLFPictureData p : ppt2.getPictureData()){ - pics.put(p.getFileName(), p); - } - assertEquals(40, pics.size()); - for (int i = 0; i < 40; i++) { - byte[] data1 = new byte[]{(byte)i}; - String fileName = "image" + (i + 1) + ".png"; - XSLFPictureData data = pics.get(fileName); - assertNotNull(data); - assertEquals(fileName, data.getFileName()); - assertArrayEquals(data1, data.getData()); - } - ppt2.close(); - } - - @Test - void testImageCaching() throws Exception { - XMLSlideShow ppt = new XMLSlideShow(); - byte[] img1 = new byte[]{1,2,3}; - byte[] img2 = new byte[]{3,4,5}; - XSLFPictureData pdata1 = ppt.addPicture(img1, PictureType.PNG); - assertEquals(0, pdata1.getIndex()); - assertEquals(0, ppt.addPicture(img1, PictureType.PNG).getIndex()); - - XSLFPictureData idx2 = ppt.addPicture(img2, PictureType.PNG); - assertEquals(1, idx2.getIndex()); - assertEquals(1, ppt.addPicture(img2, PictureType.PNG).getIndex()); - - XSLFSlide slide1 = ppt.createSlide(); - assertNotNull(slide1); - XSLFSlide slide2 = ppt.createSlide(); - assertNotNull(slide2); - - ppt.close(); - } - - @Test - void testMerge() throws Exception { - XMLSlideShow ppt1 = new XMLSlideShow(); - byte[] data1 = new byte[100]; - XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG); - - XSLFSlide slide1 = ppt1.createSlide(); - XSLFPictureShape shape1 = slide1.createPicture(pdata1); - CTPicture ctPic1 = (CTPicture)shape1.getXmlObject(); - ctPic1.getNvPicPr().getNvPr().addNewCustDataLst().addNewTags().setId("rId99"); - - XSLFPictureShape shape2 = slide1.createPicture(pdata1); - CTPicture ctPic2 = (CTPicture)shape2.getXmlObject(); - ctPic2.getNvPicPr().getNvPr().addNewCustDataLst().addNewTags().setId("rId99"); - - differentShapeName(shape1, shape2); - - XSLFGroupShape group = slide1.createGroup(); - XSLFTextBox tb1 = group.createTextBox(); - XSLFTextBox tb2 = group.createTextBox(); - - assertNotEquals("We should have different names now, but had: " + tb1.getShapeName() + " for both", tb1.getShapeName(), tb2.getShapeName()); - - XMLSlideShow pptCopy = new XMLSlideShow(); - - XSLFSlide slideCopy = pptCopy.createSlide().importContent(slide1); - XSLFPictureShape shapeCopy1 = (XSLFPictureShape)slideCopy.getShapes().get(0); - - assertArrayEquals(data1, shapeCopy1.getPictureData().getData()); - assertEquals(shape1.getShapeName(), shapeCopy1.getShapeName()); - - CTPicture ctPicCopy1 = (CTPicture)shapeCopy1.getXmlObject(); - assertFalse(ctPicCopy1.getNvPicPr().getNvPr().isSetCustDataLst()); - - XSLFPictureShape shapeCopy2 = (XSLFPictureShape)slideCopy.getShapes().get(1); - - assertArrayEquals(data1, shapeCopy2.getPictureData().getData()); - assertEquals(shape2.getShapeName(), shapeCopy2.getShapeName()); - - CTPicture ctPicCopy2 = (CTPicture)shapeCopy2.getXmlObject(); - assertFalse(ctPicCopy2.getNvPicPr().getNvPr().isSetCustDataLst()); - - differentShapeName(shapeCopy1, shapeCopy2); - - XSLFGroupShape groupCopy = (XSLFGroupShape) slideCopy.getShapes().get(2); - XSLFTextBox tbCopy1 = (XSLFTextBox) groupCopy.getShapes().get(0); - XSLFTextBox tbCopy2 = (XSLFTextBox) groupCopy.getShapes().get(1); - - assertEquals(group.getShapeName(), groupCopy.getShapeName()); - assertEquals(tb1.getShapeName(), tbCopy1.getShapeName()); - assertEquals(tb2.getShapeName(), tbCopy2.getShapeName()); - - differentShapeName(tb1, tb2); - - ppt1.close(); - pptCopy.close(); - } - - private void differentShapeName(XSLFShape shape1, XSLFShape shape2) { - assertNotEquals("We should have different names now, but had: " + shape1.getShapeName() + " for both", shape1.getShapeName(), shape2.getShapeName()); - } - - @Test - void bug58663() throws IOException { - InputStream is = _slTests.openResourceAsStream("shapes.pptx"); - XMLSlideShow ppt = new XMLSlideShow(is); - is.close(); - - XSLFSlide slide = ppt.getSlides().get(0); - XSLFPictureShape ps = (XSLFPictureShape)slide.getShapes().get(3); - slide.removeShape(ps); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ppt.write(bos); - ppt.close(); - - XMLSlideShow ppt2 = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray())); - assertTrue(ppt2.getPictureData().isEmpty()); - ppt2.close(); - } - - @Test - void testTiffImageBug59742() throws Exception { - XMLSlideShow slideShow = new XMLSlideShow(); - final InputStream tiffStream = _slTests.openResourceAsStream("testtiff.tif"); - final byte[] pictureData = IOUtils.toByteArray(tiffStream); - IOUtils.closeQuietly(tiffStream); - - XSLFPictureData pic = slideShow.addPicture(pictureData, PictureType.TIFF); - assertEquals("image/tiff", pic.getContentType()); - assertEquals("image1.tiff", pic.getFileName()); - - slideShow.close(); - } - - - @Test - void renderSvgImage() throws Exception { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - try { - XSLFPictureData svgPic = ppt.addPicture(POIDataSamples.getDocumentInstance().getFile("../project-header.svg"), PictureType.SVG); - XSLFPictureShape shape = XSLFPictureShape.addSvgImage(slide, svgPic, PictureType.JPEG, null); - - Rectangle2D anchor = shape.getAnchor(); - anchor.setRect(100, 100, anchor.getWidth(), anchor.getHeight()); - shape.setAnchor(anchor); - - assertNotNull(shape.getSvgImage()); - - final File tmpFile = TempFile.createTempFile("svgtest", ".pptx"); - System.out.println(tmpFile); - try (FileOutputStream fos = new FileOutputStream(tmpFile)) { - ppt.write(fos); - } - - String[] args = { - "-format", "png", // png,gif,jpg or null for test - "-slide", "-1", // -1 for all - "-outdir", tmpFile.getParentFile().getCanonicalPath(), - "-quiet", - tmpFile.getAbsolutePath() - }; - PPTX2PNG.main(args); - } catch (IIOException ignore) { - // Ignore all ImageIO related exceptions like "Can't create output stream!" - // which fail often in maven builds because of missing/wrong temp directory - } catch (NoClassDefFoundError ignore) { - assumeFalse(true, "Batik doesn't work on th module-path"); - } - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShape.java deleted file mode 100644 index 116eddac13..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShape.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType; - -class TestXSLFShape { - - @Test - void testReadTextShapes() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - List<XSLFSlide> slides = ppt.getSlides(); - - XSLFSlide slide1 = slides.get(0); - List<XSLFShape> shapes1 = slide1.getShapes(); - assertEquals(7, shapes1.size()); - assertEquals("TextBox 3", shapes1.get(0).getShapeName()); - XSLFAutoShape sh0 = (XSLFAutoShape) shapes1.get(0); - assertEquals("Learning PPTX", sh0.getText()); - List<XSLFTextParagraph> paragraphs0 = sh0.getTextParagraphs(); - assertEquals(1, paragraphs0.size()); - XSLFTextParagraph p0 = paragraphs0.get(0); - assertEquals("Learning PPTX", p0.getText()); - assertEquals(1, p0.getTextRuns().size()); - XSLFTextRun r0 = p0.getTextRuns().get(0); - assertEquals("Learning PPTX", r0.getRawText()); - - XSLFSlide slide2 = slides.get(1); - List<XSLFShape> shapes2 = slide2.getShapes(); - assertTrue(shapes2.get(0) instanceof XSLFAutoShape); - assertEquals("PPTX Title", ((XSLFAutoShape) shapes2.get(0)).getText()); - XSLFAutoShape sh1 = (XSLFAutoShape) shapes2.get(0); - List<XSLFTextParagraph> paragraphs1 = sh1.getTextParagraphs(); - assertEquals(1, paragraphs1.size()); - XSLFTextParagraph p1 = paragraphs1.get(0); - assertEquals("PPTX Title", p1.getText()); - List<XSLFTextRun> r2 = paragraphs1.get(0).getTextRuns(); - assertEquals(2, r2.size()); - assertEquals("PPTX ", r2.get(0).getRawText()); - assertEquals("Title", r2.get(1).getRawText()); - // Title is underlined - assertEquals(STTextUnderlineType.SNG, r2.get(1).getRPr(false).getU()); - - - assertTrue(shapes2.get(1) instanceof XSLFAutoShape); - assertEquals("Subtitle\nAnd second line", ((XSLFAutoShape) shapes2.get(1)).getText()); - XSLFAutoShape sh2 = (XSLFAutoShape) shapes2.get(1); - List<XSLFTextParagraph> paragraphs2 = sh2.getTextParagraphs(); - assertEquals(2, paragraphs2.size()); - assertEquals("Subtitle", paragraphs2.get(0).getText()); - assertEquals("And second line", paragraphs2.get(1).getText()); - - assertEquals(1, paragraphs2.get(0).getTextRuns().size()); - assertEquals(1, paragraphs2.get(1).getTextRuns().size()); - - assertEquals("Subtitle", paragraphs2.get(0).getTextRuns().get(0).getRawText()); - assertTrue(paragraphs2.get(0).getTextRuns().get(0).getRPr(false).getB()); - assertEquals("And second line", paragraphs2.get(1).getTextRuns().get(0).getRawText()); - - ppt.close(); - } - - @Test - void testProblemFile() throws IOException { - try (XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("ececapstonespring2012.pptx")) { - List<XSLFSlide> slides = ppt.getSlides(); - assertEquals(24, slides.size()); - } - } - - @Test - void testCreateShapes() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - assertTrue(slide.getShapes().isEmpty()); - - XSLFTextBox textBox = slide.createTextBox(); - - assertEquals(1, slide.getShapes().size()); - assertSame(textBox, slide.getShapes().get(0)); - - assertEquals("", textBox.getText()); - // FIXME: is this correct? Should it be starting out with 0 or 1 text paragraphs? - assertEquals(1, textBox.getTextParagraphs().size()); - textBox.addNewTextParagraph().addNewTextRun().setText("Apache"); - textBox.addNewTextParagraph().addNewTextRun().setText("POI"); - assertEquals("Apache\nPOI", textBox.getText()); - assertEquals(3, textBox.getTextParagraphs().size()); - - ppt.close(); - } - -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShapeContainer.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShapeContainer.java deleted file mode 100644 index 2f5b57161f..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShapeContainer.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -/** - * test common operations on containers of shapes (sheets and groups of shapes) - */ -class TestXSLFShapeContainer { - - void verifyContainer(XSLFShapeContainer container) { - container.clear(); - assertEquals(0, container.getShapes().size()); - - container.createGroup(); - assertEquals(1, container.getShapes().size()); - - container.createTextBox(); - assertEquals(2, container.getShapes().size()); - - container.createAutoShape(); - assertEquals(3, container.getShapes().size()); - - container.createConnector(); - assertEquals(4, container.getShapes().size()); - - container.clear(); - assertEquals(0, container.getShapes().size()); - } - - @Test - void testSheet() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSheet sheet = ppt.createSlide(); - verifyContainer(sheet); - - - XSLFGroupShape group = sheet.createGroup(); - verifyContainer(group); - - ppt.close(); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSheet.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSheet.java deleted file mode 100644 index cd467554e3..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSheet.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * test common properties for sheets (slides, masters, layouts, etc.) - * - * @author Yegor Kozlov - */ -class TestXSLFSheet { - - @Test - void testCreateShapes() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - assertTrue(slide.getShapes().isEmpty()); - - XSLFSimpleShape shape1 = slide.createAutoShape(); - assertEquals(1, slide.getShapes().size()); - assertSame(shape1, slide.getShapes().get(0)); - - XSLFTextBox shape2 = slide.createTextBox(); - assertEquals(2, slide.getShapes().size()); - assertSame(shape1, slide.getShapes().get(0)); - assertSame(shape2, slide.getShapes().get(1)); - - XSLFConnectorShape shape3 = slide.createConnector(); - assertEquals(3, slide.getShapes().size()); - assertSame(shape1, slide.getShapes().get(0)); - assertSame(shape2, slide.getShapes().get(1)); - assertSame(shape3, slide.getShapes().get(2)); - - XSLFGroupShape shape4 = slide.createGroup(); - assertEquals(4, slide.getShapes().size()); - assertSame(shape1, slide.getShapes().get(0)); - assertSame(shape2, slide.getShapes().get(1)); - assertSame(shape3, slide.getShapes().get(2)); - assertSame(shape4, slide.getShapes().get(3)); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt); - slide = ppt2.getSlides().get(0); - List<XSLFShape> shapes = slide.getShapes(); - assertEquals(4, shapes.size()); - - assertTrue(shapes.get(0) instanceof XSLFAutoShape); - assertTrue(shapes.get(1) instanceof XSLFTextBox); - assertTrue(shapes.get(2) instanceof XSLFConnectorShape); - assertTrue(shapes.get(3) instanceof XSLFGroupShape); - - ppt.close(); - ppt2.close(); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSimpleShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSimpleShape.java deleted file mode 100644 index c25e822538..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSimpleShape.java +++ /dev/null @@ -1,334 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.awt.Color; -import java.io.File; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.StrokeStyle.LineCap; -import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.apache.poi.util.Units; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.apache.poi.xslf.util.PPTX2PNG; -import org.apache.xmlbeans.XmlObject; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTEffectStyleItem; -import org.openxmlformats.schemas.drawingml.x2006.main.CTEffectStyleList; -import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSchemeColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTStyleMatrix; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineCap; -import org.openxmlformats.schemas.drawingml.x2006.main.STPresetLineDashVal; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; - -class TestXSLFSimpleShape { - - @Test - void testLineStyles() throws IOException { - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - - XSLFSimpleShape shape = slide.createAutoShape(); - assertEquals(1, slide.getShapes().size()); - // line properties are not set by default - assertFalse(getSpPr(shape).isSetLn()); - - assertEquals(0., shape.getLineWidth(), 0); - assertNull(shape.getLineColor()); - assertNull(shape.getLineDash()); - assertNull(shape.getLineCap()); - - shape.setLineWidth(0); - shape.setLineColor(null); - shape.setLineDash(null); - shape.setLineCap(null); - - assertTrue(getSpPr(shape).isSetLn()); - assertTrue(getSpPr(shape).getLn().isSetNoFill()); - - // line width - shape.setLineWidth(1.0); - assertEquals(1.0, shape.getLineWidth(), 0); - assertEquals(Units.EMU_PER_POINT, getSpPr(shape).getLn().getW()); - shape.setLineWidth(5.5); - assertEquals(5.5, shape.getLineWidth(), 0); - assertEquals(Units.toEMU(5.5), getSpPr(shape).getLn().getW()); - shape.setLineWidth(0.0); - // setting line width to zero unsets the W attribute - assertFalse(getSpPr(shape).getLn().isSetW()); - - // line cap - shape.setLineCap(LineCap.FLAT); - assertEquals(LineCap.FLAT, shape.getLineCap()); - assertEquals(STLineCap.FLAT, getSpPr(shape).getLn().getCap()); - shape.setLineCap(LineCap.SQUARE); - assertEquals(LineCap.SQUARE, shape.getLineCap()); - assertEquals(STLineCap.SQ, getSpPr(shape).getLn().getCap()); - shape.setLineCap(LineCap.ROUND); - assertEquals(LineCap.ROUND, shape.getLineCap()); - assertEquals(STLineCap.RND, getSpPr(shape).getLn().getCap()); - shape.setLineCap(null); - // setting cap to null unsets the Cap attribute - assertFalse(getSpPr(shape).getLn().isSetCap()); - - // line dash - shape.setLineDash(LineDash.SOLID); - assertEquals(LineDash.SOLID, shape.getLineDash()); - assertEquals(STPresetLineDashVal.SOLID, getSpPr(shape).getLn().getPrstDash().getVal()); - shape.setLineDash(LineDash.DASH_DOT); - assertEquals(LineDash.DASH_DOT, shape.getLineDash()); - assertEquals(STPresetLineDashVal.DASH_DOT, getSpPr(shape).getLn().getPrstDash().getVal()); - shape.setLineDash(LineDash.LG_DASH_DOT); - assertEquals(LineDash.LG_DASH_DOT, shape.getLineDash()); - assertEquals(STPresetLineDashVal.LG_DASH_DOT, getSpPr(shape).getLn().getPrstDash().getVal()); - shape.setLineDash(null); - // setting dash width to null unsets the Dash element - assertFalse(getSpPr(shape).getLn().isSetPrstDash()); - - // line color - assertFalse(getSpPr(shape).getLn().isSetSolidFill()); - shape.setLineColor(Color.RED); - assertEquals(Color.RED, shape.getLineColor()); - assertTrue(getSpPr(shape).getLn().isSetSolidFill()); - shape.setLineColor(Color.BLUE); - assertEquals(Color.BLUE, shape.getLineColor()); - assertTrue(getSpPr(shape).getLn().isSetSolidFill()); - shape.setLineColor(null); - assertNull(shape.getLineColor()); - // setting dash width to null unsets the SolidFill element - assertFalse(getSpPr(shape).getLn().isSetSolidFill()); - - XSLFSimpleShape ln2 = slide.createAutoShape(); - ln2.setLineDash(LineDash.DOT); - assertEquals(LineDash.DOT, ln2.getLineDash()); - ln2.setLineWidth(0.); - assertEquals(0., ln2.getLineWidth(), 0); - - XSLFSimpleShape ln3 = slide.createAutoShape(); - ln3.setLineWidth(1.); - assertEquals(1., ln3.getLineWidth(), 0); - ln3.setLineDash(null); - assertNull(ln3.getLineDash()); - ln3.setLineCap(null); - assertNull(ln3.getLineDash()); - } - } - - @Test - void testFill() throws IOException { - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - - XSLFAutoShape shape = slide.createAutoShape(); - // line properties are not set by default - assertFalse(getSpPr(shape).isSetSolidFill()); - - assertNull(shape.getFillColor()); - shape.setFillColor(null); - assertNull(shape.getFillColor()); - assertFalse(getSpPr(shape).isSetSolidFill()); - - shape.setFillColor(Color.RED); - assertEquals(Color.RED, shape.getFillColor()); - shape.setFillColor(Color.DARK_GRAY); - assertEquals(Color.DARK_GRAY, shape.getFillColor()); - assertTrue(getSpPr(shape).isSetSolidFill()); - - shape.setFillColor(null); - assertNull(shape.getFillColor()); - assertFalse(getSpPr(shape).isSetSolidFill()); - } - } - - @Test - void testDefaultProperties() throws IOException { - try (XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx")) { - XSLFSlide slide6 = ppt.getSlides().get(5); - List<XSLFShape> shapes = slide6.getShapes(); - for (XSLFShape xs : shapes) { - XSLFSimpleShape s = (XSLFSimpleShape) xs; - // all shapes have a theme color="accent1" - assertEquals("accent1", s.getSpStyle().getFillRef().getSchemeClr().getVal().toString()); - assertEquals(2.0, s.getLineWidth(), 0); - assertEquals(LineCap.FLAT, s.getLineCap()); - assertEquals(new Color(79, 129, 189), s.getLineColor()); - } - - XSLFSimpleShape s0 = (XSLFSimpleShape) shapes.get(0); - // fill is not set - assertNull(getSpPr(s0).getSolidFill()); - //assertEquals(slide6.getTheme().getColor("accent1").getColor(), s0.getFillColor()); - assertEquals(new Color(79, 129, 189), s0.getFillColor()); - - // lighter 80% - XSLFSimpleShape s1 = (XSLFSimpleShape) shapes.get(1); - CTSchemeColor ref1 = getSpPr(s1).getSolidFill().getSchemeClr(); - assertEquals(1, ref1.sizeOfLumModArray()); - assertEquals(1, ref1.sizeOfLumOffArray()); - assertEquals(20000, ref1.getLumModArray(0).getVal()); - assertEquals(80000, ref1.getLumOffArray(0).getVal()); - assertEquals("accent1", ref1.getVal().toString()); - assertEquals(new Color(220, 230, 242), s1.getFillColor()); - - // lighter 60% - XSLFSimpleShape s2 = (XSLFSimpleShape) shapes.get(2); - CTSchemeColor ref2 = getSpPr(s2).getSolidFill().getSchemeClr(); - assertEquals(1, ref2.sizeOfLumModArray()); - assertEquals(1, ref2.sizeOfLumOffArray()); - assertEquals(40000, ref2.getLumModArray(0).getVal()); - assertEquals(60000, ref2.getLumOffArray(0).getVal()); - assertEquals("accent1", ref2.getVal().toString()); - assertEquals(new Color(185, 205, 229), s2.getFillColor()); - - // lighter 40% - XSLFSimpleShape s3 = (XSLFSimpleShape) shapes.get(3); - CTSchemeColor ref3 = getSpPr(s3).getSolidFill().getSchemeClr(); - assertEquals(1, ref3.sizeOfLumModArray()); - assertEquals(1, ref3.sizeOfLumOffArray()); - assertEquals(60000, ref3.getLumModArray(0).getVal()); - assertEquals(40000, ref3.getLumOffArray(0).getVal()); - assertEquals("accent1", ref3.getVal().toString()); - assertEquals(new Color(149, 179, 215), s3.getFillColor()); - - // darker 25% - XSLFSimpleShape s4 = (XSLFSimpleShape) shapes.get(4); - CTSchemeColor ref4 = getSpPr(s4).getSolidFill().getSchemeClr(); - assertEquals(1, ref4.sizeOfLumModArray()); - assertEquals(0, ref4.sizeOfLumOffArray()); - assertEquals(75000, ref4.getLumModArray(0).getVal()); - assertEquals("accent1", ref3.getVal().toString()); - assertEquals(new Color(55, 96, 146), s4.getFillColor()); - - XSLFSimpleShape s5 = (XSLFSimpleShape) shapes.get(5); - CTSchemeColor ref5 = getSpPr(s5).getSolidFill().getSchemeClr(); - assertEquals(1, ref5.sizeOfLumModArray()); - assertEquals(0, ref5.sizeOfLumOffArray()); - assertEquals(50000, ref5.getLumModArray(0).getVal()); - assertEquals("accent1", ref5.getVal().toString()); - assertEquals(new Color(37, 64, 97), s5.getFillColor()); - } - } - - @Test - void testAnchor() throws IOException { - try (XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx")) { - List<XSLFSlide> slide = ppt.getSlides(); - - XSLFSlide slide2 = slide.get(1); - XSLFSlideLayout layout2 = slide2.getSlideLayout(); - List<XSLFShape> shapes2 = slide2.getShapes(); - XSLFTextShape sh1 = (XSLFTextShape) shapes2.get(0); - assertEquals(Placeholder.CENTERED_TITLE, sh1.getTextType()); - assertEquals("PPTX Title", sh1.getText()); - assertFalse(getSpPr(sh1).isSetXfrm()); // xfrm is not set, the query is delegated to the slide layout - assertEquals(sh1.getAnchor(), layout2.getTextShapeByType(Placeholder.CENTERED_TITLE).getAnchor()); - - XSLFTextShape sh2 = (XSLFTextShape) shapes2.get(1); - assertEquals("Subtitle\nAnd second line", sh2.getText()); - assertEquals(Placeholder.SUBTITLE, sh2.getTextType()); - assertFalse(getSpPr(sh2).isSetXfrm()); // xfrm is not set, the query is delegated to the slide layout - assertEquals(sh2.getAnchor(), layout2.getTextShapeByType(Placeholder.SUBTITLE).getAnchor()); - - XSLFSlide slide5 = slide.get(4); - XSLFSlideLayout layout5 = slide5.getSlideLayout(); - XSLFTextShape shTitle = slide5.getTextShapeByType(Placeholder.TITLE); - assertEquals("Hyperlinks", shTitle.getText()); - // xfrm is not set, the query is delegated to the slide layout - assertFalse(getSpPr(shTitle).isSetXfrm()); - // xfrm is not set, the query is delegated to the slide master - assertFalse(getSpPr(layout5.getTextShapeByType(Placeholder.TITLE)).isSetXfrm()); - assertTrue(getSpPr(layout5.getSlideMaster().getTextShapeByType(Placeholder.TITLE)).isSetXfrm()); - assertEquals(shTitle.getAnchor(), layout5.getSlideMaster().getTextShapeByType(Placeholder.TITLE).getAnchor()); - } - } - - @SuppressWarnings({"unused", "deprecation"}) - @Test - void testShadowEffects() throws IOException{ - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - CTStyleMatrix styleMatrix = slide.getTheme().getXmlObject().getThemeElements().getFmtScheme(); - CTEffectStyleList lst = styleMatrix.getEffectStyleLst(); - assertNotNull(lst); - for (CTEffectStyleItem ef : lst.getEffectStyleArray()) { - CTOuterShadowEffect obj = ef.getEffectLst().getOuterShdw(); - } - } - } - - @Test - void testValidGeometry() throws Exception { - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - - XSLFSimpleShape shape = slide.createAutoShape(); - CTShapeProperties spPr = getSpPr(shape); - - CTPresetGeometry2D prstGeom = CTPresetGeometry2D.Factory.newInstance(); - prstGeom.setPrst(STShapeType.Enum.forInt(1)); - - assertNotNull(prstGeom.getPrst()); - assertNotNull(prstGeom.getPrst().toString()); - assertNotNull(spPr.getPrstGeom()); - spPr.setPrstGeom(prstGeom); - assertNotNull(spPr.getPrstGeom().getPrst()); - assertNotNull(spPr.getPrstGeom().getPrst().toString()); - - assertNotNull(shape.getGeometry()); - } - } - - @Test - void testArrayStoreException() throws Exception { - File tmpDir = new File("build/tmp/"); - - // fix maven build errors - if (!tmpDir.exists()) { - assertTrue(tmpDir.mkdirs()); - } - - File file = POIDataSamples.getSlideShowInstance().getFile("aascu.org_workarea_downloadasset.aspx_id=5864.pptx"); - String[] args = { - "-format", "null", // png,gif,jpg,svg or null for test - "-slide", "-1", // -1 for all - "-outdir", tmpDir.getCanonicalPath(), - "-quiet", - "-fixside", "long", - "-scale", "800", - file.getAbsolutePath() - }; - PPTX2PNG.main(args); - } - - static CTShapeProperties getSpPr(XSLFShape shape) { - XmlObject xo = shape.getShapeProperties(); - assertTrue(xo instanceof CTShapeProperties); - return (CTShapeProperties)xo; - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlide.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlide.java deleted file mode 100644 index 3b83355369..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlide.java +++ /dev/null @@ -1,214 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.awt.Color; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * @author Yegor Kozlov - */ -class TestXSLFSlide { - - @Test - void testReadShapes() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - List<XSLFSlide> slides = ppt.getSlides(); - - XSLFSlide slide1 = slides.get(0); - List<XSLFShape> shapes1 = slide1.getShapes(); - assertEquals(7, shapes1.size()); - assertEquals("TextBox 3", shapes1.get(0).getShapeName()); - assertTrue(shapes1.get(0) instanceof XSLFTextBox); - XSLFAutoShape sh0 = (XSLFAutoShape)shapes1.get(0); - assertEquals("Learning PPTX", sh0.getText()); - - - assertEquals("Straight Connector 5", shapes1.get(1).getShapeName()); - assertTrue(shapes1.get(1) instanceof XSLFConnectorShape); - - assertEquals("Freeform 6", shapes1.get(2).getShapeName()); - assertTrue(shapes1.get(2) instanceof XSLFFreeformShape); - XSLFAutoShape sh2 = (XSLFAutoShape)shapes1.get(2); - assertEquals("Cloud", sh2.getText()); - - assertEquals("Picture 1", shapes1.get(3).getShapeName()); - assertTrue(shapes1.get(3) instanceof XSLFPictureShape); - - assertEquals("Table 2", shapes1.get(4).getShapeName()); - assertTrue(shapes1.get(4) instanceof XSLFGraphicFrame); - - assertEquals("Straight Arrow Connector 7", shapes1.get(5).getShapeName()); - assertTrue(shapes1.get(5) instanceof XSLFConnectorShape); - - assertEquals("Elbow Connector 9", shapes1.get(6).getShapeName()); - assertTrue(shapes1.get(6) instanceof XSLFConnectorShape); - - // titles on slide2 - XSLFSlide slide2 = slides.get(1); - List<XSLFShape> shapes2 = slide2.getShapes(); - assertEquals(2, shapes2.size()); - assertTrue(shapes2.get(0) instanceof XSLFAutoShape); - assertEquals("PPTX Title", ((XSLFAutoShape)shapes2.get(0)).getText()); - assertTrue(shapes2.get(1) instanceof XSLFAutoShape); - assertEquals("Subtitle\nAnd second line", ((XSLFAutoShape)shapes2.get(1)).getText()); - - // group shape on slide3 - XSLFSlide slide3 = slides.get(2); - List<XSLFShape> shapes3 = slide3.getShapes(); - assertEquals(1, shapes3.size()); - assertTrue(shapes3.get(0) instanceof XSLFGroupShape); - List<XSLFShape> groupShapes = ((XSLFGroupShape)shapes3.get(0)).getShapes(); - assertEquals(3, groupShapes.size()); - assertTrue(groupShapes.get(0) instanceof XSLFAutoShape); - assertEquals("Rectangle 1", groupShapes.get(0).getShapeName()); - - assertTrue(groupShapes.get(1) instanceof XSLFAutoShape); - assertEquals("Oval 2", groupShapes.get(1).getShapeName()); - - assertTrue(groupShapes.get(2) instanceof XSLFAutoShape); - assertEquals("Right Arrow 3", groupShapes.get(2).getShapeName()); - - XSLFSlide slide4 = slides.get(3); - List<XSLFShape> shapes4 = slide4.getShapes(); - assertEquals(1, shapes4.size()); - assertTrue(shapes4.get(0) instanceof XSLFTable); - XSLFTable tbl = (XSLFTable)shapes4.get(0); - assertEquals(3, tbl.getNumberOfColumns()); - assertEquals(6, tbl.getNumberOfRows()); - - ppt.close(); - } - - @Test - void testCreateSlide() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - assertEquals(0, ppt.getSlides().size()); - - XSLFSlide slide = ppt.createSlide(); - assertTrue(slide.getFollowMasterGraphics()); - slide.setFollowMasterGraphics(false); - assertFalse(slide.getFollowMasterGraphics()); - slide.setFollowMasterGraphics(true); - assertTrue(slide.getFollowMasterGraphics()); - - ppt.close(); - } - - @Test - void testImportContent() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - - XMLSlideShow src = XSLFTestDataSamples.openSampleDocument("themes.pptx"); - - // create a blank slide and import content from the 4th slide of themes.pptx - XSLFSlide slide1 = ppt.createSlide().importContent(src.getSlides().get(3)); - List<XSLFShape> shapes1 = slide1.getShapes(); - assertEquals(2, shapes1.size()); - - XSLFTextShape sh1 = (XSLFTextShape)shapes1.get(0); - assertEquals("Austin Theme", sh1.getText()); - XSLFTextRun r1 = sh1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Century Gothic", r1.getFontFamily()); - assertEquals(40.0, r1.getFontSize(), 0); - assertTrue(r1.isBold()); - assertTrue(r1.isItalic()); - assertEquals(new Color(148, 198, 0), getColor(r1.getFontColor())); - assertNull(sh1.getFillColor()); - assertNull(sh1.getLineColor()); - - XSLFTextShape sh2 = (XSLFTextShape)shapes1.get(1); - assertEquals( - "Text in a autoshape is white\n" + - "Fill: RGB(148, 198,0)", sh2.getText()); - XSLFTextRun r2 = sh2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Century Gothic", r2.getFontFamily()); - assertEquals(18.0, r2.getFontSize(), 0); - assertFalse(r2.isBold()); - assertFalse(r2.isItalic()); - assertEquals(Color.white, getColor(r2.getFontColor())); - assertEquals(new Color(148, 198, 0), sh2.getFillColor()); - assertEquals(new Color(148, 198, 0), sh2.getLineColor()); // slightly different from PowerPoint! - - // the 5th slide has a picture and a texture fill - XSLFSlide slide2 = ppt.createSlide().importContent(src.getSlides().get(4)); - List<XSLFShape> shapes2 = slide2.getShapes(); - assertEquals(2, shapes2.size()); - - XSLFTextShape sh3 = (XSLFTextShape)shapes2.get(0); - assertEquals("This slide overrides master background with a texture fill", sh3.getText()); - XSLFTextRun r3 = sh3.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Century Gothic", r3.getFontFamily()); - //assertEquals(32.4.0, r3.getFontSize()); - assertTrue(r3.isBold()); - assertTrue(r3.isItalic()); - assertEquals(new Color(148, 198, 0), getColor(r3.getFontColor())); - assertNull(sh3.getFillColor()); - assertNull(sh3.getLineColor()); - - XSLFPictureShape sh4 = (XSLFPictureShape)shapes2.get(1); - XSLFPictureShape srcPic = (XSLFPictureShape)src.getSlides().get(4).getShapes().get(1); - assertArrayEquals(sh4.getPictureData().getData(), srcPic.getPictureData().getData()); - - ppt.close(); - } - - @Test - void testMergeSlides() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - String[] pptx = {"shapes.pptx", "themes.pptx", "layouts.pptx", "backgrounds.pptx"}; - - for(String arg : pptx){ - XMLSlideShow src = XSLFTestDataSamples.openSampleDocument(arg); - - for(XSLFSlide srcSlide : src.getSlides()){ - ppt.createSlide().importContent(srcSlide); - } - } - assertEquals(30, ppt.getSlides().size()); - - ppt.close(); - } - - @Test - void testCreateChart() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - XSLFChart chart = ppt.createChart(); - assertNotNull(chart); - - slide.addChart(chart); - assertEquals(XSLFRelation.CHART.getContentType(), chart.getPackagePart().getContentType()); - - String partName = slide.getRelationPartById("rId2").getDocumentPart().getPackagePart().getPartName().getName(); - assertEquals(partName, chart.getPackagePart().getPartName().getName()); - - ppt.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShow.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShow.java deleted file mode 100644 index 7e47a24b0a..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShow.java +++ /dev/null @@ -1,149 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -import java.awt.Dimension; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ooxml.POIXMLDocumentPart; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * @author Yegor Kozlov - */ -class TestXSLFSlideShow { - @Test - void testCreateSlide() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - assertEquals(0, ppt.getSlides().size()); - - XSLFSlide slide1 = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - assertSame(slide1, ppt.getSlides().get(0)); - - List<POIXMLDocumentPart> rels = slide1.getRelations(); - assertEquals(1, rels.size()); - assertEquals(slide1.getSlideMaster().getLayout(SlideLayout.BLANK), rels.get(0)); - - XSLFSlide slide2 = ppt.createSlide(); - assertEquals(2, ppt.getSlides().size()); - assertSame(slide2, ppt.getSlides().get(1)); - - ppt.setSlideOrder(slide2, 0); - assertSame(slide2, ppt.getSlides().get(0)); - assertSame(slide1, ppt.getSlides().get(1)); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt); - assertEquals(2, ppt2.getSlides().size()); - rels = ppt2.getSlides().get(0).getRelations(); - - ppt2.close(); - ppt.close(); - } - - @Test - void testRemoveSlide() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - assertEquals(0, ppt.getSlides().size()); - - XSLFSlide slide1 = ppt.createSlide(); - XSLFSlide slide2 = ppt.createSlide(); - - assertEquals(2, ppt.getSlides().size()); - assertSame(slide1, ppt.getSlides().get(0)); - assertSame(slide2, ppt.getSlides().get(1)); - - XSLFSlide removedSlide = ppt.removeSlide(0); - assertSame(slide1, removedSlide); - - assertEquals(1, ppt.getSlides().size()); - assertSame(slide2, ppt.getSlides().get(0)); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt); - assertEquals(1, ppt2.getSlides().size()); - - ppt2.close(); - ppt.close(); - } - - @Test - void testDimension() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - Dimension sz = ppt.getPageSize(); - assertEquals(720, sz.width); - assertEquals(540, sz.height); - ppt.setPageSize(new Dimension(792, 612)); - sz = ppt.getPageSize(); - assertEquals(792, sz.width); - assertEquals(612, sz.height); - ppt.close(); - } - - @Test - void testSlideMasters() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - List<XSLFSlideMaster> masters = ppt.getSlideMasters(); - assertEquals(1, masters.size()); - - XSLFSlide slide = ppt.createSlide(); - assertSame(masters.get(0), slide.getSlideMaster()); - ppt.close(); - } - - @Test - void testSlideLayout() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - List<XSLFSlideMaster> masters = ppt.getSlideMasters(); - assertEquals(1, masters.size()); - - XSLFSlide slide = ppt.createSlide(); - XSLFSlideLayout layout = slide.getSlideLayout(); - assertNotNull(layout); - - assertSame(masters.get(0), layout.getSlideMaster()); - ppt.close(); - } - - @Test - void testSlideLayoutNames() throws IOException { - final String[] names = { - "Blank", "Title Only", "Section Header", "Picture with Caption", "Title and Content" - , "Title Slide", "Title and Vertical Text", "Vertical Title and Text", "Comparison" - , "Two Content", "Content with Caption" - }; - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("layouts.pptx"); - for (String name : names) { - assertNotNull(ppt.findLayout(name)); - } - final SlideLayout[] layTypes = { - SlideLayout.BLANK, SlideLayout.TITLE_ONLY, SlideLayout.SECTION_HEADER - , SlideLayout.PIC_TX, SlideLayout.TITLE_AND_CONTENT, SlideLayout.TITLE - , SlideLayout.VERT_TX, SlideLayout.VERT_TITLE_AND_TX, SlideLayout.TWO_TX_TWO_OBJ - , SlideLayout.TWO_OBJ, SlideLayout.OBJ_TX - }; - for (SlideLayout sl : layTypes){ - assertNotNull(ppt.getSlideMasters().get(0).getLayout(sl)); - } - ppt.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java deleted file mode 100644 index 89436fcbf0..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.GeneralSecurityException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.Encryptor; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.sl.usermodel.BaseTestSlideShowFactory; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.Test; - -public final class TestXSLFSlideShowFactory extends BaseTestSlideShowFactory { - private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - private static final String filename = "SampleShow.pptx"; - private static final String password = "opensesame"; - private static final String removeExpectedExceptionMsg = - "This functionality this unit test is trying to test is now passing. " + - "The unit test needs to be updated by deleting the expected exception code. Status and close any related bugs."; - - @Test - void testFactoryFromFile() { - // Remove thrown.* when bug 58779 is resolved - // In the mean time, this function will modify SampleShow.pptx on disk. - AssertionError ex = assertThrows(AssertionError.class, () -> testFactoryFromFile(filename), - "Bug 58779: " + removeExpectedExceptionMsg); - assertTrue(ex.getMessage().contains("SampleShow.pptx sample file was modified as a result of closing the slideshow")); - } - - @Test - void testFactoryFromStream() throws Exception { - testFactoryFromStream(filename); - } - - @Test - void testFactoryFromNative() { - // Remove thrown.* when unit test for XSLF SlideShowFactory.create(OPCPackage) is implemented - UnsupportedOperationException ex = assertThrows(UnsupportedOperationException.class, - () -> testFactoryFromNative(filename), removeExpectedExceptionMsg - ); - assertEquals("Test not implemented", ex.getMessage()); - } - - @Test - void testFactoryFromProtectedFile() throws Exception { - File pFile = createProtected(); - testFactoryFromProtectedFile(pFile.getAbsolutePath(), password); - } - - @Test - void testFactoryFromProtectedStream() throws Exception { - File pFile = createProtected(); - testFactoryFromProtectedStream(pFile.getAbsolutePath(), password); - } - - @Test - void testFactoryFromProtectedNative() throws Exception { - File pFile = createProtected(); - testFactoryFromProtectedNative(pFile.getAbsolutePath(), password); - } - - private static File createProtected() throws IOException, GeneralSecurityException { - try (POIFSFileSystem fs = new POIFSFileSystem()) { - EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); - Encryptor enc = info.getEncryptor(); - enc.confirmPassword(password); - try (InputStream fis = _slTests.openResourceAsStream(filename); - OutputStream os = enc.getDataStream(fs)) { - IOUtils.copy(fis, os); - } - - File tf = TempFile.createTempFile("test-xslf-slidefactory", ".pptx"); - try (FileOutputStream fos = new FileOutputStream(tf)) { - fs.writeFilesystem(fos); - } - return tf; - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTable.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTable.java deleted file mode 100644 index c36035244c..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTable.java +++ /dev/null @@ -1,366 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.List; -import java.util.Random; - -import org.apache.poi.sl.draw.DrawTableShape; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.StrokeStyle; -import org.apache.poi.sl.usermodel.TableCell.BorderEdge; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.util.TempFile; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.apache.poi.xslf.util.PPTX2PNG; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame; - -class TestXSLFTable { - - @Test - void testResize() throws Exception { - String[][] data = getDummyData(20); - final int maxHeight = 400; - - XMLSlideShow ppt = new XMLSlideShow(); - int rowIdx=1; - - XSLFSlide slide = ppt.createSlide(); - // a red bordered box in the background, to show/verify the table dimensions - XSLFAutoShape as = slide.createAutoShape(); - as.setShapeType(ShapeType.RECT); - as.setStrokeStyle(Color.RED, 2., StrokeStyle.LineDash.LG_DASH); - - XSLFTable tab = slide.createTable(1, data[0].length); - tab.setAnchor(new Rectangle2D.Double(50,50,0,0)); - tab.setColumnWidth(0, 60); - tab.setColumnWidth(1, 60); - tab.setColumnWidth(2, 60); - - tab.insertColumn(0); - assertEquals(tab.getColumnWidth(1), tab.getColumnWidth(0), 0.00001); - assertNotNull(tab.getCell(0, 0).getTextBody()); - tab.addColumn(); - XSLFTableCell cell = tab.getCell(0, data[0].length + 1); - assertEquals(1, cell.getTextBody().getParagraphs().size()); - assertEquals("", cell.getTextBody().getParagraph(0).getText()); - assertEquals(tab.getColumnWidth(tab.getNumberOfColumns() - 2), tab.getColumnWidth(tab.getNumberOfColumns() - 1), 0.00001); - assertNotNull(tab.getCell(0, tab.getNumberOfColumns() - 1).getTextBody()); - tab.removeColumn(0); - tab.removeColumn(tab.getNumberOfColumns() - 1); - assertEquals(data[0].length, tab.getNumberOfColumns()); - - int startRow = rowIdx-1; - - XSLFTableRow row = tab.getRows().get(0); - for (int colIdx=0; colIdx<data[0].length; colIdx++) { - XSLFTextRun tr = row.getCells().get(colIdx).setText(data[0][colIdx]); - tr.setFontSize(20.); - tr.setFontFamily("Arial"); - } - - while (rowIdx<data.length) { - row = tab.addRow(); - for (int col=0; col<data[rowIdx].length; col++) { - XSLFTextRun tr = row.addCell().setText(data[rowIdx][col]); - tr.setFontSize(15.); - tr.setFontFamily("Arial"); - } - row = tab.insertRow(rowIdx); - for (int col=0; col<data[rowIdx].length; col++) { - XSLFTextRun tr = tab - .getCell(rowIdx, col) - .setText(data[rowIdx][col]); - tr.setFontSize(12.); - tr.setFontFamily("Arial"); - } - tab.updateCellAnchor(); - if (tab.getAnchor().getHeight() > maxHeight) { - tab.removeRow(rowIdx-startRow); - break; - } - rowIdx += 2; - } - - as.setAnchor(tab.getAnchor()); - - File fileOut = TempFile.createTempFile("tabtest", ".pptx"); - try (FileOutputStream fos = new FileOutputStream(fileOut)) { - ppt.write(fos); - } - - String[] args = { - "-format", "null", // png,gif,jpg or null for test - "-slide", "-1", // -1 for all - "-outdir", fileOut.getParentFile().getCanonicalPath(), - "-quiet", - fileOut.getAbsolutePath() - }; - PPTX2PNG.main(args); - } - - private static String[][] getDummyData(int rows) { - String[] header = { "Row#", "ID", "Name", "Description", "Price", "Percent", "Current Value" }; - String[][] data = new String[rows+1][header.length]; - System.arraycopy(header, 0, data[0], 0, header.length); - - String[] names = { "car", "rubber duckie", "phone", "gadget" }; - String[] desc = { "new", "used", "untouched" }; - - Random r = new Random(); - - for (int row=1; row<=rows; row++) { - String[] line = new String[header.length]; - line[0] = Integer.toString(row); - line[1] = Integer.toString(r.nextInt(1000)); - line[2] = names[r.nextInt(names.length)]; - line[3] = "The "+desc[r.nextInt(desc.length)]+" "+line[2]+" in "+(2017+row); - line[4] = "$"+r.nextInt(50000); - line[5] = r.nextInt(100)+"%"; - line[6] = "$"+r.nextInt(50000); - System.arraycopy(line, 0, data[row], 0, header.length); - } - - return data; - } - - - @Test - void testRead() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - - XSLFSlide slide = ppt.getSlides().get(3); - List<XSLFShape> shapes = slide.getShapes(); - assertEquals(1, shapes.size()); - assertTrue(shapes.get(0) instanceof XSLFTable); - XSLFTable tbl = (XSLFTable)shapes.get(0); - assertEquals(3, tbl.getNumberOfColumns()); - assertEquals(6, tbl.getNumberOfRows()); - assertNotNull(tbl.getCTTable()); - - List<XSLFTableRow> rows = tbl.getRows(); - assertEquals(6, rows.size()); - - assertEquals(90.0, tbl.getColumnWidth(0), 0); - assertEquals(240.0, tbl.getColumnWidth(1), 0); - assertEquals(150.0, tbl.getColumnWidth(2), 0); - - for(XSLFTableRow row : tbl){ - // all rows have the same height - assertEquals(29.2, row.getHeight(), 0); - } - - XSLFTableRow row0 = rows.get(0); - List<XSLFTableCell> cells0 = row0.getCells(); - assertEquals(3, cells0.size()); - assertEquals("header1", cells0.get(0).getText()); - assertEquals("header2", cells0.get(1).getText()); - assertEquals("header3", cells0.get(2).getText()); - - XSLFTableRow row1 = rows.get(1); - List<XSLFTableCell> cells1 = row1.getCells(); - assertEquals(3, cells1.size()); - assertEquals("A1", cells1.get(0).getText()); - assertEquals("B1", cells1.get(1).getText()); - assertEquals("C1", cells1.get(2).getText()); - - ppt.close(); - } - - @Test - void testCreate() throws IOException { - XMLSlideShow ppt1 = new XMLSlideShow(); - XSLFSlide slide = ppt1.createSlide(); - - XSLFTable tbl = slide.createTable(); - assertNotNull(tbl.getCTTable()); - assertNotNull(tbl.getCTTable().getTblGrid()); - assertNotNull(tbl.getCTTable().getTblPr()); - assertTrue(tbl.getXmlObject() instanceof CTGraphicalObjectFrame); - assertEquals("Table 2", tbl.getShapeName()); - assertEquals(2, tbl.getShapeId()); - assertEquals(0, tbl.getRows().size()); - assertEquals(0, tbl.getCTTable().sizeOfTrArray()); - assertEquals(0, tbl.getCTTable().getTblGrid().sizeOfGridColArray()); - - assertEquals(0, tbl.getNumberOfColumns()); - assertEquals(0, tbl.getNumberOfRows()); - - XSLFTableRow row0 = tbl.addRow(); - assertNotNull(row0.getXmlObject()); - assertEquals(1, tbl.getNumberOfRows()); - assertSame(row0, tbl.getRows().get(0)); - assertEquals(20.0, row0.getHeight(), 0); - row0.setHeight(30.0); - assertEquals(30.0, row0.getHeight(), 0); - - assertEquals(0, row0.getCells().size()); - XSLFTableCell cell0 = row0.addCell(); - assertNotNull(cell0.getXmlObject()); - // by default table cell has no borders - CTTableCell tc = (CTTableCell)cell0.getXmlObject(); - assertTrue(tc.getTcPr().getLnB().isSetNoFill()); - assertTrue(tc.getTcPr().getLnT().isSetNoFill()); - assertTrue(tc.getTcPr().getLnL().isSetNoFill()); - assertTrue(tc.getTcPr().getLnR().isSetNoFill()); - - assertSame(cell0, row0.getCells().get(0)); - assertEquals(1, tbl.getNumberOfColumns()); - assertEquals(100.0, tbl.getColumnWidth(0), 0); - cell0.addNewTextParagraph().addNewTextRun().setText("POI"); - assertEquals("POI", cell0.getText()); - - XSLFTableCell cell1 = row0.addCell(); - assertSame(cell1, row0.getCells().get(1)); - assertEquals(2, tbl.getNumberOfColumns()); - assertEquals(100.0, tbl.getColumnWidth(1), 0); - cell1.addNewTextParagraph().addNewTextRun().setText("Apache"); - assertEquals("Apache", cell1.getText()); - - for (BorderEdge edge : BorderEdge.values()) { - assertNull(cell1.getBorderWidth(edge)); - cell1.setBorderWidth(edge, 2.0); - assertEquals(2.0, cell1.getBorderWidth(edge), 0); - assertNull(cell1.getBorderColor(edge)); - cell1.setBorderColor(edge, Color.yellow); - assertEquals(Color.yellow, cell1.getBorderColor(edge)); - } - - assertEquals(VerticalAlignment.TOP, cell1.getVerticalAlignment()); - cell1.setVerticalAlignment(VerticalAlignment.MIDDLE); - assertEquals(VerticalAlignment.MIDDLE, cell1.getVerticalAlignment()); - cell1.setVerticalAlignment(null); - assertEquals(VerticalAlignment.TOP, cell1.getVerticalAlignment()); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - - slide = ppt2.getSlides().get(0); - tbl = (XSLFTable)slide.getShapes().get(0); - assertEquals(2, tbl.getNumberOfColumns()); - assertEquals(1, tbl.getNumberOfRows()); - assertEquals("POI", tbl.getCell(0, 0).getText()); - assertEquals("Apache", tbl.getCell(0, 1).getText()); - - ppt2.close(); - } - - @Test - void removeTable() throws IOException { - XMLSlideShow ss = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - XSLFSlide sl = ss.getSlides().get(0); - XSLFTable tab = (XSLFTable)sl.getShapes().get(4); - sl.removeShape(tab); - - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss); - ss.close(); - - sl = ss2.getSlides().get(0); - for (XSLFShape s : sl.getShapes()) { - assertFalse(s instanceof XSLFTable); - } - - ss2.close(); - } - - @Test - void checkTextHeight() throws IOException { - // from bug 59686 - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide sl = ppt.createSlide(); - XSLFTable tab = sl.createTable(); - tab.setAnchor(new Rectangle2D.Double(50,50,300,50)); - XSLFTableRow tr = tab.addRow(); - XSLFTableCell tc0 = tr.addCell(); - tc0.setText("bla bla bla bla"); - tab.setColumnWidth(0, 50); - - // usually text height == 88, but font rendering is plattform dependent - // so we use something more reliable - assertTrue(tc0.getTextHeight() > 50); - assertEquals(0, tc0.getLineWidth(), 0); - - ppt.close(); - } - - @Test - void checkNullPointerException() throws IOException { - String file = "au.asn.aes.www_conferences_2011_presentations_Fri_20Room4Level4_20930_20Maloney.pptx"; - try (XMLSlideShow ss = XSLFTestDataSamples.openSampleDocument(file)) { - Dimension pgsize = ss.getPageSize(); - for (Slide<?, ?> s : ss.getSlides()) { - BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = img.createGraphics(); - - // draw stuff - assertDoesNotThrow(() -> s.draw(graphics)); - - graphics.dispose(); - img.flush(); - } - } - } - - @Test - void simpleMerge() throws IOException { - // github-221 - try (XMLSlideShow slideshow = new XMLSlideShow()) { - XSLFSlide slide = slideshow.createSlide(); - XSLFTable newTable = slide.createTable(3, 3); - newTable.setAnchor(new Rectangle(100, 100, 100, 100)); - - XSLFTableRow tableRow = newTable.addRow(); - assertEquals(0, tableRow.getCells().size()); - XSLFTableCell cell = tableRow.addCell(); - XSLFTextParagraph textparagraph = cell.addNewTextParagraph(); - XSLFTextRun textrun = textparagraph.addNewTextRun(); - textrun.setText("Any Text"); - textrun.setFontColor(Color.BLUE); - textparagraph.setTextAlign(TextParagraph.TextAlign.CENTER); - tableRow.addCell(); - tableRow.addCell(); - tableRow.mergeCells(0, 1); - - new DrawTableShape(newTable).setAllBorders(3., StrokeStyle.LineDash.LG_DASH_DOT, Color.BLUE); - - assertEquals(3, newTable.getCTTable().getTblGrid().sizeOfGridColArray()); - } - } - -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableRow.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableRow.java deleted file mode 100644 index 4c1109e519..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableRow.java +++ /dev/null @@ -1,141 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableRow; - -class TestXSLFTableRow { - - private static XMLSlideShow ppt; - private static XSLFTable tbl; - private static XSLFTableRow row; - - /** Copied from {@link TestXSLFTable#testRead()} */ - @BeforeEach - void setUp() throws IOException { - ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - - XSLFSlide slide = ppt.getSlides().get(3); - List<XSLFShape> shapes = slide.getShapes(); - tbl = (XSLFTable)shapes.get(0); - List<XSLFTableRow> rows = tbl.getRows(); - row = rows.get(0); - } - - @AfterEach - void tearDown() throws IOException { - ppt.getPackage().revert(); - ppt.close(); - } - - - @Test - void constructor() { - XSLFTableRow row2 = new XSLFTableRow(row.getXmlObject(), tbl); - assertSame(row.getXmlObject(), row2.getXmlObject()); - assertEquals(row.getHeight(), row2.getHeight(), 1e-16); - } - - @Test - void testHeight() { - final double h = 10.0; - row.setHeight(h); - assertEquals(h, row.getHeight(), 1e-16); - } - - /** copied from {@link TestXSLFTable#testCreate()} */ - @Test - void getCells() { - List<XSLFTableCell> cells = row.getCells(); - assertNotNull(cells); - assertEquals(3, cells.size()); - } - - @Test - void testIterator() { - int i = 0; - for (XSLFTableCell cell : row) { - i++; - assertEquals("header"+i, cell.getText()); - } - assertEquals(3, i); - } - - /** copied from {@link TestXSLFTable#testCreate()} */ - @Test - void addCell() { - XSLFTableCell cell = row.addCell(); - assertNotNull(cell); - - assertNotNull(cell.getXmlObject()); - // by default table cell has no borders - CTTableCell tc = (CTTableCell)cell.getXmlObject(); - assertTrue(tc.getTcPr().getLnB().isSetNoFill()); - assertTrue(tc.getTcPr().getLnT().isSetNoFill()); - assertTrue(tc.getTcPr().getLnL().isSetNoFill()); - assertTrue(tc.getTcPr().getLnR().isSetNoFill()); - } - - @Test - void mergeCells() { - assertThrows(IllegalArgumentException.class, () -> row.mergeCells(0, 0), - "expected IllegalArgumentException when merging fewer than 2 columns"); - - row.mergeCells(0, 1); - List<XSLFTableCell> cells = row.getCells(); - //the top-left cell of a merged region is not regarded as merged - assertFalse(cells.get(0).isMerged(), "top-left cell of merged region"); - assertTrue(cells.get(1).isMerged(), "inside merged region"); - assertFalse(cells.get(2).isMerged(), "outside merged region"); - } - - @Test - void getXmlObject() { - CTTableRow ctrow = row.getXmlObject(); - assertNotNull(ctrow); - } - - - @Test - void getShapeNameOfCells() throws Exception { - try(XMLSlideShow ss1 = XSLFTestDataSamples.openSampleDocument("table_test.pptx")) { - for (XSLFSlide slide : ss1.getSlides()) { - for (XSLFShape shape : slide.getShapes()) { - assertEquals("Table 3", shape.getShapeName()); - if (shape instanceof XSLFTable) { - for (XSLFTableRow row : ((XSLFTable) shape).getRows()) { - for (XSLFTableCell cell : row.getCells()) { - assertNull(cell.getShapeName()); // Do not throw NPE - assertThrows(IllegalStateException.class, cell::getShapeId); - } - } - } - } - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableStyles.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableStyles.java deleted file mode 100644 index f1232de7cd..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableStyles.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -class TestXSLFTableStyles { - - @Test - void testRead() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFTableStyles tblStyles = ppt.getTableStyles(); - assertNotNull(tblStyles); - - assertEquals(0, tblStyles.getStyles().size()); - - ppt.close(); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextBox.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextBox.java deleted file mode 100644 index 04fa9551d1..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextBox.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.io.IOException; - -import org.apache.poi.sl.usermodel.Placeholder; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; - -/** - * @author Yegor Kozlov - */ -class TestXSLFTextBox { - - @Test - void testPlaceholder() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFTextBox shape = slide.createTextBox(); - assertNull(shape.getTextType()); - shape.setPlaceholder(Placeholder.TITLE); - assertEquals(Placeholder.TITLE, shape.getTextType()); - shape.setPlaceholder(null); - assertNull(shape.getTextType()); - shape.setText("Apache POI"); - - ppt.close(); - } - - /** - * text box inherits default text proeprties from presentation.xml - */ - @Test - void testDefaultTextStyle() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - // default character properties for paragraphs with level=1 - CTTextCharacterProperties pPr = ppt.getCTPresentation().getDefaultTextStyle().getLvl1PPr().getDefRPr(); - - XSLFTextBox shape = slide.createTextBox(); - shape.setText("Apache POI"); - assertEquals(1, shape.getTextParagraphs().size()); - assertEquals(1, shape.getTextParagraphs().get(0).getTextRuns().size()); - - XSLFTextRun r = shape.getTextParagraphs().get(0).getTextRuns().get(0); - - assertEquals(1800, pPr.getSz()); - assertEquals(18.0, r.getFontSize(), 0); - assertEquals("Calibri", r.getFontFamily()); - - pPr.setSz(900); - pPr.getLatin().setTypeface("Arial"); - assertEquals(9.0, r.getFontSize(), 0); - assertEquals("Arial", r.getFontFamily()); - - // unset font size in presentation.xml. The value should be taken from master slide - // from /p:sldMaster/p:txStyles/p:otherStyle/a:lvl1pPr/a:defRPr - ppt.getCTPresentation().getDefaultTextStyle().getLvl1PPr().getDefRPr().unsetSz(); - pPr = slide.getSlideMaster().getXmlObject().getTxStyles().getOtherStyle().getLvl1PPr().getDefRPr(); - assertEquals(1800, pPr.getSz()); - assertEquals(18.0, r.getFontSize(), 0); - pPr.setSz(2000); - assertEquals(20.0, r.getFontSize(), 0); - - pPr.unsetSz(); // Should never be - assertNull(r.getFontSize()); - - ppt.close(); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextParagraph.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextParagraph.java deleted file mode 100644 index 749a8faeca..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextParagraph.java +++ /dev/null @@ -1,387 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.sl.draw.DrawTextFragment; -import org.apache.poi.sl.draw.DrawTextParagraph; -import org.apache.poi.sl.usermodel.AutoNumberingScheme; -import org.apache.poi.sl.usermodel.TextParagraph.TextAlign; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; - -class TestXSLFTextParagraph { - static class DrawTextParagraphProxy extends DrawTextParagraph { - DrawTextParagraphProxy(XSLFTextParagraph p) { - super(p); - } - - @Override - public void breakText(Graphics2D graphics) { - super.breakText(graphics); - } - - @Override - public double getWrappingWidth(boolean firstLine, Graphics2D graphics) { - return super.getWrappingWidth(firstLine, graphics); - } - - public List<DrawTextFragment> getLines() { - return lines; - } - } - - @Test - void testWrappingWidth() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - sh.setLineColor(Color.black); - - XSLFTextParagraph p = sh.addNewTextParagraph(); - p.addNewTextRun().setText( - "Paragraph formatting allows for more granular control " + - "of text within a shape. Properties here apply to all text " + - "residing within the corresponding paragraph."); - - Rectangle2D anchor = new Rectangle2D.Double(50, 50, 300, 200); - sh.setAnchor(anchor); - - DrawTextParagraphProxy dtp = new DrawTextParagraphProxy(p); - - double leftInset = sh.getLeftInset(); - double rightInset = sh.getRightInset(); - assertEquals(7.2, leftInset, 0); - assertEquals(7.2, rightInset, 0); - - Double leftMargin = p.getLeftMargin(); - assertEquals(0.0, leftMargin, 0); - - Double indent = p.getIndent(); - assertNull(indent); // default - - double expectedWidth; - - // Case 1: bullet=false, leftMargin=0, indent=0. - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin; - assertEquals(285.6, expectedWidth, 0); // 300 - 7.2 - 7.2 - 0 - assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); - assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0); - - p.setLeftMargin(36d); // 0.5" - leftMargin = p.getLeftMargin(); - assertEquals(36.0, leftMargin, 0); - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin; - assertEquals(249.6, expectedWidth, 1E-5); // 300 - 7.2 - 7.2 - 36 - assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); - assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0); - - // increase insets, the wrapping width should get smaller - sh.setLeftInset(10); - sh.setRightInset(10); - leftInset = sh.getLeftInset(); - rightInset = sh.getRightInset(); - assertEquals(10.0, leftInset, 0); - assertEquals(10.0, rightInset, 0); - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin; - assertEquals(244.0, expectedWidth, 0); // 300 - 10 - 10 - 36 - assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); - assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0); - - // set a positive indent of a 0.5 inch. This means "First Line" indentation: - // |<--- indent -->|Here goes first line of the text - // Here go other lines (second and subsequent) - - p.setIndent(36.0); // 0.5" - indent = p.getIndent(); - assertEquals(36.0, indent, 0); - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin - indent; - assertEquals(208.0, expectedWidth, 0); // 300 - 10 - 10 - 36 - 6.4 - assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); // first line is indented - // other lines are not indented - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin; - assertEquals(244.0, expectedWidth, 0); // 300 - 10 - 10 - 36 - assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0); - - // set a negative indent of a 1 inch. This means "Hanging" indentation: - // Here goes first line of the text - // |<--- indent -->|Here go other lines (second and subsequent) - p.setIndent(-72.0); // 1" - indent = p.getIndent(); - assertEquals(-72.0, indent, 0); - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin - indent; - assertEquals(316.0, expectedWidth, 0); // 300 - 10 - 10 - assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); // first line is NOT indented - // other lines are indented by leftMargin (the value of indent is not used) - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin; - assertEquals(244.0, expectedWidth, 0); // 300 - 10 - 10 - 36 - assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0); - - ppt.close(); - } - - /** - * test breaking test into lines. - * This test requires that the Arial font is available and will run only on windows - */ - @Test - void testBreakLines() throws IOException { - String os = System.getProperty("os.name"); - assumeTrue((os != null && os.contains("Windows")), "Skipping testBreakLines(), it is executed only on Windows machines"); - - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - - XSLFTextParagraph p = sh.addNewTextParagraph(); - XSLFTextRun r = p.addNewTextRun(); - r.setFontFamily("Arial"); // this should always be available - r.setFontSize(12d); - r.setText( - "Paragraph formatting allows for more granular control " + - "of text within a shape. Properties here apply to all text " + - "residing within the corresponding paragraph."); - - sh.setAnchor(new Rectangle2D.Double(50, 50, 300, 200)); - DrawTextParagraphProxy dtp = new DrawTextParagraphProxy(p); - - BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics = img.createGraphics(); - - List<DrawTextFragment> lines; - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(4, lines.size()); - - // decrease the shape width from 300 pt to 100 pt - sh.setAnchor(new Rectangle2D.Double(50, 50, 100, 200)); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(12, lines.size()); - - // decrease the shape width from 300 pt to 100 pt - sh.setAnchor(new Rectangle2D.Double(50, 50, 600, 200)); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(2, lines.size()); - - // set left and right margins to 200pt. This leaves 200pt for wrapping text - sh.setLeftInset(200); - sh.setRightInset(200); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(5, lines.size()); - - r.setText("Apache POI"); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(1, lines.size()); - assertEquals("Apache POI", lines.get(0).getString()); - - r.setText("Apache\nPOI"); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(2, lines.size()); - assertEquals("Apache", lines.get(0).getString()); - assertEquals("POI", lines.get(1).getString()); - - // trailing newlines are ignored - r.setText("Apache\nPOI\n"); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(2, lines.size()); - assertEquals("Apache", lines.get(0).getString()); - assertEquals("POI", lines.get(1).getString()); - - XSLFAutoShape sh2 = slide.createAutoShape(); - sh2.setAnchor(new Rectangle2D.Double(50, 50, 300, 200)); - XSLFTextParagraph p2 = sh2.addNewTextParagraph(); - XSLFTextRun r2 = p2.addNewTextRun(); - r2.setFontFamily("serif"); // this should always be available - r2.setFontSize(30d); - r2.setText("Apache\n"); - XSLFTextRun r3 = p2.addNewTextRun(); - r3.setFontFamily("serif"); // this should always be available - r3.setFontSize(10d); - r3.setText("POI"); - dtp = new DrawTextParagraphProxy(p2); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(2, lines.size()); - assertEquals("Apache", lines.get(0).getString()); - assertEquals("POI", lines.get(1).getString()); - // the first line is at least two times higher than the second - assertTrue(lines.get(0).getHeight() > lines.get(1).getHeight()*2); - - ppt.close(); - } - - @Test - void testThemeInheritance() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("prProps.pptx"); - List<XSLFShape> shapes = ppt.getSlides().get(0).getShapes(); - XSLFTextShape sh1 = (XSLFTextShape)shapes.get(0); - assertEquals("Apache", sh1.getText()); - assertEquals(TextAlign.CENTER, sh1.getTextParagraphs().get(0).getTextAlign()); - XSLFTextShape sh2 = (XSLFTextShape)shapes.get(1); - assertEquals("Software", sh2.getText()); - assertEquals(TextAlign.CENTER, sh2.getTextParagraphs().get(0).getTextAlign()); - XSLFTextShape sh3 = (XSLFTextShape)shapes.get(2); - assertEquals("Foundation", sh3.getText()); - assertEquals(TextAlign.CENTER, sh3.getTextParagraphs().get(0).getTextAlign()); - ppt.close(); - } - - @Test - void testParagraphProperties() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - - XSLFTextParagraph p = sh.addNewTextParagraph(); - assertFalse(p.isBullet()); - p.setBullet(true); - assertTrue(p.isBullet()); - - assertEquals("\u2022", p.getBulletCharacter()); - p.setBulletCharacter("*"); - assertEquals("*", p.getBulletCharacter()); - - assertEquals("Arial", p.getBulletFont()); - p.setBulletFont("Calibri"); - assertEquals("Calibri", p.getBulletFont()); - - assertNull(p.getBulletFontColor()); - p.setBulletFontColor(Color.red); - assertEquals(Color.red, getColor(p.getBulletFontColor())); - - assertNull(p.getBulletFontSize()); - p.setBulletFontSize(200.); - assertEquals(200., p.getBulletFontSize(), 0); - p.setBulletFontSize(-20.); - assertEquals(-20.0, p.getBulletFontSize(), 0); - - assertEquals(72.0, p.getDefaultTabSize(), 0); - - assertNull(p.getIndent()); - p.setIndent(72.0); - assertEquals(72.0, p.getIndent(), 0); - p.setIndent(-1d); // the value of -1.0 resets to the defaults (not any more ...) - assertEquals(-1d, p.getIndent(), 0); - p.setIndent(null); - assertNull(p.getIndent()); - - assertEquals(0.0, p.getLeftMargin(), 0); - p.setLeftMargin(72.0); - assertEquals(72.0, p.getLeftMargin(), 0); - p.setLeftMargin(-1.0); // the value of -1.0 resets to the defaults - assertEquals(-1.0, p.getLeftMargin(), 0); - p.setLeftMargin(null); - assertEquals(0d, p.getLeftMargin(), 0); // default will be taken from master - - assertEquals(0, p.getIndentLevel()); - p.setIndentLevel(1); - assertEquals(1, p.getIndentLevel()); - p.setIndentLevel(2); - assertEquals(2, p.getIndentLevel()); - - assertNull(p.getLineSpacing()); - p.setLineSpacing(200.); - assertEquals(200.0, p.getLineSpacing(), 0); - p.setLineSpacing(-15.); - assertEquals(-15.0, p.getLineSpacing(), 0); - - assertNull(p.getSpaceAfter()); - p.setSpaceAfter(200.); - assertEquals(200.0, p.getSpaceAfter(), 0); - p.setSpaceAfter(-15.); - assertEquals(-15.0, p.getSpaceAfter(), 0); - p.setSpaceAfter(null); - assertNull(p.getSpaceAfter()); - p.setSpaceAfter(null); - assertNull(p.getSpaceAfter()); - - assertNull(p.getSpaceBefore()); - p.setSpaceBefore(200.); - assertEquals(200.0, p.getSpaceBefore(), 0); - p.setSpaceBefore(-15.); - assertEquals(-15.0, p.getSpaceBefore(), 0); - p.setSpaceBefore(null); - assertNull(p.getSpaceBefore()); - p.setSpaceBefore(null); - assertNull(p.getSpaceBefore()); - - assertEquals(TextAlign.LEFT, p.getTextAlign()); - p.setTextAlign(TextAlign.RIGHT); - assertEquals(TextAlign.RIGHT, p.getTextAlign()); - - p.setBullet(false); - assertFalse(p.isBullet()); - - p.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenBoth, 1); - - double tabStop = p.getTabStop(0); - assertEquals(0.0, tabStop, 0); - - p.addTabStop(100.); - assertEquals(100., p.getTabStop(0), 0); - - assertEquals(72.0, p.getDefaultTabSize(), 0); - - ppt.close(); - } - - @Test - void testLineBreak() throws IOException { - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - - XSLFTextParagraph p = sh.addNewTextParagraph(); - XSLFTextRun r1 = p.addNewTextRun(); - r1.setText("Hello,"); - XSLFTextRun r2 = p.addLineBreak(); - assertEquals("\n", r2.getRawText()); - r2.setFontSize(10.0); - assertEquals(10.0, r2.getFontSize(), 0); - XSLFTextRun r3 = p.addNewTextRun(); - r3.setText("World!"); - r3.setFontSize(20.0); - XSLFTextRun r4 = p.addLineBreak(); - assertEquals(20.0, r4.getFontSize(), 0); - - assertEquals("Hello,\nWorld!\n", sh.getText()); - - // "You cannot change text of a line break, it is always '\\n'" - assertThrows(IllegalStateException.class, () -> r2.setText("aaa")); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextRun.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextRun.java deleted file mode 100644 index 783e8abe4d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextRun.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.awt.Color; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.sl.draw.DrawTextParagraph; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextLineBreak; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; - -/** - * @author Yegor Kozlov - */ -class TestXSLFTextRun { - - @Test - void testRunProperties() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - - XSLFTextRun r = sh.addNewTextParagraph().addNewTextRun(); - assertEquals("en-US", r.getRPr(true).getLang()); - - assertEquals(0., r.getCharacterSpacing(), 0); - r.setCharacterSpacing(3); - assertEquals(3., r.getCharacterSpacing(), 0); - r.setCharacterSpacing(-3); - assertEquals(-3., r.getCharacterSpacing(), 0); - r.setCharacterSpacing(0); - assertEquals(0., r.getCharacterSpacing(), 0); - assertFalse(r.getRPr(true).isSetSpc()); - - assertEquals(Color.black, getColor(r.getFontColor())); - r.setFontColor(Color.red); - assertEquals(Color.red, getColor(r.getFontColor())); - - assertEquals("Calibri", r.getFontFamily()); - r.setFontFamily("Arial"); - assertEquals("Arial", r.getFontFamily()); - - assertEquals(18.0, r.getFontSize(), 0); - r.setFontSize(13.0); - assertEquals(13.0, r.getFontSize(), 0); - - assertFalse(r.isSuperscript()); - r.setSuperscript(true); - assertTrue(r.isSuperscript()); - r.setSuperscript(false); - assertFalse(r.isSuperscript()); - - assertFalse(r.isSubscript()); - r.setSubscript(true); - assertTrue(r.isSubscript()); - r.setSubscript(false); - assertFalse(r.isSubscript()); - - ppt.close(); - } - - @Test - void testUnicodeSurrogates() throws Exception { - final String unicodeSurrogates = "\uD835\uDF4A\uD835\uDF4B\uD835\uDF4C\uD835\uDF4D\uD835\uDF4E" - + "\uD835\uDF4F\uD835\uDF50\uD835\uDF51\uD835\uDF52\uD835\uDF53\uD835\uDF54\uD835" - + "\uDF55\uD835\uDF56\uD835\uDF57\uD835\uDF58\uD835\uDF59\uD835\uDF5A\uD835\uDF5B" - + "\uD835\uDF5C\uD835\uDF5D\uD835\uDF5E\uD835\uDF5F\uD835\uDF60\uD835\uDF61\uD835" - + "\uDF62\uD835\uDF63\uD835\uDF64\uD835\uDF65\uD835\uDF66\uD835\uDF67\uD835\uDF68" - + "\uD835\uDF69\uD835\uDF6A\uD835\uDF6B\uD835\uDF6C\uD835\uDF6D\uD835\uDF6E\uD835" - + "\uDF6F\uD835\uDF70\uD835\uDF71\uD835\uDF72\uD835\uDF73\uD835\uDF74\uD835\uDF75" - + "\uD835\uDF76\uD835\uDF77\uD835\uDF78\uD835\uDF79\uD835\uDF7A"; - - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - XSLFTextParagraph p = sh.addNewTextParagraph(); - XSLFTextRun r = p.addNewTextRun(); - r.setText(unicodeSurrogates); - - assertEquals(unicodeSurrogates, new DrawTextParagraph(p).getRenderableText(r)); - } - } - - @Test - void testCopyNullFontSize() throws IOException { - try (XMLSlideShow ppt = new XMLSlideShow()) { - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - - XSLFTextRun r = sh.addNewTextParagraph().addNewTextRun(); - - XSLFTextRun s = new XSLFTextRun(CTTextLineBreak.Factory.newInstance(), - new XSLFTextParagraph(CTTextParagraph.Factory.newInstance(), - new XSLFTextBox(CTShape.Factory.newInstance(), slide))); - - assertDoesNotThrow(() -> r.copy(s)); - } - } - - @Test - void testDefaultRunProperties() throws IOException { - // bug #63290 - POIDataSamples pds = POIDataSamples.getSlideShowInstance(); - try (InputStream is = pds.openResourceAsStream("bug63290.pptx"); - XMLSlideShow ppt = new XMLSlideShow(is)) { - XSLFSlide slide = ppt.getSlides().get(0); - for (XSLFShape shape : slide.getShapes()) { - if (shape instanceof XSLFTextShape) { - XSLFTextShape text = (XSLFTextShape) shape; - XSLFTextParagraph paragraph = text.getTextParagraphs().get(0); - XSLFTextRun defaultRun = paragraph.getTextRuns().get(0); - assertEquals("DefaultRunProperties", defaultRun.getRawText().trim()); - XSLFTextRun explicitRun = paragraph.getTextRuns().get(1); - assertEquals("ExplicitRunProperties", explicitRun.getRawText().trim()); - assertEquals(defaultRun.getFontSize(), explicitRun.getFontSize()); - assertNotEquals(defaultRun.getFontColor(), explicitRun.getFontColor()); - } - } - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextShape.java deleted file mode 100644 index 372e0216f4..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextShape.java +++ /dev/null @@ -1,964 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; -import static org.apache.poi.xslf.usermodel.TestXSLFSimpleShape.getSpPr; -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.awt.Color; -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.stream.Collectors; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.sl.usermodel.TextParagraph.TextAlign; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.xddf.usermodel.text.XDDFBodyProperties; -import org.apache.poi.xddf.usermodel.text.XDDFTextBody; -import org.apache.poi.xddf.usermodel.text.XDDFTextParagraph; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBodyProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextAlignType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder; -import org.openxmlformats.schemas.presentationml.x2006.main.STPlaceholderType; - -class TestXSLFTextShape { - private static boolean xslfOnly; - - @BeforeAll - public static void checkHslf() { - try { - Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); - } catch (Exception e) { - xslfOnly = true; - } - } - - @Test - void testLayouts() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("layouts.pptx"); - - List<XSLFSlide> slide = ppt.getSlides(); - - verifySlide1(slide.get(0)); - verifySlide2(slide.get(1)); - verifySlide3(slide.get(2)); - verifySlide4(slide.get(3)); - verifySlide7(slide.get(6)); - verifySlide8(slide.get(7)); - verifySlide10(slide.get(9)); - - ppt.close(); - } - - void verifySlide1(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List<XSLFShape> shapes = slide.getShapes(); - assertEquals("Title Slide",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - XDDFTextBody tb1 = shape1.getTextBody(); - XDDFBodyProperties tbp1 = tb1.getBodyProperties(); - CTPlaceholder ph1 = shape1.getPlaceholderDetails().getCTPlaceholder(false); - assertEquals(STPlaceholderType.CTR_TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - XSLFTextShape masterShape1 = (XSLFTextShape)layout.getPlaceholder(ph1); - assertNotNull(getSpPr(masterShape1).getXfrm()); - assertEquals(masterShape1.getAnchor(), shape1.getAnchor()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.MIDDLE, shape1.getVerticalAlignment()); - assertNull(tbp1.getLeftInset()); - assertNull(tbp1.getRightInset()); - assertNull(tbp1.getBottomInset()); - assertNull(tbp1.getTopInset()); - assertNull(tbp1.getAnchoring()); - - // now check text properties - assertEquals("Centered Title", shape1.getText()); - assertEquals("Centered Title", - tb1.getParagraphs().stream().map(XDDFTextParagraph::getText).collect(Collectors.joining("\n"))); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(44.0, r1.getFontSize(), 0); - assertEquals(Color.black, getColor(r1.getFontColor())); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - XDDFTextBody tb2 = shape2.getTextBody(); - XDDFBodyProperties tbp2 = tb2.getBodyProperties(); - CTPlaceholder ph2 = shape2.getPlaceholderDetails().getCTPlaceholder(false); - assertEquals(STPlaceholderType.SUB_TITLE, ph2.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape2).getXfrm()); - - XSLFTextShape masterShape2 = (XSLFTextShape)layout.getPlaceholder(ph2); - assertNotNull(getSpPr(masterShape2).getXfrm()); - assertEquals(masterShape2.getAnchor(), shape2.getAnchor()); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape2.getVerticalAlignment()); - assertNull(tbp2.getLeftInset()); - assertNull(tbp2.getRightInset()); - assertNull(tbp2.getBottomInset()); - assertNull(tbp2.getTopInset()); - assertNull(tbp2.getAnchoring()); - - assertEquals("subtitle", shape2.getText()); - assertEquals("subtitle", tb2.getParagraphs().stream().map(XDDFTextParagraph::getText).collect(Collectors.joining("\n"))); - XSLFTextRun r2 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Calibri", r2.getFontFamily()); - assertEquals(32.0, r2.getFontSize(), 0); - // TODO fix calculation of tint - //assertEquals(new Color(137, 137, 137), r2.getFontColor()); - } - - void verifySlide2(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List<XSLFShape> shapes = slide.getShapes(); - assertEquals("Title and Content",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - CTPlaceholder ph1 = shape1.getPlaceholderDetails().getCTPlaceholder(false); - assertEquals(STPlaceholderType.TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - XSLFTextShape masterShape1 = (XSLFTextShape)layout.getPlaceholder(ph1); - // layout does not have anchor info either, it is in the slide master - assertNull(getSpPr(masterShape1).getXfrm()); - masterShape1 = (XSLFTextShape)layout.getSlideMaster().getPlaceholder(ph1); - assertNotNull(getSpPr(masterShape1).getXfrm()); - assertEquals(masterShape1.getAnchor(), shape1.getAnchor()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.MIDDLE, shape1.getVerticalAlignment()); - - // now check text properties - assertEquals("Title", shape1.getText()); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(44.0, r1.getFontSize(), 0); - assertEquals(Color.black, getColor(r1.getFontColor())); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - CTPlaceholder ph2 = shape2.getPlaceholderDetails().getCTPlaceholder(false); - assertFalse(ph2.isSetType()); // <p:ph idx="1"/> - assertTrue(ph2.isSetIdx()); - assertEquals(1, ph2.getIdx()); - // anchor is not defined in the shape - assertNull(getSpPr(shape2).getXfrm()); - - XSLFTextShape masterShape2 = (XSLFTextShape)layout.getPlaceholder(ph2); - // anchor of the body text is missing in the slide layout, llokup in the slide master - assertNull(getSpPr(masterShape2).getXfrm()); - masterShape2 = (XSLFTextShape)layout.getSlideMaster().getPlaceholder(ph2); - assertNotNull(getSpPr(masterShape2).getXfrm()); - assertEquals(masterShape2.getAnchor(), shape2.getAnchor()); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape2.getVerticalAlignment()); - - XSLFTextRun pr1 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr1.getParagraph().getIndentLevel()); - assertEquals("Content", pr1.getRawText()); - assertEquals("Calibri", pr1.getFontFamily()); - assertEquals(32.0, pr1.getFontSize(), 0); - assertEquals(27.0, pr1.getParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr1.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr1.getParagraph().getBulletFont()); - - XSLFTextRun pr2 = shape2.getTextParagraphs().get(1).getTextRuns().get(0); - assertEquals(1, pr2.getParagraph().getIndentLevel()); - assertEquals("Level 2", pr2.getRawText()); - assertEquals("Calibri", pr2.getFontFamily()); - assertEquals(28.0, pr2.getFontSize(), 0); - assertEquals(58.5, pr2.getParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr2.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr2.getParagraph().getBulletFont()); - - XSLFTextRun pr3 = shape2.getTextParagraphs().get(2).getTextRuns().get(0); - assertEquals(2, pr3.getParagraph().getIndentLevel()); - assertEquals("Level 3", pr3.getRawText()); - assertEquals("Calibri", pr3.getFontFamily()); - assertEquals(24.0, pr3.getFontSize(), 0); - assertEquals(90.0, pr3.getParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr3.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr3.getParagraph().getBulletFont()); - - XSLFTextRun pr4 = shape2.getTextParagraphs().get(3).getTextRuns().get(0); - assertEquals(3, pr4.getParagraph().getIndentLevel()); - assertEquals("Level 4", pr4.getRawText()); - assertEquals("Calibri", pr4.getFontFamily()); - assertEquals(20.0, pr4.getFontSize(), 0); - assertEquals(126.0, pr4.getParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr4.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr4.getParagraph().getBulletFont()); - - XSLFTextRun pr5 = shape2.getTextParagraphs().get(4).getTextRuns().get(0); - assertEquals(4, pr5.getParagraph().getIndentLevel()); - assertEquals("Level 5", pr5.getRawText()); - assertEquals("Calibri", pr5.getFontFamily()); - assertEquals(20.0, pr5.getFontSize(), 0); - assertEquals(162.0, pr5.getParagraph().getLeftMargin(), 0); - assertEquals("\u00bb", pr5.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr5.getParagraph().getBulletFont()); - - } - - void verifySlide3(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List<XSLFShape> shapes = slide.getShapes(); - assertEquals("Section Header",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - CTPlaceholder ph1 = shape1.getPlaceholderDetails().getCTPlaceholder(false); - assertEquals(STPlaceholderType.TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - XSLFTextShape masterShape1 = (XSLFTextShape)layout.getPlaceholder(ph1); - assertNotNull(getSpPr(masterShape1).getXfrm()); - assertEquals(masterShape1.getAnchor(), shape1.getAnchor()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape1.getVerticalAlignment()); - - // now check text properties - assertEquals("Section Title", shape1.getText()); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.LEFT, r1.getParagraph().getTextAlign()); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(40.0, r1.getFontSize(), 0); - assertEquals(Color.black, getColor(r1.getFontColor())); - assertTrue(r1.isBold()); - assertFalse(r1.isItalic()); - assertFalse(r1.isUnderlined()); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - CTPlaceholder ph2 = shape2.getPlaceholderDetails().getCTPlaceholder(false); - assertEquals(STPlaceholderType.BODY, ph2.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape2).getXfrm()); - - XSLFTextShape masterShape2 = (XSLFTextShape)layout.getPlaceholder(ph2); - assertNotNull(getSpPr(masterShape2).getXfrm()); - assertEquals(masterShape2.getAnchor(), shape2.getAnchor()); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.BOTTOM, shape2.getVerticalAlignment()); - - assertEquals("Section Header", shape2.getText()); - XSLFTextRun r2 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.LEFT, r2.getParagraph().getTextAlign()); - assertEquals("Calibri", r2.getFontFamily()); - assertEquals(20.0, r2.getFontSize(), 0); - // TODO fix calculation of tint - //assertEquals(new Color(137, 137, 137), r2.getFontColor()); - } - - void verifySlide4(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List<XSLFShape> shapes = slide.getShapes(); - assertEquals("Two Content",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - CTPlaceholder ph1 = shape1.getPlaceholderDetails().getCTPlaceholder(false); - assertEquals(STPlaceholderType.TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - XSLFTextShape masterShape1 = (XSLFTextShape)layout.getPlaceholder(ph1); - // layout does not have anchor info either, it is in the slide master - assertNull(getSpPr(masterShape1).getXfrm()); - masterShape1 = (XSLFTextShape)layout.getSlideMaster().getPlaceholder(ph1); - assertNotNull(getSpPr(masterShape1).getXfrm()); - assertEquals(masterShape1.getAnchor(), shape1.getAnchor()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.MIDDLE, shape1.getVerticalAlignment()); - - // now check text properties - assertEquals("Title", shape1.getText()); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.CENTER, r1.getParagraph().getTextAlign()); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(44.0, r1.getFontSize(), 0); - assertEquals(Color.black, getColor(r1.getFontColor())); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - CTPlaceholder ph2 = shape2.getPlaceholderDetails().getCTPlaceholder(false); - assertFalse(ph2.isSetType()); - assertTrue(ph2.isSetIdx()); - assertEquals(1, ph2.getIdx()); //<p:ph sz="half" idx="1"/> - // anchor is not defined in the shape - assertNull(getSpPr(shape2).getXfrm()); - - XSLFTextShape masterShape2 = (XSLFTextShape)layout.getPlaceholder(ph2); - assertNotNull(getSpPr(masterShape2).getXfrm()); - assertEquals(masterShape2.getAnchor(), shape2.getAnchor()); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape2.getVerticalAlignment()); - - XSLFTextRun pr1 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr1.getParagraph().getIndentLevel()); - assertEquals("Left", pr1.getRawText()); - assertEquals("Calibri", pr1.getFontFamily()); - assertEquals(28.0, pr1.getFontSize(), 0); - assertEquals(27.0, pr1.getParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr1.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr1.getParagraph().getBulletFont()); - - XSLFTextRun pr2 = shape2.getTextParagraphs().get(1).getTextRuns().get(0); - assertEquals(1, pr2.getParagraph().getIndentLevel()); - assertEquals("Level 2", pr2.getParagraph().getText()); - assertEquals("Calibri", pr2.getFontFamily()); - assertEquals(24.0, pr2.getFontSize(), 0); - assertEquals(58.5, pr2.getParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr2.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr2.getParagraph().getBulletFont()); - - XSLFTextRun pr3 = shape2.getTextParagraphs().get(2).getTextRuns().get(0); - assertEquals(2, pr3.getParagraph().getIndentLevel()); - assertEquals("Level 3", pr3.getParagraph().getText()); - assertEquals("Calibri", pr3.getFontFamily()); - assertEquals(20.0, pr3.getFontSize(), 0); - assertEquals(90.0, pr3.getParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr3.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr3.getParagraph().getBulletFont()); - - XSLFTextRun pr4 = shape2.getTextParagraphs().get(3).getTextRuns().get(0); - assertEquals(3, pr4.getParagraph().getIndentLevel()); - assertEquals("Level 4", pr4.getParagraph().getText()); - assertEquals("Calibri", pr4.getFontFamily()); - assertEquals(18.0, pr4.getFontSize(), 0); - assertEquals(126.0, pr4.getParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr4.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr4.getParagraph().getBulletFont()); - - XSLFTextShape shape3 = (XSLFTextShape)shapes.get(2); - XSLFTextRun pr5 = shape3.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr5.getParagraph().getIndentLevel()); - assertEquals("Right", pr5.getRawText()); - assertEquals("Calibri", pr5.getFontFamily()); - assertEquals(Color.black, getColor(pr5.getFontColor())); - } - - @SuppressWarnings("unused") - void verifySlide5(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List<XSLFShape> shapes = slide.getShapes(); - // TODO - } - - void verifySlide7(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List<XSLFShape> shapes = slide.getShapes(); - assertEquals("Blank",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - CTPlaceholder ph1 = shape1.getPlaceholderDetails().getCTPlaceholder(false); - assertEquals(STPlaceholderType.TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.MIDDLE, shape1.getVerticalAlignment()); - - // now check text properties - assertEquals("Blank with Default Title", shape1.getText()); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.CENTER, r1.getParagraph().getTextAlign()); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(44.0, r1.getFontSize(), 0); - assertEquals(Color.black, getColor(r1.getFontColor())); - assertFalse(r1.isBold()); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape2.getVerticalAlignment()); - - XSLFTextRun pr1 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr1.getParagraph().getIndentLevel()); - assertEquals("Default Text", pr1.getRawText()); - assertEquals("Calibri", pr1.getFontFamily()); - assertEquals(18.0, pr1.getFontSize(), 0); - - XSLFTextShape shape3 = (XSLFTextShape)shapes.get(2); - assertEquals("Default", shape3.getTextParagraphs().get(0).getText()); - assertEquals("Text with levels", shape3.getTextParagraphs().get(1).getText()); - assertEquals("Level 1", shape3.getTextParagraphs().get(2).getText()); - assertEquals("Level 2", shape3.getTextParagraphs().get(3).getText()); - assertEquals("Level 3", shape3.getTextParagraphs().get(4).getText()); - - for(int p = 0; p < 5; p++) { - XSLFTextParagraph pr = shape3.getTextParagraphs().get(p); - assertEquals("Calibri", pr.getTextRuns().get(0).getFontFamily()); - assertEquals(18.0, pr.getTextRuns().get(0).getFontSize(), 0); - } - } - - void verifySlide8(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List<XSLFShape> shapes = slide.getShapes(); - assertEquals("Content with Caption",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - CTPlaceholder ph1 = shape1.getPlaceholderDetails().getCTPlaceholder(false); - assertEquals(STPlaceholderType.TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - XSLFTextShape masterShape1 = (XSLFTextShape)layout.getPlaceholder(ph1); - // layout does not have anchor info either, it is in the slide master - assertNotNull(getSpPr(masterShape1).getXfrm()); - assertEquals(masterShape1.getAnchor(), shape1.getAnchor()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.BOTTOM, shape1.getVerticalAlignment()); - - // now check text properties - assertEquals("Caption", shape1.getText()); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.LEFT, r1.getParagraph().getTextAlign()); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(20.0, r1.getFontSize(), 0); - assertEquals(Color.black, getColor(r1.getFontColor())); - assertTrue(r1.isBold()); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - CTPlaceholder ph2 = shape2.getPlaceholderDetails().getCTPlaceholder(false); - assertFalse(ph2.isSetType()); - assertTrue(ph2.isSetIdx()); - assertEquals(1, ph2.getIdx()); - // anchor is not defined in the shape - assertNull(getSpPr(shape2).getXfrm()); - - XSLFTextShape masterShape2 = (XSLFTextShape)layout.getPlaceholder(ph2); - assertNotNull(getSpPr(masterShape2).getXfrm()); - assertEquals(masterShape2.getAnchor(), shape2.getAnchor()); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape2.getVerticalAlignment()); - - XSLFTextRun pr1 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr1.getParagraph().getIndentLevel()); - assertEquals("Level 1", pr1.getRawText()); - assertEquals("Calibri", pr1.getFontFamily()); - assertEquals(32.0, pr1.getFontSize(), 0); - assertEquals(27.0, pr1.getParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr1.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr1.getParagraph().getBulletFont()); - - XSLFTextRun pr2 = shape2.getTextParagraphs().get(1).getTextRuns().get(0); - assertEquals(1, pr2.getParagraph().getIndentLevel()); - assertEquals("Level 2", pr2.getParagraph().getText()); - assertEquals("Calibri", pr2.getFontFamily()); - assertEquals(28.0, pr2.getFontSize(), 0); - assertEquals(58.5, pr2.getParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr2.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr2.getParagraph().getBulletFont()); - - XSLFTextRun pr3 = shape2.getTextParagraphs().get(2).getTextRuns().get(0); - assertEquals(2, pr3.getParagraph().getIndentLevel()); - assertEquals("Level 3", pr3.getParagraph().getText()); - assertEquals("Calibri", pr3.getFontFamily()); - assertEquals(24.0, pr3.getFontSize(), 0); - assertEquals(90.0, pr3.getParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr3.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr3.getParagraph().getBulletFont()); - - XSLFTextRun pr4 = shape2.getTextParagraphs().get(3).getTextRuns().get(0); - assertEquals(3, pr4.getParagraph().getIndentLevel()); - assertEquals("Level 4", pr4.getParagraph().getText()); - assertEquals("Calibri", pr4.getFontFamily()); - assertEquals(20.0, pr4.getFontSize(), 0); - assertEquals(126.0, pr4.getParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr4.getParagraph().getBulletCharacter()); - assertEquals("Arial", pr4.getParagraph().getBulletFont()); - - XSLFTextShape shape3 = (XSLFTextShape)shapes.get(2); - assertEquals(VerticalAlignment.TOP, shape3.getVerticalAlignment()); - assertEquals("Content with caption", shape3.getText()); - - pr1 = shape3.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr1.getParagraph().getIndentLevel()); - assertEquals("Content with caption", pr1.getRawText()); - assertEquals("Calibri", pr1.getFontFamily()); - assertEquals(14.0, pr1.getFontSize(), 0); - - } - - void verifySlide10(XSLFSlide slide){ - XSLFTextShape footer = (XSLFTextShape)slide.getPlaceholderByType(STPlaceholderType.INT_FTR); - - // now check text properties - assertEquals("Apache Software Foundation", footer.getText()); - assertEquals(VerticalAlignment.MIDDLE, footer.getVerticalAlignment()); - - XSLFTextRun r1 = footer.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.CENTER, r1.getParagraph().getTextAlign()); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(12.0, r1.getFontSize(), 0); - assertEquals(new Color(0x898989), getColor(r1.getFontColor())); - - XSLFTextShape dt = (XSLFTextShape)slide.getPlaceholderByType(STPlaceholderType.INT_DT); - assertEquals("Friday, October 21, 2011", dt.getText()); - - XSLFTextShape sldNum = (XSLFTextShape)slide.getPlaceholderByType(STPlaceholderType.INT_SLD_NUM); - assertEquals("10", sldNum.getText()); - } - - @Test - void testTitleStyles() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlideMaster master = ppt.getSlideMasters().get(0); - XSLFTheme theme = master.getTheme(); - XSLFSlideLayout layout = master.getLayout(SlideLayout.TITLE); - XSLFSlide slide = ppt.createSlide(layout) ; - assertSame(layout, slide.getSlideLayout()); - assertSame(master, slide.getSlideMaster()); - - XSLFTextShape titleShape = slide.getPlaceholder(0); - titleShape.setText("Apache POI"); - XSLFTextParagraph paragraph = titleShape.getTextParagraphs().get(0); - XSLFTextRun textRun = paragraph.getTextRuns().get(0); - - // level 1 : default title style on the master slide - // /p:sldMaster/p:txStyles/p:titleStyle/a:lvl1pPr - CTTextParagraphProperties lv1PPr = master.getXmlObject().getTxStyles().getTitleStyle().getLvl1PPr(); - CTTextCharacterProperties lv1CPr = lv1PPr.getDefRPr(); - assertEquals(4400, lv1CPr.getSz()); - assertEquals(44.0, textRun.getFontSize(), 0); - assertEquals("+mj-lt", lv1CPr.getLatin().getTypeface()); - assertEquals("Calibri", theme.getMajorFont()); - assertEquals("Calibri", textRun.getFontFamily()); - lv1CPr.setSz(3200); - assertEquals(32.0, textRun.getFontSize(), 0); - lv1CPr.getLatin().setTypeface("Arial"); - assertEquals("Arial", textRun.getFontFamily()); - assertEquals(STTextAlignType.CTR, lv1PPr.getAlgn()); - assertEquals(TextAlign.CENTER, paragraph.getTextAlign()); - lv1PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, paragraph.getTextAlign()); - - // level 2: title placeholder on the master slide - // /p:sldMaster/p:cSld/p:spTree/p:sp/p:nvPr/p:ph[@type="title"] - XSLFTextShape tx2 = master.getPlaceholder(0); - CTTextParagraphProperties lv2PPr = tx2.getTextBody(true).getLstStyle().addNewLvl1PPr(); - CTTextCharacterProperties lv2CPr = lv2PPr.addNewDefRPr(); - lv2CPr.setSz(3300); - assertEquals(33.0, textRun.getFontSize(), 0); - lv2CPr.addNewLatin().setTypeface("Times"); - assertEquals("Times", textRun.getFontFamily()); - lv2PPr.setAlgn(STTextAlignType.R); - assertEquals(TextAlign.RIGHT, paragraph.getTextAlign()); - - - // level 3: title placeholder on the slide layout - // /p:sldLayout /p:cSld/p:spTree/p:sp/p:nvPr/p:ph[@type="ctrTitle"] - XSLFTextShape tx3 = layout.getPlaceholder(0); - CTTextParagraphProperties lv3PPr = tx3.getTextBody(true).getLstStyle().addNewLvl1PPr(); - CTTextCharacterProperties lv3CPr = lv3PPr.addNewDefRPr(); - lv3CPr.setSz(3400); - assertEquals(34.0, textRun.getFontSize(), 0); - lv3CPr.addNewLatin().setTypeface("Courier New"); - assertEquals("Courier New", textRun.getFontFamily()); - lv3PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, paragraph.getTextAlign()); - - // level 4: default text properties in the shape itself - // ./p:sp/p:txBody/a:lstStyle/a:lvl1pPr - CTTextParagraphProperties lv4PPr = titleShape.getTextBody(true).getLstStyle().addNewLvl1PPr(); - CTTextCharacterProperties lv4CPr = lv4PPr.addNewDefRPr(); - lv4CPr.setSz(3500); - assertEquals(35.0, textRun.getFontSize(), 0); - lv4CPr.addNewLatin().setTypeface("Arial"); - assertEquals("Arial", textRun.getFontFamily()); - lv4PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, paragraph.getTextAlign()); - - // level 5: text properties are defined in the text run - CTTextParagraphProperties lv5PPr = paragraph.getXmlObject().addNewPPr(); - CTTextCharacterProperties lv5CPr = textRun.getRPr(false); - lv5CPr.setSz(3600); - assertEquals(36.0, textRun.getFontSize(), 0); - lv5CPr.addNewLatin().setTypeface("Calibri"); - assertEquals("Calibri", textRun.getFontFamily()); - lv5PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, paragraph.getTextAlign()); - - ppt.close(); - } - - @Test - void testBodyStyles() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlideMaster master = ppt.getSlideMasters().get(0); - XSLFTheme theme = master.getTheme(); - XSLFSlideLayout layout = master.getLayout(SlideLayout.TITLE_AND_CONTENT); - XSLFSlide slide = ppt.createSlide(layout) ; - assertSame(layout, slide.getSlideLayout()); - assertSame(master, slide.getSlideMaster()); - - XSLFTextShape tx1 = slide.getPlaceholder(1); - tx1.clearText(); - - XSLFTextParagraph p1 = tx1.addNewTextParagraph(); - assertEquals(0, p1.getIndentLevel()); - XSLFTextRun r1 = p1.addNewTextRun(); - r1.setText("Apache POI"); - - XSLFTextParagraph p2 = tx1.addNewTextParagraph(); - p2.setIndentLevel(1); - assertEquals(1, p2.getIndentLevel()); - XSLFTextRun r2 = p2.addNewTextRun(); - r2.setText("HSLF"); - - XSLFTextParagraph p3 = tx1.addNewTextParagraph(); - p3.setIndentLevel(2); - assertEquals(2, p3.getIndentLevel()); - XSLFTextRun r3 = p3.addNewTextRun(); - r3.setText("XSLF"); - - // level 1 : default title style on the master slide - // /p:sldMaster/p:txStyles/p:bodyStyle/a:lvl1pPr - CTTextParagraphProperties lv1PPr = master.getXmlObject().getTxStyles().getBodyStyle().getLvl1PPr(); - CTTextCharacterProperties lv1CPr = lv1PPr.getDefRPr(); - CTTextParagraphProperties lv2PPr = master.getXmlObject().getTxStyles().getBodyStyle().getLvl2PPr(); - CTTextCharacterProperties lv2CPr = lv2PPr.getDefRPr(); - CTTextParagraphProperties lv3PPr = master.getXmlObject().getTxStyles().getBodyStyle().getLvl3PPr(); - CTTextCharacterProperties lv3CPr = lv3PPr.getDefRPr(); - // lv1 - assertEquals(3200, lv1CPr.getSz()); - assertEquals(32.0, r1.getFontSize(), 0); - assertEquals("+mn-lt", lv1CPr.getLatin().getTypeface()); - assertEquals("Calibri", theme.getMinorFont()); - assertEquals("Calibri", r1.getFontFamily()); - lv1CPr.setSz(3300); - assertEquals(33.0, r1.getFontSize(), 0); - lv1CPr.getLatin().setTypeface("Arial"); - assertEquals("Arial", r1.getFontFamily()); - assertEquals(STTextAlignType.L, lv1PPr.getAlgn()); - assertEquals(TextAlign.LEFT, p1.getTextAlign()); - lv1PPr.setAlgn(STTextAlignType.R); - assertEquals(TextAlign.RIGHT, p1.getTextAlign()); - //lv2 - assertEquals(2800, lv2CPr.getSz()); - assertEquals(28.0, r2.getFontSize(), 0); - lv2CPr.setSz(3300); - assertEquals(33.0, r2.getFontSize(), 0); - lv2CPr.getLatin().setTypeface("Times"); - assertEquals("Times", r2.getFontFamily()); - assertEquals(STTextAlignType.L, lv2PPr.getAlgn()); - assertEquals(TextAlign.LEFT, p2.getTextAlign()); - lv2PPr.setAlgn(STTextAlignType.R); - assertEquals(TextAlign.RIGHT, p2.getTextAlign()); - //lv3 - assertEquals(2400, lv3CPr.getSz()); - assertEquals(24.0, r3.getFontSize(), 0); - lv3CPr.setSz(2500); - assertEquals(25.0, r3.getFontSize(), 0); - lv3CPr.getLatin().setTypeface("Courier New"); - assertEquals("Courier New", r3.getFontFamily()); - assertEquals(STTextAlignType.L, lv3PPr.getAlgn()); - assertEquals(TextAlign.LEFT, p3.getTextAlign()); - lv3PPr.setAlgn(STTextAlignType.R); - assertEquals(TextAlign.RIGHT, p3.getTextAlign()); - - - // level 2: body placeholder on the master slide - // /p:sldMaster/p:cSld/p:spTree/p:sp/p:nvPr/p:ph[@type="body"] - XSLFTextShape tx2 = master.getPlaceholder(1); - assertEquals(Placeholder.BODY, tx2.getTextType()); - - lv1PPr = tx2.getTextBody(true).getLstStyle().addNewLvl1PPr(); - lv1CPr = lv1PPr.addNewDefRPr(); - lv2PPr = tx2.getTextBody(true).getLstStyle().addNewLvl2PPr(); - lv2CPr = lv2PPr.addNewDefRPr(); - lv3PPr = tx2.getTextBody(true).getLstStyle().addNewLvl3PPr(); - lv3CPr = lv3PPr.addNewDefRPr(); - - lv1CPr.setSz(3300); - assertEquals(33.0, r1.getFontSize(), 0); - lv1CPr.addNewLatin().setTypeface("Times"); - assertEquals("Times", r1.getFontFamily()); - lv1PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p1.getTextAlign()); - - lv2CPr.setSz(3300); - assertEquals(33.0, r2.getFontSize(), 0); - lv2CPr.addNewLatin().setTypeface("Times"); - assertEquals("Times", r2.getFontFamily()); - lv2PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p2.getTextAlign()); - - lv3CPr.setSz(3300); - assertEquals(33.0, r3.getFontSize(), 0); - lv3CPr.addNewLatin().setTypeface("Times"); - assertEquals("Times", r3.getFontFamily()); - lv3PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p3.getTextAlign()); - - // level 3: body placeholder on the slide layout - // /p:sldLayout /p:cSld/p:spTree/p:sp/p:nvPr/p:ph[@type="ctrTitle"] - XSLFTextShape tx3 = layout.getPlaceholder(1); - assertEquals(Placeholder.BODY, tx2.getTextType()); - lv1PPr = tx3.getTextBody(true).getLstStyle().addNewLvl1PPr(); - lv1CPr = lv1PPr.addNewDefRPr(); - lv2PPr = tx3.getTextBody(true).getLstStyle().addNewLvl2PPr(); - lv2CPr = lv2PPr.addNewDefRPr(); - lv3PPr = tx3.getTextBody(true).getLstStyle().addNewLvl3PPr(); - lv3CPr = lv3PPr.addNewDefRPr(); - - lv1CPr.setSz(3400); - assertEquals(34.0, r1.getFontSize(), 0); - lv1CPr.addNewLatin().setTypeface("Courier New"); - assertEquals("Courier New", r1.getFontFamily()); - lv1PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p1.getTextAlign()); - - lv2CPr.setSz(3400); - assertEquals(34.0, r2.getFontSize(), 0); - lv2CPr.addNewLatin().setTypeface("Courier New"); - assertEquals("Courier New", r2.getFontFamily()); - lv2PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p2.getTextAlign()); - - lv3CPr.setSz(3400); - assertEquals(34.0, r3.getFontSize(), 0); - lv3CPr.addNewLatin().setTypeface("Courier New"); - assertEquals("Courier New", r3.getFontFamily()); - lv3PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p3.getTextAlign()); - - // level 4: default text properties in the shape itself - // ./p:sp/p:txBody/a:lstStyle/a:lvl1pPr - lv1PPr = tx1.getTextBody(true).getLstStyle().addNewLvl1PPr(); - lv1CPr = lv1PPr.addNewDefRPr(); - lv2PPr = tx1.getTextBody(true).getLstStyle().addNewLvl2PPr(); - lv2CPr = lv2PPr.addNewDefRPr(); - lv3PPr = tx1.getTextBody(true).getLstStyle().addNewLvl3PPr(); - lv3CPr = lv3PPr.addNewDefRPr(); - - lv1CPr.setSz(3500); - assertEquals(35.0, r1.getFontSize(), 0); - lv1CPr.addNewLatin().setTypeface("Arial"); - assertEquals("Arial", r1.getFontFamily()); - lv1PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p1.getTextAlign()); - - lv2CPr.setSz(3500); - assertEquals(35.0, r2.getFontSize(), 0); - lv2CPr.addNewLatin().setTypeface("Arial"); - assertEquals("Arial", r2.getFontFamily()); - lv2PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p2.getTextAlign()); - - lv3CPr.setSz(3500); - assertEquals(35.0, r3.getFontSize(), 0); - lv3CPr.addNewLatin().setTypeface("Arial"); - assertEquals("Arial", r3.getFontFamily()); - lv3PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p3.getTextAlign()); - - // level 5: text properties are defined in the text run - lv1PPr = p1.getXmlObject().isSetPPr() ? p1.getXmlObject().getPPr() : p1.getXmlObject().addNewPPr(); - lv1CPr = r1.getRPr(false); - lv2PPr = p2.getXmlObject().isSetPPr() ? p2.getXmlObject().getPPr() : p2.getXmlObject().addNewPPr(); - lv2CPr = r2.getRPr(false); - lv3PPr = p3.getXmlObject().isSetPPr() ? p3.getXmlObject().getPPr() : p3.getXmlObject().addNewPPr(); - lv3CPr = r3.getRPr(false); - - lv1CPr.setSz(3600); - assertEquals(36.0, r1.getFontSize(), 0); - lv1CPr.addNewLatin().setTypeface("Calibri"); - assertEquals("Calibri", r1.getFontFamily()); - lv1PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p1.getTextAlign()); - - lv2CPr.setSz(3600); - assertEquals(36.0, r2.getFontSize(), 0); - lv2CPr.addNewLatin().setTypeface("Calibri"); - assertEquals("Calibri", r2.getFontFamily()); - lv2PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p2.getTextAlign()); - - lv3CPr.setSz(3600); - assertEquals(36.0, r3.getFontSize(), 0); - lv3CPr.addNewLatin().setTypeface("Calibri"); - assertEquals("Calibri", r3.getFontFamily()); - lv3PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p3.getTextAlign()); - - ppt.close(); - } - - @Test - void metroBlob() throws IOException, ReflectiveOperationException { - assumeFalse(xslfOnly); - File f = POIDataSamples.getSlideShowInstance().getFile("bug52297.ppt"); - SlideShow<?,?> ppt = SlideShowFactory.create(f); - Shape<?, ?> sh = ppt.getSlides().get(1).getShapes().get(3); - XSLFAutoShape xsh = (XSLFAutoShape)sh.getClass().getMethod("getMetroShape").invoke(sh); - String textExp = " ___ ___ ___ ________ __ _______ ___ ___________ __________ __ _____ ___ ___ ___ _______ ____ ______ ___________ _____________ ___ _______ ______ ____ ______ __ ___________ __________ ___ _________ _____ ________ __________ ___ _______ __________ "; - String textAct = xsh.getText(); - ppt.close(); - assertEquals(textExp, textAct); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTheme.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTheme.java deleted file mode 100644 index 54f66f6b8b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTheme.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.awt.Color; -import java.util.List; - -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.GradientPaint; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.PaintStyle.TexturePaint; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * test reading properties from a multi-theme and multi-master document - * - * @author Yegor Kozlov - */ -class TestXSLFTheme { - @Test - void testRead(){ - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("themes.pptx"); - List<XSLFSlide> slides = ppt.getSlides(); - - slide1(slides.get(0)); - slide2(slides.get(1)); - slide3(slides.get(2)); - slide4(slides.get(3)); - slide5(slides.get(4)); - slide6(slides.get(5)); - slide7(slides.get(6)); - slide8(slides.get(7)); - slide9(slides.get(8)); - slide10(slides.get(9)); - } - - private XSLFShape getShape(XSLFSheet sheet, String name){ - for(XSLFShape sh : sheet.getShapes()){ - if(sh.getShapeName().equals(name)) { - return sh; - } - } - throw new IllegalArgumentException("Shape not found: " + name); - } - - void slide1(XSLFSlide slide){ - assertEquals(Color.WHITE, slide.getBackground().getFillColor()); - - XSLFTheme theme = slide.getTheme(); - assertEquals("Office Theme", theme.getName()); - - XSLFTextShape sh1 = (XSLFTextShape)getShape(slide, "Rectangle 3"); - XSLFTextRun run1 = sh1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(Color.white, getColor(run1.getFontColor())); - assertEquals(new Color(79, 129, 189), sh1.getFillColor()); - assertTrue(sh1.getFillStyle().getPaint() instanceof SolidPaint) ; // solid fill - - } - - void slide2(XSLFSlide slide){ - // Background 2, darker 10% - // YK: PPT shows slightly different color: new Color(221, 217, 195) - assertEquals(new Color(221, 217, 195), slide.getBackground().getFillColor()); - } - - void slide3(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof GradientPaint); - } - - void slide4(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof GradientPaint); - - XSLFTextShape sh1 = (XSLFTextShape)getShape(slide, "Rectangle 4"); - XSLFTextRun run1 = sh1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(Color.white, getColor(run1.getFontColor())); - assertEquals(new Color(148, 198, 0), sh1.getFillColor()); - assertTrue(sh1.getFillStyle().getPaint() instanceof SolidPaint) ; // solid fill - - XSLFTextShape sh2 = (XSLFTextShape)getShape(slide, "Title 3"); - XSLFTextRun run2 = sh2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(new Color(148, 198, 0), getColor(run2.getFontColor())); - assertNull(sh2.getFillColor()); // no fill - - assertTrue(slide.getSlideLayout().getFollowMasterGraphics()); - } - - void slide5(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof TexturePaint); - - XSLFTextShape sh2 = (XSLFTextShape)getShape(slide, "Title 1"); - XSLFTextRun run2 = sh2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(new Color(148, 198, 0), getColor(run2.getFontColor())); - assertNull(sh2.getFillColor()); // no fill - // font size is 40pt and scale factor is 90% - assertEquals(36.0, run2.getFontSize(), 0); - - assertTrue(slide.getSlideLayout().getFollowMasterGraphics()); - } - - void slide6(XSLFSlide slide){ - - XSLFTextShape sh1 = (XSLFTextShape)getShape(slide, "Subtitle 3"); - XSLFTextRun run1 = sh1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(new Color(66, 66, 66), getColor(run1.getFontColor())); - assertNull(sh1.getFillColor()); // no fill - - XSLFTextShape sh2 = (XSLFTextShape)getShape(slide, "Title 2"); - XSLFTextRun run2 = sh2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(new Color(148, 198, 0), getColor(run2.getFontColor())); - assertNull(sh2.getFillColor()); // no fill - - assertFalse(slide.getSlideLayout().getFollowMasterGraphics()); - } - - void slide7(XSLFSlide slide){ - - //YK: PPT reports a slightly different color: r=189,g=239,b=87 - assertEquals(new Color(189, 239, 87), slide.getBackground().getFillColor()); - - assertFalse(slide.getFollowMasterGraphics()); - } - - void slide8(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof TexturePaint); - } - - void slide9(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof TexturePaint); - } - - void slide10(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof GradientPaint); - - XSLFTextShape sh1 = (XSLFTextShape)getShape(slide, "Title 3"); - XSLFTextRun run1 = sh1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(Color.white, getColor(run1.getFontColor())); - assertNull(sh1.getFillColor()); // no fill - - XSLFTextShape sh2 = (XSLFTextShape)getShape(slide, "Subtitle 4"); - XSLFTextRun run2 = sh2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(Color.white, getColor(run2.getFontColor())); - assertNull(sh2.getFillColor()); // no fill - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java b/src/ooxml/testcases/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java deleted file mode 100644 index 56c5efda1f..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.streaming.DeferredSXSSFSheet; -import org.apache.poi.xssf.streaming.DeferredSXSSFWorkbook; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; - -public final class DeferredSXSSFITestDataProvider implements ITestDataProvider { - public static final DeferredSXSSFITestDataProvider instance = new DeferredSXSSFITestDataProvider(); - - // an instance of all DeferredSXSSFWorkbooks opened by this TestDataProvider, - // so that the temporary files created can be disposed up by cleanup() - private final Collection<DeferredSXSSFWorkbook> instances = new ArrayList<>(); - - private DeferredSXSSFITestDataProvider() { - // enforce singleton - } - - @Override - public Workbook openSampleWorkbook(String sampleFileName) { - XSSFWorkbook xssfWorkbook = XSSFITestDataProvider.instance.openSampleWorkbook(sampleFileName); - DeferredSXSSFWorkbook swb = new DeferredSXSSFWorkbook(xssfWorkbook); - instances.add(swb); - return swb; - } - - /** - * Returns an XSSFWorkbook since SXSSFWorkbook is write-only - */ - @Override - public XSSFWorkbook writeOutAndReadBack(Workbook wb) { - // wb is usually an SXSSFWorkbook, but must also work on an XSSFWorkbook - // since workbooks must be able to be written out and read back - // several times in succession - if(!(wb instanceof SXSSFWorkbook || wb instanceof XSSFWorkbook)) { - throw new IllegalArgumentException("Expected an instance of XSSFWorkbook"); - } - - XSSFWorkbook result; - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); - wb.write(baos); - InputStream is = new ByteArrayInputStream(baos.toByteArray()); - result = new XSSFWorkbook(is); - } catch (IOException e) { - throw new RuntimeException(e); - } - return result; - } - - @Override - public DeferredSXSSFWorkbook createWorkbook() { - DeferredSXSSFWorkbook wb = new DeferredSXSSFWorkbook(); - instances.add(wb); - return wb; - } - - //************ SXSSF-specific methods ***************// - @Override - public DeferredSXSSFWorkbook createWorkbook(int rowAccessWindowSize) { - DeferredSXSSFWorkbook wb = new DeferredSXSSFWorkbook(rowAccessWindowSize); - instances.add(wb); - return wb; - } - - @Override - public void trackAllColumnsForAutosizing(Sheet sheet) { - ((DeferredSXSSFSheet)sheet).trackAllColumnsForAutoSizing(); - } - //************ End SXSSF-specific methods ***************// - - @Override - public FormulaEvaluator createFormulaEvaluator(Workbook wb) { - return new XSSFFormulaEvaluator(((DeferredSXSSFWorkbook) wb).getXSSFWorkbook()); - } - - @Override - public byte[] getTestDataFileContent(String fileName) { - return POIDataSamples.getSpreadSheetInstance().readFile(fileName); - } - - @Override - public SpreadsheetVersion getSpreadsheetVersion() { - return SpreadsheetVersion.EXCEL2007; - } - - @Override - public String getStandardFileNameExtension() { - return "xlsx"; - } - - public synchronized boolean cleanup() { - boolean ok = true; - for(final DeferredSXSSFWorkbook wb : instances) { - ok = ok && wb.dispose(); - } - instances.clear(); - return ok; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/SXSSFITestDataProvider.java b/src/ooxml/testcases/org/apache/poi/xssf/SXSSFITestDataProvider.java deleted file mode 100644 index 90de9c5977..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/SXSSFITestDataProvider.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * @author Yegor Kozlov - */ -public final class SXSSFITestDataProvider implements ITestDataProvider { - public static final SXSSFITestDataProvider instance = new SXSSFITestDataProvider(); - - // an instance of all SXSSFWorkbooks opened by this TestDataProvider, - // so that the temporary files created can be disposed up by cleanup() - private final Collection<SXSSFWorkbook> instances = new ArrayList<>(); - - private SXSSFITestDataProvider() { - // enforce singleton - } - - @Override - public Workbook openSampleWorkbook(String sampleFileName) { - XSSFWorkbook xssfWorkbook = XSSFITestDataProvider.instance.openSampleWorkbook(sampleFileName); - SXSSFWorkbook swb = new SXSSFWorkbook(xssfWorkbook); - instances.add(swb); - return swb; - } - - /** - * Returns an XSSFWorkbook since SXSSFWorkbook is write-only - */ - @Override - public XSSFWorkbook writeOutAndReadBack(Workbook wb) { - // wb is usually an SXSSFWorkbook, but must also work on an XSSFWorkbook - // since workbooks must be able to be written out and read back - // several times in succession - if(!(wb instanceof SXSSFWorkbook || wb instanceof XSSFWorkbook)) { - throw new IllegalArgumentException("Expected an instance of SXSSFWorkbook"); - } - - XSSFWorkbook result; - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); - wb.write(baos); - InputStream is = new ByteArrayInputStream(baos.toByteArray()); - result = new XSSFWorkbook(is); - } catch (IOException e) { - throw new RuntimeException(e); - } - return result; - } - - @Override - public SXSSFWorkbook createWorkbook() { - SXSSFWorkbook wb = new SXSSFWorkbook(); - instances.add(wb); - return wb; - } - - //************ SXSSF-specific methods ***************// - @Override - public SXSSFWorkbook createWorkbook(int rowAccessWindowSize) { - SXSSFWorkbook wb = new SXSSFWorkbook(rowAccessWindowSize); - instances.add(wb); - return wb; - } - - @Override - public void trackAllColumnsForAutosizing(Sheet sheet) { - ((SXSSFSheet)sheet).trackAllColumnsForAutoSizing(); - } - //************ End SXSSF-specific methods ***************// - - @Override - public FormulaEvaluator createFormulaEvaluator(Workbook wb) { - return new XSSFFormulaEvaluator(((SXSSFWorkbook) wb).getXSSFWorkbook()); - } - - @Override - public byte[] getTestDataFileContent(String fileName) { - return POIDataSamples.getSpreadSheetInstance().readFile(fileName); - } - - @Override - public SpreadsheetVersion getSpreadsheetVersion() { - return SpreadsheetVersion.EXCEL2007; - } - - @Override - public String getStandardFileNameExtension() { - return "xlsx"; - } - - public synchronized boolean cleanup() { - boolean ok = true; - for(final SXSSFWorkbook wb : instances) { - ok = ok && wb.dispose(); - } - instances.clear(); - return ok; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestNecessaryOOXMLClasses.java b/src/ooxml/testcases/org/apache/poi/xssf/TestNecessaryOOXMLClasses.java deleted file mode 100644 index db2a96a844..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestNecessaryOOXMLClasses.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPhoneticRun; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData; - -// aim is to get these classes loaded and included in poi-ooxml-lite.jar -class TestNecessaryOOXMLClasses { - - @Test - void testProblemClasses() { - CTRow row = CTRow.Factory.newInstance(); - CTSheetData sheetData = CTSheetData.Factory.newInstance(); - // need to get the inner class that implements the row list class loaded - assertTrue(sheetData.getRowList().add(row)); - assertTrue(sheetData.getRowList().iterator().hasNext()); - //important class missing in v5.0.0 poi-ooxml-lite - CTPhoneticRun run = CTPhoneticRun.Factory.newInstance(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java b/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java deleted file mode 100644 index f3459af7dc..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java +++ /dev/null @@ -1,293 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf; - -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class TestSheetProtection { - private XSSFWorkbook workbook; - private XSSFSheet sheet; - - @BeforeEach - void setUp() { - workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_not_protected.xlsx"); - sheet = workbook.getSheetAt(0); - } - - @AfterEach - void tearDown() throws IOException { - workbook.close(); - } - - @Test - void testShouldReadWorkbookProtection() throws IOException { - assertFalse(sheet.isAutoFilterLocked()); - assertFalse(sheet.isDeleteColumnsLocked()); - assertFalse(sheet.isDeleteRowsLocked()); - assertFalse(sheet.isFormatCellsLocked()); - assertFalse(sheet.isFormatColumnsLocked()); - assertFalse(sheet.isFormatRowsLocked()); - assertFalse(sheet.isInsertColumnsLocked()); - assertFalse(sheet.isInsertHyperlinksLocked()); - assertFalse(sheet.isInsertRowsLocked()); - assertFalse(sheet.isPivotTablesLocked()); - assertFalse(sheet.isSortLocked()); - assertFalse(sheet.isObjectsLocked()); - assertFalse(sheet.isScenariosLocked()); - assertFalse(sheet.isSelectLockedCellsLocked()); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - assertFalse(sheet.isSheetLocked()); - - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx")) { - sheet = workbook.getSheetAt(0); - - assertTrue(sheet.isAutoFilterLocked()); - assertTrue(sheet.isDeleteColumnsLocked()); - assertTrue(sheet.isDeleteRowsLocked()); - assertTrue(sheet.isFormatCellsLocked()); - assertTrue(sheet.isFormatColumnsLocked()); - assertTrue(sheet.isFormatRowsLocked()); - assertTrue(sheet.isInsertColumnsLocked()); - assertTrue(sheet.isInsertHyperlinksLocked()); - assertTrue(sheet.isInsertRowsLocked()); - assertTrue(sheet.isPivotTablesLocked()); - assertTrue(sheet.isSortLocked()); - assertTrue(sheet.isObjectsLocked()); - assertTrue(sheet.isScenariosLocked()); - assertTrue(sheet.isSelectLockedCellsLocked()); - assertTrue(sheet.isSelectUnlockedCellsLocked()); - assertTrue(sheet.isSheetLocked()); - } - } - - @Test - void testWriteAutoFilter() { - assertFalse(sheet.isAutoFilterLocked()); - sheet.lockAutoFilter(true); - assertFalse(sheet.isAutoFilterLocked()); - sheet.enableLocking(); - assertTrue(sheet.isAutoFilterLocked()); - sheet.lockAutoFilter(false); - assertFalse(sheet.isAutoFilterLocked()); - } - - @Test - void testWriteDeleteColumns() { - assertFalse(sheet.isDeleteColumnsLocked()); - sheet.lockDeleteColumns(true); - assertFalse(sheet.isDeleteColumnsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isDeleteColumnsLocked()); - sheet.lockDeleteColumns(false); - assertFalse(sheet.isDeleteColumnsLocked()); - } - - @Test - void testWriteDeleteRows() { - assertFalse(sheet.isDeleteRowsLocked()); - sheet.lockDeleteRows(true); - assertFalse(sheet.isDeleteRowsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isDeleteRowsLocked()); - sheet.lockDeleteRows(false); - assertFalse(sheet.isDeleteRowsLocked()); - } - - @Test - void testWriteFormatCells() { - assertFalse(sheet.isFormatCellsLocked()); - sheet.lockFormatCells(true); - assertFalse(sheet.isFormatCellsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isFormatCellsLocked()); - sheet.lockFormatCells(false); - assertFalse(sheet.isFormatCellsLocked()); - } - - @Test - void testWriteFormatColumns() { - assertFalse(sheet.isFormatColumnsLocked()); - sheet.lockFormatColumns(true); - assertFalse(sheet.isFormatColumnsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isFormatColumnsLocked()); - sheet.lockFormatColumns(false); - assertFalse(sheet.isFormatColumnsLocked()); - } - - @Test - void testWriteFormatRows() { - assertFalse(sheet.isFormatRowsLocked()); - sheet.lockFormatRows(true); - assertFalse(sheet.isFormatRowsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isFormatRowsLocked()); - sheet.lockFormatRows(false); - assertFalse(sheet.isFormatRowsLocked()); - } - - @Test - void testWriteInsertColumns() { - assertFalse(sheet.isInsertColumnsLocked()); - sheet.lockInsertColumns(true); - assertFalse(sheet.isInsertColumnsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isInsertColumnsLocked()); - sheet.lockInsertColumns(false); - assertFalse(sheet.isInsertColumnsLocked()); - } - - @Test - void testWriteInsertHyperlinks() { - assertFalse(sheet.isInsertHyperlinksLocked()); - sheet.lockInsertHyperlinks(true); - assertFalse(sheet.isInsertHyperlinksLocked()); - sheet.enableLocking(); - assertTrue(sheet.isInsertHyperlinksLocked()); - sheet.lockInsertHyperlinks(false); - assertFalse(sheet.isInsertHyperlinksLocked()); - } - - @Test - void testWriteInsertRows() { - assertFalse(sheet.isInsertRowsLocked()); - sheet.lockInsertRows(true); - assertFalse(sheet.isInsertRowsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isInsertRowsLocked()); - sheet.lockInsertRows(false); - assertFalse(sheet.isInsertRowsLocked()); - } - - @Test - void testWritePivotTables() { - assertFalse(sheet.isPivotTablesLocked()); - sheet.lockPivotTables(true); - assertFalse(sheet.isPivotTablesLocked()); - sheet.enableLocking(); - assertTrue(sheet.isPivotTablesLocked()); - sheet.lockPivotTables(false); - assertFalse(sheet.isPivotTablesLocked()); - } - - @Test - void testWriteSort() { - assertFalse(sheet.isSortLocked()); - sheet.lockSort(true); - assertFalse(sheet.isSortLocked()); - sheet.enableLocking(); - assertTrue(sheet.isSortLocked()); - sheet.lockSort(false); - assertFalse(sheet.isSortLocked()); - } - - @Test - void testWriteObjects() { - assertFalse(sheet.isObjectsLocked()); - sheet.lockObjects(true); - assertFalse(sheet.isObjectsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isObjectsLocked()); - sheet.lockObjects(false); - assertFalse(sheet.isObjectsLocked()); - } - - @Test - void testWriteScenarios() { - assertFalse(sheet.isScenariosLocked()); - sheet.lockScenarios(true); - assertFalse(sheet.isScenariosLocked()); - sheet.enableLocking(); - assertTrue(sheet.isScenariosLocked()); - sheet.lockScenarios(false); - assertFalse(sheet.isScenariosLocked()); - } - - @Test - void testWriteSelectLockedCells() { - assertFalse(sheet.isSelectLockedCellsLocked()); - sheet.lockSelectLockedCells(true); - assertFalse(sheet.isSelectLockedCellsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isSelectLockedCellsLocked()); - sheet.lockSelectLockedCells(false); - assertFalse(sheet.isSelectLockedCellsLocked()); - } - - @Test - void testWriteSelectUnlockedCells() { - assertFalse(sheet.isSelectUnlockedCellsLocked()); - sheet.lockSelectUnlockedCells(true); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isSelectUnlockedCellsLocked()); - sheet.lockSelectUnlockedCells(false); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - } - - @Test - void testWriteSelectEnableLocking() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx")) { - sheet = workbook.getSheetAt(0); - - assertTrue(sheet.isAutoFilterLocked()); - assertTrue(sheet.isDeleteColumnsLocked()); - assertTrue(sheet.isDeleteRowsLocked()); - assertTrue(sheet.isFormatCellsLocked()); - assertTrue(sheet.isFormatColumnsLocked()); - assertTrue(sheet.isFormatRowsLocked()); - assertTrue(sheet.isInsertColumnsLocked()); - assertTrue(sheet.isInsertHyperlinksLocked()); - assertTrue(sheet.isInsertRowsLocked()); - assertTrue(sheet.isPivotTablesLocked()); - assertTrue(sheet.isSortLocked()); - assertTrue(sheet.isObjectsLocked()); - assertTrue(sheet.isScenariosLocked()); - assertTrue(sheet.isSelectLockedCellsLocked()); - assertTrue(sheet.isSelectUnlockedCellsLocked()); - assertTrue(sheet.isSheetLocked()); - - sheet.disableLocking(); - - assertFalse(sheet.isAutoFilterLocked()); - assertFalse(sheet.isDeleteColumnsLocked()); - assertFalse(sheet.isDeleteRowsLocked()); - assertFalse(sheet.isFormatCellsLocked()); - assertFalse(sheet.isFormatColumnsLocked()); - assertFalse(sheet.isFormatRowsLocked()); - assertFalse(sheet.isInsertColumnsLocked()); - assertFalse(sheet.isInsertHyperlinksLocked()); - assertFalse(sheet.isInsertRowsLocked()); - assertFalse(sheet.isPivotTablesLocked()); - assertFalse(sheet.isSortLocked()); - assertFalse(sheet.isObjectsLocked()); - assertFalse(sheet.isScenariosLocked()); - assertFalse(sheet.isSelectLockedCellsLocked()); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - assertFalse(sheet.isSheetLocked()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java b/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java deleted file mode 100644 index 11c4ff20d7..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java +++ /dev/null @@ -1,247 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf; - -import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook; -import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.OutputStream; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.Encryptor; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -class TestWorkbookProtection { - - @Test - void workbookAndRevisionPassword() throws Exception { - String password = "test"; - - // validate password with an actual office file (Excel 2010) - try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection-workbook_password_user_range-2010.xlsx")) { - assertTrue(workbook.validateWorkbookPassword(password)); - } - - // validate with another office file (Excel 2013) - try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection-workbook_password-2013.xlsx")){ - assertTrue(workbook.validateWorkbookPassword(password)); - } - - - try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx")) { - // setting a null password shouldn't introduce the protection element - workbook.setWorkbookPassword(null, null); - assertNull(workbook.getCTWorkbook().getWorkbookProtection()); - - // compare the hashes - workbook.setWorkbookPassword(password, null); - int hashVal = CryptoFunctions.createXorVerifier1(password); - int actualVal = Integer.parseInt(workbook.getCTWorkbook().getWorkbookProtection().xgetWorkbookPassword().getStringValue(), 16); - assertEquals(hashVal, actualVal); - assertTrue(workbook.validateWorkbookPassword(password)); - - // removing the password again - workbook.setWorkbookPassword(null, null); - assertFalse(workbook.getCTWorkbook().getWorkbookProtection().isSetWorkbookPassword()); - - // removing the whole protection structure - workbook.unLock(); - assertNull(workbook.getCTWorkbook().getWorkbookProtection()); - - // setting a null password shouldn't introduce the protection element - workbook.setRevisionsPassword(null, null); - assertNull(workbook.getCTWorkbook().getWorkbookProtection()); - - // compare the hashes - password = "T\u0400ST\u0100passwordWhichIsLongerThan15Chars"; - workbook.setRevisionsPassword(password, null); - hashVal = CryptoFunctions.createXorVerifier1(password); - actualVal = Integer.parseInt(workbook.getCTWorkbook().getWorkbookProtection().xgetRevisionsPassword().getStringValue(), 16); - assertEquals(hashVal, actualVal); - assertTrue(workbook.validateRevisionsPassword(password)); - } - } - - @Test - void shouldReadWorkbookProtection() throws Exception { - try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx")) { - assertFalse(workbook.isStructureLocked()); - assertFalse(workbook.isWindowsLocked()); - assertFalse(workbook.isRevisionLocked()); - } - - try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_workbook_structure_protected.xlsx")) { - assertTrue(workbook.isStructureLocked()); - assertFalse(workbook.isWindowsLocked()); - assertFalse(workbook.isRevisionLocked()); - } - - try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_workbook_windows_protected.xlsx")) { - assertTrue(workbook.isWindowsLocked()); - assertFalse(workbook.isStructureLocked()); - assertFalse(workbook.isRevisionLocked()); - } - - try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_workbook_revision_protected.xlsx")) { - assertTrue(workbook.isRevisionLocked()); - assertFalse(workbook.isWindowsLocked()); - assertFalse(workbook.isStructureLocked()); - } - } - - @Test - void shouldWriteStructureLock() throws Exception { - try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx")) { - assertFalse(workbook.isStructureLocked()); - - workbook.lockStructure(); - - assertTrue(workbook.isStructureLocked()); - - workbook.unLockStructure(); - - assertFalse(workbook.isStructureLocked()); - } - } - - @Test - void shouldWriteWindowsLock() throws Exception { - try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx")) { - assertFalse(workbook.isWindowsLocked()); - - workbook.lockWindows(); - - assertTrue(workbook.isWindowsLocked()); - - workbook.unLockWindows(); - - assertFalse(workbook.isWindowsLocked()); - } - } - - @Test - void shouldWriteRevisionLock() throws Exception { - try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx")) { - assertFalse(workbook.isRevisionLocked()); - - workbook.lockRevision(); - - assertTrue(workbook.isRevisionLocked()); - - workbook.unLockRevision(); - - assertFalse(workbook.isRevisionLocked()); - } - } - - @SuppressWarnings("resource") - @Test - void testHashPassword() throws Exception { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - wb.lockRevision(); - wb.setRevisionsPassword("test", HashAlgorithm.sha1); - - try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) { - - assertTrue(wbBack.isRevisionLocked()); - assertTrue(wbBack.validateRevisionsPassword("test")); - } - } - } - - @SuppressWarnings("resource") - @Test - void testIntegration() throws Exception { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - wb.createSheet("Testing purpose sheet"); - assertFalse(wb.isRevisionLocked()); - - wb.lockRevision(); - wb.setRevisionsPassword("test", null); - - try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) { - - assertTrue(wbBack.isRevisionLocked()); - assertTrue(wbBack.validateRevisionsPassword("test")); - } - } - } - - @Test - void testEncryptDecrypt() throws Exception { - final String password = "abc123"; - final String sheetName = "TestSheet1"; - final String cellValue = "customZipEntrySource"; - try (XSSFWorkbook workbook = new XSSFWorkbook()) { - XSSFSheet sheet1 = workbook.createSheet(sheetName); - XSSFRow row1 = sheet1.createRow(1); - XSSFCell cell1 = row1.createCell(1); - cell1.setCellValue(cellValue); - File tf1 = TempFile.createTempFile("poitest", ".xlsx"); - FileOutputStream fos1 = new FileOutputStream(tf1); - workbook.write(fos1); - IOUtils.closeQuietly(fos1); - POIFSFileSystem poiFileSystem = new POIFSFileSystem(); - EncryptionInfo encryptionInfo = new EncryptionInfo(EncryptionMode.agile); - Encryptor enc = encryptionInfo.getEncryptor(); - enc.confirmPassword(password); - FileInputStream fis = new FileInputStream(tf1); - OPCPackage opc = OPCPackage.open(fis); - IOUtils.closeQuietly(fis); - try { - OutputStream os = enc.getDataStream(poiFileSystem); - opc.save(os); - IOUtils.closeQuietly(os); - } finally { - IOUtils.closeQuietly(opc); - } - assertTrue(tf1.delete()); - FileOutputStream fos2 = new FileOutputStream(tf1); - poiFileSystem.writeFilesystem(fos2); - IOUtils.closeQuietly(fos2); - workbook.close(); - fis = new FileInputStream(tf1); - POIFSFileSystem poiFileSystem2 = new POIFSFileSystem(fis); - IOUtils.closeQuietly(fis); - EncryptionInfo encryptionInfo2 = new EncryptionInfo(poiFileSystem2); - Decryptor decryptor = encryptionInfo2.getDecryptor(); - decryptor.verifyPassword(password); - XSSFWorkbook workbook2 = new XSSFWorkbook(decryptor.getDataStream(poiFileSystem2)); - workbook2.close(); - assertTrue(tf1.delete()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFCloneSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFCloneSheet.java deleted file mode 100644 index b3c2896fd8..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFCloneSheet.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestCloneSheet; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xddf.usermodel.chart.XDDFDataSource; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.IOException; - -class TestXSSFCloneSheet extends BaseTestCloneSheet { - public TestXSSFCloneSheet() { - super(HSSFITestDataProvider.instance); - } - - private static final String OTHER_SHEET_NAME = "Another"; - private static final String VALID_SHEET_NAME = "Sheet01"; - private XSSFWorkbook wb; - - @BeforeEach - void setUp() { - wb = new XSSFWorkbook(); - wb.createSheet(VALID_SHEET_NAME); - } - - @Test - void testCloneSheetIntStringValidName() { - XSSFSheet cloned = wb.cloneSheet(0, OTHER_SHEET_NAME); - assertEquals(OTHER_SHEET_NAME, cloned.getSheetName()); - assertEquals(2, wb.getNumberOfSheets()); - } - - @Test - void testCloneSheetIntStringInvalidName() { - assertThrows(IllegalArgumentException.class, () -> wb.cloneSheet(0, VALID_SHEET_NAME)); - assertEquals(1, wb.getNumberOfSheets()); - } - - @Test - void test60512() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("60512.xlsm"); - - assertEquals(1, wb.getNumberOfSheets()); - Sheet sheet = wb.cloneSheet(0); - assertNotNull(sheet); - assertEquals(2, wb.getNumberOfSheets()); - - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wbBack); - wbBack.close(); - - wb.close(); - } - - @Test - void test61605() throws IOException { - try (Workbook template_wb = XSSFTestDataSamples.openSampleWorkbook("61605.xlsx")) { - Sheet template_sh = template_wb.getSheetAt(0); - assertNotNull(template_sh); - Sheet source_sh = template_wb.cloneSheet(0); - assertNotNull(source_sh); - } - } - - @Test - void testBug63902() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("chartTitle_withTitle.xlsx")) { - XSSFSheet sheet = workbook.getSheetAt(0); - XSSFDrawing drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getCharts().size()); - - XSSFSheet sheet2 = workbook.cloneSheet(0, "Sheet 2"); - XSSFDrawing drawing2 = sheet2.getDrawingPatriarch(); - assertEquals(1, drawing2.getCharts().size()); - assertEquals("Sheet 2", sheet2.getSheetName()); - - XDDFDataSource<?> data = drawing.getCharts().get(0).getChartSeries().get(0).getSeries(0).getCategoryData(); - XDDFDataSource<?> data2 = drawing2.getCharts().get(0).getChartSeries().get(0).getSeries(0).getCategoryData(); - assertNotEquals(data.getFormula(), data2.getFormula()); - assertEquals(sheet.getSheetName(), data.getFormula().substring(0, data.getFormula().indexOf('!'))); - assertEquals("'Sheet 2'", data2.getFormula().substring(0, data2.getFormula().indexOf('!'))); - assertEquals( - data.getFormula().substring(data.getFormula().indexOf('!')), - data2.getFormula().substring(data2.getFormula().indexOf('!')) - ); - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook, "poi_cloned_sheet_with_chart"); - assertNotNull(wbBack); - wbBack.close(); - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFMemoryLeak.java b/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFMemoryLeak.java deleted file mode 100644 index bb9859998c..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFMemoryLeak.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf; - -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 java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ooxml.POIXMLException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.MemoryLeakVerifier; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; - -/** - * A test which uses {@link MemoryLeakVerifier} to ensure that certain - * objects are not left over in memory after the test. - * - * E.g. verifies that objects are freed when stuff is removed from sheets or rows - */ -public class TestXSSFMemoryLeak { - private final MemoryLeakVerifier verifier = new MemoryLeakVerifier(); - - // keep some items in memory, so checks in tearDown() actually - // verify that they do not keep certain objects in memory, - // e.g. nested CT... objects which should be released - @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") - private final List<Object> references = new ArrayList<>(); - - @AfterEach - void tearDown() { - verifier.assertGarbageCollected(); - } - - @Test - void testWriteRow() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - final XSSFSheet sheet1 = wb.createSheet("Sheet1"); - final XSSFRow row = sheet1.createRow(0); - final XSSFCell cell = row.createCell(0); - cell.setCellValue("hello"); - - // Cannot check the CTCell here as it is reused now and thus - // not freed until we free up the Cell itself - //verifier.addObject(ctCell); - - try (OutputStream out = new ByteArrayOutputStream(8192)) { - wb.write(out); - } - - CTCell ctCell = cell.getCTCell(); - assertSame(cell.getCTCell(), ctCell, "The CTCell should not be replaced"); - assertSame(row.getCTRow().getCArray(0), ctCell, "The CTCell in the row should not be replaced"); - } - } - - @Test - void testRemoveCellFromRow() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - final XSSFSheet sheet1 = wb.createSheet("Sheet1"); - final XSSFRow rowToCheck = sheet1.createRow(0); - references.add(rowToCheck); - - XSSFCell cell = rowToCheck.createCell(0); - cell.setCellValue("hello"); - - // previously the CTCell was still referenced in the CTRow, verify that it is freed - verifier.addObject(cell); - verifier.addObject(cell.getCTCell()); - - rowToCheck.removeCell(cell); - - assertNull(rowToCheck.getCell(0)); - } - } - - @Test - void testRemove2CellsFromRow() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - final XSSFSheet sheet1 = wb.createSheet("Sheet1"); - final XSSFRow rowToCheck = sheet1.createRow(0); - references.add(rowToCheck); - - XSSFCell cell1 = rowToCheck.createCell(0); - cell1.setCellValue("hello"); - XSSFCell cell2 = rowToCheck.createCell(1); - cell2.setCellValue("world"); - - // previously the CTCell was still referenced in the CTRow, verify that it is freed - verifier.addObject(cell1); - verifier.addObject(cell1.getCTCell()); - verifier.addObject(cell2); - verifier.addObject(cell2.getCTCell()); - - rowToCheck.removeCell(cell2); - rowToCheck.removeCell(cell1); - - assertNull(rowToCheck.getCell(0)); - assertNull(rowToCheck.getCell(1)); - } - } - - @Test - void testRemoveRowFromSheet() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - final XSSFSheet sheetToCheck = wb1.createSheet("Sheet1"); - references.add(sheetToCheck); - final XSSFRow row = sheetToCheck.createRow(0); - final XSSFCell cell = row.createCell(0); - cell.setCellValue(1); - - // ensure that the row-data is not kept somewhere in another member - verifier.addObject(row.getCTRow()); - verifier.addObject(row); - verifier.addObject(cell.getCTCell()); - verifier.addObject(cell); - - sheetToCheck.removeRow(row); - - assertNull(sheetToCheck.getRow(0)); - } - } - - @Test - void testFileLeak() { - File file = XSSFTestDataSamples.getSampleFile("xlsx-corrupted.xlsx"); - verifier.addObject(file); - assertThrows(POIXMLException.class, () -> new XSSFWorkbook(file), "Should catch exception as the file is corrupted"); - } - - @Test - void testFileLeak2() throws IOException, InvalidFormatException { - File file = XSSFTestDataSamples.getSampleFile("xlsx-corrupted.xlsx"); - verifier.addObject(file); - try (OPCPackage pkg = OPCPackage.open(file)) { - assertThrows(POIXMLException.class, () -> new XSSFWorkbook(pkg), "Should catch exception as the file is corrupted"); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFOffset.java b/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFOffset.java deleted file mode 100644 index b39c33bce0..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFOffset.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class TestXSSFOffset { - - @Test - void testOffsetWithEmpty23Arguments() throws IOException { - try (Workbook workbook = new XSSFWorkbook()) { - Cell cell = workbook.createSheet().createRow(0).createCell(0); - cell.setCellFormula("OFFSET(B1,,)"); - - String value = "EXPECTED_VALUE"; - Cell valueCell = cell.getRow().createCell(1); - valueCell.setCellValue(value); - - workbook.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - assertEquals(CellType.STRING, cell.getCachedFormulaResultType()); - assertEquals(value, cell.getStringCellValue()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/XSSFITestDataProvider.java b/src/ooxml/testcases/org/apache/poi/xssf/XSSFITestDataProvider.java deleted file mode 100644 index e0ba6617ca..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/XSSFITestDataProvider.java +++ /dev/null @@ -1,86 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * @author Yegor Kozlov - */ -public final class XSSFITestDataProvider implements ITestDataProvider { - public static final XSSFITestDataProvider instance = new XSSFITestDataProvider(); - - private XSSFITestDataProvider() { - // enforce singleton - } - - @Override - public XSSFWorkbook openSampleWorkbook(String sampleFileName) { - return XSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - @Override - public XSSFWorkbook writeOutAndReadBack(Workbook original) { - if(!(original instanceof XSSFWorkbook)) { - throw new IllegalArgumentException("Expected an instance of XSSFWorkbook, but had " + original.getClass()); - } - return XSSFTestDataSamples.writeOutAndReadBack((XSSFWorkbook)original); - } - - @Override - public XSSFWorkbook createWorkbook() { - return new XSSFWorkbook(); - } - - //************ SXSSF-specific methods ***************// - @Override - public XSSFWorkbook createWorkbook(int rowAccessWindowSize) { - return createWorkbook(); - } - - @Override - public void trackAllColumnsForAutosizing(Sheet sheet) {} - //************ End SXSSF-specific methods ***************// - - @Override - public FormulaEvaluator createFormulaEvaluator(Workbook wb) { - return new XSSFFormulaEvaluator((XSSFWorkbook) wb); - } - - @Override - public byte[] getTestDataFileContent(String fileName) { - return POIDataSamples.getSpreadSheetInstance().readFile(fileName); - } - - @Override - public SpreadsheetVersion getSpreadsheetVersion(){ - return SpreadsheetVersion.EXCEL2007; - } - - @Override - public String getStandardFileNameExtension() { - return "xlsx"; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/XSSFTestDataSamples.java b/src/ooxml/testcases/org/apache/poi/xssf/XSSFTestDataSamples.java deleted file mode 100644 index b981b9994e..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/XSSFTestDataSamples.java +++ /dev/null @@ -1,295 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Centralises logic for finding/opening sample files in the test-data/spreadsheet folder. - * - * @author Josh Micich - */ -public class XSSFTestDataSamples { - /** - * Used by {@link #writeOutAndReadBack(Workbook, String)}. If a - * value is set for this in the System Properties, the xlsx file - * will be written out to that directory. - */ - public static final String TEST_OUTPUT_DIR = "poi.test.xssf.output.dir"; - - public static File getSampleFile(String sampleFileName) { - return HSSFTestDataSamples.getSampleFile(sampleFileName); - } - public static OPCPackage openSamplePackage(String sampleName) { - try { - return OPCPackage.open(HSSFTestDataSamples.openSampleFileStream(sampleName)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - public static XSSFWorkbook openSampleWorkbook(String sampleName) { - InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleName); - try { - return new XSSFWorkbook(is); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Write out workbook <code>wb</code> to {@link #TEST_OUTPUT_DIR}/testName.xlsx - * (or create a temporary file if <code>TEST_OUTPUT_DIR</code> is not defined). - * - * @param wb the workbook to write - * @param testName a fragment of the filename - * @return the location where the workbook was saved - * @throws IOException If writing the file fails - */ - public static <R extends Workbook> File writeOut(R wb, String testName) throws IOException { - final File file = getOutputFile(testName); - writeOut(wb, file); - return file; - } - - private static <R extends Workbook> void writeOut(R wb, File file) throws IOException { - try (FileOutputStream out = new FileOutputStream(file)) { - wb.write(out); - } - } - - // Anticipates the location of where a workbook will be written to - // Note that if TEST_OUTPUT_DIR is not set, this will create temporary files - // with unique names. Subsequent calls with the same argument may return a different file. - // Gets a test data sample file, deleting the file if it exists. - // This is used in preparation for writing a workbook out to the returned output file. - // testName is a filename fragment and should not include the extension - private static File getOutputFile(String testName) throws IOException { - final String testOutputDir = System.getProperty(TEST_OUTPUT_DIR); - final File file; - if (testOutputDir != null) { - // In case user provided testName with a file extension, don't repeat the file extension a second time - final String testNameWithExtension = testName.endsWith(".xlsx") ? testName : testName + ".xlsx"; - // FIXME: may want to defer to the TempFile with a persistent file creation strategy to the test output dir - // This would add the random value in the middle of the filename so that test runs wouldn't overwrite files - file = new File(testOutputDir, testNameWithExtension); - } - else { - file = TempFile.createTempFile(testName, ".xlsx"); - } - if (file.exists()) { - if(!file.delete()) { - throw new IOException("Could not delete file " + file); - } - } - return file; - } - - /** - * Write out workbook <code>wb</code> to a memory buffer - * - * @param wb the workbook to write - * @return the memory buffer - * @throws IOException If writing the file fails - */ - public static <R extends Workbook> ByteArrayOutputStream writeOut(R wb) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(8192); - wb.write(out); - return out; - } - - /** - * Write out the workbook then closes the workbook. - * This should be used when there is insufficient memory to have - * both workbooks open. - * - * Make sure there are no references to any objects in the workbook - * so that garbage collection may free the workbook. - * - * After calling this method, null the reference to <code>wb</code>, - * then call {@link #readBack(File)} or {@link #readBackAndDelete(File)} to re-read the file. - * - * Alternatively, use {@link #writeOutAndClose(Workbook)} to use a ByteArrayOutputStream/ByteArrayInputStream - * to avoid creating a temporary file. However, this may complicate the calling - * code to avoid having the workbook, BAOS, and BAIS open at the same time. - * - * @param wb The workbook to write out, it is closed after the call. - * @param testName file name to be used to write to a file. This file will be cleaned up by a call to readBack(String) - * @return workbook location - * @throws RuntimeException if {@link #TEST_OUTPUT_DIR} System property is not set - */ - public static <R extends Workbook> File writeOutAndClose(R wb, String testName) { - try { - File file = writeOut(wb, testName); - // Do not close the workbook if there was a problem writing the workbook - wb.close(); - return file; - } - catch (final IOException e) { - throw new RuntimeException(e); - } - } - - - /** - * Write out workbook <code>wb</code> to a memory buffer, - * then close the workbook - * - * @param wb the workbook to write - * @return the memory buffer - * @throws RuntimeException If writing the file fails - */ - public static <R extends Workbook> ByteArrayOutputStream writeOutAndClose(R wb) throws IOException { - ByteArrayOutputStream out = writeOut(wb); - // Do not close the workbook if there was a problem writing the workbook - wb.close(); - return out; - } - - /** - * Read back a workbook that was written out to a file with - * {@link #writeOut(Workbook, String))} or {@link #writeOutAndClose(Workbook, String)}. - * Deletes the file after reading back the file. - * Does not delete the file if an exception is raised. - * - * @param file the workbook file to read and delete - * @return the read back workbook - * @throws IOException If reading or deleting the file fails - */ - public static XSSFWorkbook readBackAndDelete(File file) throws IOException { - XSSFWorkbook wb = readBack(file); - // do not delete the file if there's an error--might be helpful for debugging - if(!file.delete()) { - throw new IOException("Could not delete file " + file + " after reading"); - } - return wb; - } - - /** - * Read back a workbook that was written out to a file with - * {@link #writeOut(Workbook, String)} or {@link #writeOutAndClose(Workbook, String)}. - * - * @param file the workbook file to read - * @return the read back workbook - * @throws IOException If reading the file fails - */ - public static XSSFWorkbook readBack(File file) throws IOException { - try (InputStream in = new FileInputStream(file)) { - return new XSSFWorkbook(in); - } - } - - /** - * Read back a workbook that was written out to a memory buffer with - * {@link #writeOut(Workbook)} or {@link #writeOutAndClose(Workbook)}. - * - * @param out the output stream to read back from - * @return the read back workbook - * @throws IOException If reading the file fails - */ - public static XSSFWorkbook readBack(ByteArrayOutputStream out) throws IOException { - try (InputStream is = new ByteArrayInputStream(out.toByteArray())) { - out.close(); - return new XSSFWorkbook(is); - } - } - - /** - * Write out and read back using a memory buffer to avoid disk I/O. - * If there is not enough memory to have two workbooks open at the same time, - * consider using: - * - * Workbook wb = new XSSFWorkbook(); - * String testName = "example"; - * - * <code> - * File file = writeOutAndClose(wb, testName); - * // clear all references that would prevent the workbook from getting garbage collected - * wb = null; - * Workbook wbBack = readBackAndDelete(file); - * </code> - * - * @param wb the workbook to write out - * @return the read back workbook - */ - public static <R extends Workbook> R writeOutAndReadBack(R wb) { - Workbook result; - try { - result = readBack(writeOut(wb)); - } catch (IOException e) { - throw new RuntimeException(e); - } - @SuppressWarnings("unchecked") - R r = (R) result; - return r; - } - - /** - * Write out, close, and read back the workbook using a memory buffer to avoid disk I/O. - * - * @param wb the workbook to write out and close - * @return the read back workbook - */ - public static <R extends Workbook> R writeOutCloseAndReadBack(R wb) { - Workbook result; - try { - result = readBack(writeOutAndClose(wb)); - } catch (IOException e) { - throw new RuntimeException(e); - } - @SuppressWarnings("unchecked") - R r = (R) result; - return r; - - } - - /** - * Writes the Workbook either into a file or into a byte array, depending on presence of - * the system property {@value #TEST_OUTPUT_DIR}, and reads it in a new instance of the Workbook back. - * If TEST_OUTPUT_DIR is set, the file will NOT be deleted at the end of this function. - * @param wb workbook to write - * @param testName file name to be used if writing into a file. The old file with the same name will be overridden. - * @return new instance read from the stream written by the wb parameter. - */ - - public static <R extends Workbook> R writeOutAndReadBack(R wb, String testName) { - if (System.getProperty(TEST_OUTPUT_DIR) == null) { - return writeOutAndReadBack(wb); - } else { - try { - Workbook result = readBack(writeOut(wb, testName)); - @SuppressWarnings("unchecked") - R r = (R) result; - return r; - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java deleted file mode 100644 index 7a56829584..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.List; -import java.util.regex.Pattern; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.junit.jupiter.api.Test; - -class TestXSSFBSharedStringsTable { - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - - @Test - void testBasic() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("51519.xlsb"))) { - List<PackagePart> parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.bin")); - assertEquals(1, parts.size()); - - XSSFBSharedStringsTable rtbl = new XSSFBSharedStringsTable(parts.get(0)); - - assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getItemAt(0).getString()); - assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB", rtbl.getItemAt(3).getString()); - assertEquals(55, rtbl.getCount()); - assertEquals(49, rtbl.getUniqueCount()); - - //TODO: add in tests for phonetic runs - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java deleted file mode 100644 index 6fd654df31..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.xssf.eventusermodel.XSSFBReader; -import org.apache.poi.xssf.eventusermodel.XSSFReader; -import org.junit.jupiter.api.Test; - -class TestXSSFBSheetHyperlinkManager { - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - - @Test - void testBasic() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("hyperlink.xlsb"))) { - XSSFBReader reader = new XSSFBReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) reader.getSheetsData(); - it.next(); - XSSFBHyperlinksTable manager = new XSSFBHyperlinksTable(it.getSheetPart()); - List<XSSFHyperlinkRecord> records = manager.getHyperLinks().get(new CellAddress(0, 0)); - assertNotNull(records); - assertEquals(1, records.size()); - XSSFHyperlinkRecord record = records.get(0); - assertEquals("http://tika.apache.org/", record.getLocation()); - assertEquals("rId2", record.getRelId()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java deleted file mode 100644 index 3d59980c05..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.eventusermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; -import java.util.List; -import java.util.regex.Pattern; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.xml.sax.SAXException; - -/** - * Tests for {@link org.apache.poi.xssf.eventusermodel.XSSFReader} - */ -public final class TestReadOnlySharedStringsTable { - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - - @Test - void testParse() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { - List<PackagePart> parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml")); - assertEquals(1, parts.size()); - - SharedStringsTable stbl = new SharedStringsTable(parts.get(0)); - ReadOnlySharedStringsTable rtbl = new ReadOnlySharedStringsTable(parts.get(0)); - - assertEquals(stbl.getCount(), rtbl.getCount()); - assertEquals(stbl.getUniqueCount(), rtbl.getUniqueCount()); - - assertEquals(stbl.getCount(), stbl.getUniqueCount()); - assertEquals(rtbl.getCount(), rtbl.getUniqueCount()); - for (int i = 0; i < stbl.getUniqueCount(); i++) { - RichTextString i1 = stbl.getItemAt(i); - RichTextString i2 = rtbl.getItemAt(i); - assertEquals(i1.getString(), i2.getString()); - } - } - } - - //51519 - @Test - void testPhoneticRuns() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("51519.xlsx"))) { - List < PackagePart > parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml")); - assertEquals(1, parts.size()); - - ReadOnlySharedStringsTable rtbl = new ReadOnlySharedStringsTable(parts.get(0), true); - assertEquals(49, rtbl.getUniqueCount()); - - assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getItemAt(0).getString()); - assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3", rtbl.getItemAt(3).getString()); - - //now do not include phonetic runs - rtbl = new ReadOnlySharedStringsTable(parts.get(0),false); - assertEquals(49, rtbl.getUniqueCount()); - - assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getItemAt(0).getString()); - assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB", rtbl.getItemAt(3).getString()); - } - } - - @Test - void testEmptySSTOnPackageObtainedViaWorkbook() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(_ssTests.openResourceAsStream("noSharedStringTable.xlsx")); - OPCPackage pkg = wb.getPackage(); - assertEmptySST(pkg); - wb.close(); - } - - @Test - void testEmptySSTOnPackageDirect() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("noSharedStringTable.xlsx"))) { - assertEmptySST(pkg); - } - } - - private void assertEmptySST(OPCPackage pkg) throws IOException, SAXException { - ReadOnlySharedStringsTable sst = new ReadOnlySharedStringsTable(pkg); - assertEquals(0, sst.getCount()); - assertEquals(0, sst.getUniqueCount()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java deleted file mode 100644 index 2d6e57e049..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java +++ /dev/null @@ -1,219 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.eventusermodel; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.xssf.binary.XSSFBSharedStringsTable; -import org.apache.poi.xssf.binary.XSSFBSheetHandler; -import org.apache.poi.xssf.binary.XSSFBStylesTable; -import org.apache.poi.xssf.usermodel.XSSFComment; -import org.junit.jupiter.api.Test; - -class TestXSSFBReader { - - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - - @Test - void testBasic() throws Exception { - List<String> sheetTexts = getSheets("testVarious.xlsb"); - - assertEquals(1, sheetTexts.size()); - String xsxml = sheetTexts.get(0); - assertContains(xsxml, "This is a string"); - assertContains(xsxml, "<td ref=\"B2\">13</td>"); - assertContains(xsxml, "<td ref=\"B3\">13.12112313</td>"); - assertContains(xsxml, "<td ref=\"B4\">$ 3.03</td>"); - assertContains(xsxml, "<td ref=\"B5\">20%</td>"); - assertContains(xsxml, "<td ref=\"B6\">13.12</td>"); - assertContains(xsxml, "<td ref=\"B7\">1.23457E+14</td>"); - assertContains(xsxml, "<td ref=\"B8\">1.23457E+15</td>"); - - assertContains(xsxml, "46/1963");//custom format 1 - assertContains(xsxml, "3/128");//custom format 2 - - assertContains(xsxml, "<tr num=\"7>\n" + - "\t<td ref=\"A8\">longer int</td>\n" + - "\t<td ref=\"B8\">1.23457E+15</td>\n" + - "\t<td ref=\"C8\"><span type=\"comment\" author=\"Allison, Timothy B.\">Allison, Timothy B.:\n" + - "test comment2</span></td>\n" + - "</tr num=\"7>"); - - assertContains(xsxml, "<tr num=\"34>\n" + - "\t<td ref=\"B35\">comment6<span type=\"comment\" author=\"Allison, Timothy B.\">Allison, Timothy B.:\n" + - "comment6 actually in cell</span></td>\n" + - "</tr num=\"34>"); - - assertContains(xsxml, "<tr num=\"64>\n" + - "\t<td ref=\"I65\"><span type=\"comment\" author=\"Allison, Timothy B.\">Allison, Timothy B.:\n" + - "comment7 end of file</span></td>\n" + - "</tr num=\"64>"); - - assertContains(xsxml, "<tr num=\"65>\n" + - "\t<td ref=\"I66\"><span type=\"comment\" author=\"Allison, Timothy B.\">Allison, Timothy B.:\n" + - "comment8 end of file</span></td>\n" + - "</tr num=\"65>"); - - assertContains(xsxml, - "<header tagName=\"header\">OddLeftHeader OddCenterHeader OddRightHeader</header>"); - assertContains(xsxml, - "<footer tagName=\"footer\">OddLeftFooter OddCenterFooter OddRightFooter</footer>"); - assertContains(xsxml, - "<header tagName=\"evenHeader\">EvenLeftHeader EvenCenterHeader EvenRightHeader\n</header>"); - assertContains(xsxml, - "<footer tagName=\"evenFooter\">EvenLeftFooter EvenCenterFooter EvenRightFooter</footer>"); - assertContains(xsxml, - "<header tagName=\"firstHeader\">FirstPageLeftHeader FirstPageCenterHeader FirstPageRightHeader</header>"); - assertContains(xsxml, - "<footer tagName=\"firstFooter\">FirstPageLeftFooter FirstPageCenterFooter FirstPageRightFooter</footer>"); - - } - - @Test - void testComments() throws Exception { - List<String> sheetTexts = getSheets("comments.xlsb"); - String xsxml = sheetTexts.get(0); - assertContains(xsxml, - "<tr num=\"0>\n" + - "\t<td ref=\"A1\"><span type=\"comment\" author=\"Sven Nissel\">comment top row1 (index0)</span></td>\n" + - "\t<td ref=\"B1\">row1</td>\n" + - "</tr num=\"0>"); - assertContains(xsxml, - "<tr num=\"1>\n" + - "\t<td ref=\"A2\"><span type=\"comment\" author=\"Allison, Timothy B.\">Allison, Timothy B.:\n" + - "comment row2 (index1)</span></td>\n" + - "</tr num=\"1>"); - assertContains(xsxml, "<tr num=\"2>\n" + - "\t<td ref=\"A3\">row3<span type=\"comment\" author=\"Sven Nissel\">comment top row3 (index2)</span></td>\n" + - "\t<td ref=\"B3\">row3</td>\n"); - - assertContains(xsxml, "<tr num=\"3>\n" + - "\t<td ref=\"A4\"><span type=\"comment\" author=\"Sven Nissel\">comment top row4 (index3)</span></td>\n" + - "\t<td ref=\"B4\">row4</td>\n" + - "</tr num=\"3></sheet>"); - - } - - @Test - void testAbsPath() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("testVarious.xlsb"))) { - XSSFBReader r = new XSSFBReader(pkg); - assertEquals("C:\\Users\\tallison\\Desktop\\working\\xlsb\\", r.getAbsPathMetadata()); - } - } - - private List<String> getSheets(String testFileName) throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream(testFileName))) { - List<String> sheetTexts = new ArrayList<>(); - XSSFBReader r = new XSSFBReader(pkg); - -// assertNotNull(r.getWorkbookData()); - // assertNotNull(r.getSharedStringsData()); - assertNotNull(r.getXSSFBStylesTable()); - XSSFBSharedStringsTable sst = new XSSFBSharedStringsTable(pkg); - XSSFBStylesTable xssfbStylesTable = r.getXSSFBStylesTable(); - XSSFBReader.SheetIterator it = (XSSFBReader.SheetIterator) r.getSheetsData(); - - while (it.hasNext()) { - InputStream is = it.next(); - String name = it.getSheetName(); - TestSheetHandler testSheetHandler = new TestSheetHandler(); - testSheetHandler.startSheet(name); - XSSFBSheetHandler sheetHandler = new XSSFBSheetHandler(is, - xssfbStylesTable, - it.getXSSFBSheetComments(), - sst, testSheetHandler, - new DataFormatter(), - false); - sheetHandler.parse(); - testSheetHandler.endSheet(); - sheetTexts.add(testSheetHandler.toString()); - } - return sheetTexts; - } - } - - @Test - void testDate() throws Exception { - List<String> sheets = getSheets("date.xlsb"); - assertEquals(1, sheets.size()); - assertContains(sheets.get(0), "1/12/13"); - } - - - private class TestSheetHandler implements XSSFSheetXMLHandler.SheetContentsHandler { - private final StringBuilder sb = new StringBuilder(); - - void startSheet(String sheetName) { - sb.append("<sheet name=\"").append(sheetName).append(">"); - } - - public void endSheet() { - sb.append("</sheet>"); - } - - @Override - public void startRow(int rowNum) { - sb.append("\n<tr num=\"").append(rowNum).append(">"); - } - - @Override - public void endRow(int rowNum) { - sb.append("\n</tr num=\"").append(rowNum).append(">"); - } - - @Override - public void cell(String cellReference, String formattedValue, XSSFComment comment) { - formattedValue = (formattedValue == null) ? "" : formattedValue; - if (comment == null) { - sb.append("\n\t<td ref=\"").append(cellReference).append("\">").append(formattedValue).append("</td>"); - } else { - sb.append("\n\t<td ref=\"").append(cellReference).append("\">") - .append(formattedValue) - .append("<span type=\"comment\" author=\"") - .append(comment.getAuthor()).append("\">") - .append(comment.getString().toString().trim()).append("</span>") - .append("</td>"); - } - } - - @Override - public void headerFooter(String text, boolean isHeader, String tagName) { - if (isHeader) { - sb.append("<header tagName=\"").append(tagName).append("\">").append(text).append("</header>"); - } else { - sb.append("<footer tagName=\"").append(tagName).append("\">").append(text).append("</footer>"); - - } - } - - @Override - public String toString() { - return sb.toString(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java deleted file mode 100644 index 766ebeb0ef..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java +++ /dev/null @@ -1,374 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.eventusermodel; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.POITestCase.assertNotContained; -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.assertNull; -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.security.MessageDigest; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.apache.commons.codec.binary.Base64; -import org.apache.poi.POIDataSamples; -import org.apache.poi.ooxml.POIXMLException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.XSSFShape; -import org.apache.poi.xssf.usermodel.XSSFSimpleShape; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link XSSFReader} - */ -public final class TestXSSFReader { - - private static final POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - - @Test - void testGetBits() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { - - XSSFReader r = new XSSFReader(pkg); - - assertNotNull(r.getWorkbookData()); - assertNotNull(r.getSharedStringsData()); - assertNotNull(r.getStylesData()); - - assertNotNull(r.getSharedStringsTable()); - assertNotNull(r.getStylesTable()); - } - } - - @Test - void testStyles() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { - - XSSFReader r = new XSSFReader(pkg); - - assertEquals(3, r.getStylesTable().getFonts().size()); - assertEquals(0, r.getStylesTable().getNumDataFormats()); - - // The Styles Table should have the themes associated with it too - assertNotNull(r.getStylesTable().getTheme()); - - // Check we get valid data for the two - assertNotNull(r.getStylesData()); - assertNotNull(r.getThemesData()); - } - } - - @Test - void testStrings() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { - - XSSFReader r = new XSSFReader(pkg); - - assertEquals(11, r.getSharedStringsTable().getSharedStringItems().size()); - assertEquals("Test spreadsheet", r.getSharedStringsTable().getItemAt(0).toString()); - } - } - - @Test - void testSheets() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { - - XSSFReader r = new XSSFReader(pkg); - byte[] data = new byte[4096]; - - // By r:id - assertNotNull(r.getSheet("rId2")); - int read = IOUtils.readFully(r.getSheet("rId2"), data); - assertEquals(974, read); - - // All - Iterator<InputStream> it = r.getSheetsData(); - - int count = 0; - while (it.hasNext()) { - count++; - InputStream inp = it.next(); - assertNotNull(inp); - read = IOUtils.readFully(inp, data); - inp.close(); - - assertTrue(read > 400); - assertTrue(read < 1500); - } - assertEquals(3, count); - } - } - - /** - * Check that the sheet iterator returns sheets in the logical order - * (as they are defined in the workbook.xml) - */ - @Test - void testOrderOfSheets() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("reordered_sheets.xlsx"))) { - - XSSFReader r = new XSSFReader(pkg); - - String[] sheetNames = {"Sheet4", "Sheet2", "Sheet3", "Sheet1"}; - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); - - int count = 0; - while (it.hasNext()) { - InputStream inp = it.next(); - assertNotNull(inp); - inp.close(); - - assertEquals(sheetNames[count], it.getSheetName()); - count++; - } - assertEquals(4, count); - } - } - - @Test - void testComments() throws Exception { - try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("comments.xlsx")) { - XSSFReader r = new XSSFReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); - - int count = 0; - while (it.hasNext()) { - count++; - InputStream inp = it.next(); - inp.close(); - - if (count == 1) { - assertNotNull(it.getSheetComments()); - CommentsTable ct = it.getSheetComments(); - assertEquals(1, ct.getNumberOfAuthors()); - assertEquals(3, ct.getNumberOfComments()); - } else { - assertNull(it.getSheetComments()); - } - } - assertEquals(3, count); - } - } - - /** - * Iterating over a workbook with chart sheets in it, using the - * XSSFReader method - */ - @Test - void test50119() throws Exception { - try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("WithChartSheet.xlsx")) { - XSSFReader r = new XSSFReader(pkg); - assertEquals("bxdf4aa1n9VLkn/4++RNhoygSelxWDM2Can1m9TLlTw=", hash(r)); - } - } - - /** - * Test text extraction from text box using getShapes() - */ - @Test - void testShapes() throws Exception { - try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("WithTextBox.xlsx")) { - XSSFReader r = new XSSFReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); - - String text = getShapesString(it); - assertContains(text, "Line 1"); - assertContains(text, "Line 2"); - assertContains(text, "Line 3"); - } - } - - private String getShapesString(XSSFReader.SheetIterator it) { - StringBuilder sb = new StringBuilder(); - while (it.hasNext()) { - it.next(); - List<XSSFShape> shapes = it.getShapes(); - if (shapes != null) { - for (XSSFShape shape : shapes) { - if (shape instanceof XSSFSimpleShape) { - String t = ((XSSFSimpleShape) shape).getText(); - sb.append(t).append('\n'); - } - } - } - } - return sb.toString(); - } - - @Test - void testBug57914() throws Exception { - try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("57914.xlsx")) { - // for now expect this to fail, when we fix 57699, this one should fail so we know we should adjust - // this test as well - POIXMLException e = assertThrows(POIXMLException.class, () -> { - final XSSFReader r = new XSSFReader(pkg); - - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); - - String text = getShapesString(it); - assertContains(text, "Line 1"); - assertContains(text, "Line 2"); - assertContains(text, "Line 3"); - }); - assertContains(e.getMessage(), "57699"); - } - } - - /** - * NPE from XSSFReader$SheetIterator.<init> on XLSX files generated by - * the openpyxl library - */ - @Test - void test58747() throws Exception { - try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("58747.xlsx")) { - ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg); - assertNotNull(strings); - XSSFReader reader = new XSSFReader(pkg); - StylesTable styles = reader.getStylesTable(); - assertNotNull(styles); - - XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) reader.getSheetsData(); - assertTrue(iter.hasNext()); - iter.next(); - - assertFalse(iter.hasNext()); - assertEquals("Orders", iter.getSheetName()); - } - } - - /** - * NPE when sheet has no relationship id in the workbook - * 60825 - */ - @Test - void testSheetWithNoRelationshipId() throws Exception { - try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("60825.xlsx")) { - ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg); - assertNotNull(strings); - XSSFReader reader = new XSSFReader(pkg); - StylesTable styles = reader.getStylesTable(); - assertNotNull(styles); - - XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) reader.getSheetsData(); - assertNotNull(iter.next()); - assertFalse(iter.hasNext()); - } - } - - /** - * bug 61304: Call to XSSFReader.getSheetsData() returns duplicate sheets. - * - * The problem seems to be caused only by those xlsx files which have a specific - * order of the attributes inside the <sheet> tag of workbook.xml - * - * Example (which causes the problems): - * <sheet name="Sheet6" r:id="rId6" sheetId="4"/> - * - * While this one works correctly: - * <sheet name="Sheet6" sheetId="4" r:id="rId6"/> - */ - @Test - void test61034() throws Exception { - try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("61034.xlsx")) { - XSSFReader reader = new XSSFReader(pkg); - XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) reader.getSheetsData(); - Set<String> seen = new HashSet<>(); - while (iter.hasNext()) { - InputStream stream = iter.next(); - String sheetName = iter.getSheetName(); - assertNotContained(seen, sheetName); - seen.add(sheetName); - stream.close(); - } - } - } - - @Disabled("until we fix issue https://bz.apache.org/bugzilla/show_bug.cgi?id=61701") - void test61701() throws Exception { - try(Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("simple-table-named-range.xlsx")) { - Name name = workbook.getName("total"); - System.out.println("workbook.getName(\"total\").getSheetName() returned: " + name.getSheetName()); - } - } - - @Test - void test64420() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("64420.xlsm"))) { - XSSFReader reader = new XSSFReader(pkg); - assertEquals("U/j5UN7LN8wH6Gw/gsn6pCMASz+Nb1euCsFtC8tAPm0=", hash(reader)); - } - } - - @Test - void testStrictOoxmlNotAllowed() throws Exception { - assertThrows(POIXMLException.class, () -> { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("sample.strict.xlsx"))) { - XSSFReader reader = new XSSFReader(pkg); - } - }); - assertThrows(POIXMLException.class, () -> { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("sample.strict.xlsx"))) { - XSSFReader reader = new XSSFReader(pkg, false); - } - }); - } - - @Test - void testStrictOoxmlAllowed() throws Exception { - try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("sample.strict.xlsx"))) { - XSSFReader reader = new XSSFReader(pkg, true); - assertNotNull(reader.pkg); - } - } - - private static String hash(XSSFReader reader) throws IOException { - Iterable<InputStream> iter = () -> { - try { - return reader.getSheetsData(); - } catch (IOException | InvalidFormatException e) { - throw new RuntimeException(e); - } - }; - - MessageDigest md = CryptoFunctions.getMessageDigest(HashAlgorithm.sha256); - for (InputStream is : iter) { - md.update(IOUtils.toByteArray(is)); - } - - return Base64.encodeBase64String(md.digest()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFSheetXMLHandler.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFSheetXMLHandler.java deleted file mode 100644 index 377918ec1f..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFSheetXMLHandler.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.eventusermodel; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.XMLHelper; -import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler; -import org.apache.poi.xssf.usermodel.XSSFComment; -import org.junit.jupiter.api.Test; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; - -import java.io.InputStream; -import java.util.Iterator; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class TestXSSFSheetXMLHandler { - private static final POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - - @Test - public void testInlineString() throws Exception { - try (OPCPackage xlsxPackage = OPCPackage.open(_ssTests.openResourceAsStream("InlineString.xlsx"))) { - final XSSFReader reader = new XSSFReader(xlsxPackage); - - final Iterator<InputStream> iter = reader.getSheetsData(); - - try (InputStream stream = iter.next()) { - final XMLReader sheetParser = XMLHelper.getSaxParserFactory().newSAXParser().getXMLReader(); - - sheetParser.setContentHandler(new XSSFSheetXMLHandler(reader.getStylesTable(), - new ReadOnlySharedStringsTable(xlsxPackage), new SheetContentsHandler() { - - int cellCount = 0; - - @Override - public void startRow(final int rowNum) { - } - - @Override - public void endRow(final int rowNum) { - } - - @Override - public void cell(final String cellReference, final String formattedValue, - final XSSFComment comment) { - assertEquals("\uD83D\uDE1Cmore text", formattedValue); - assertEquals(cellCount++, 0); - } - }, false)); - - sheetParser.parse(new InputSource(stream)); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java deleted file mode 100644 index 8cd773a2e9..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.POITestCase.assertStartsWith; -import static org.apache.poi.POITestCase.assertEndsWith; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -import java.io.BufferedReader; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; - -/** - * Tests for {@link XSSFBEventBasedExcelExtractor} - */ -class TestXSSFBEventBasedExcelExtractor { - protected XSSFEventBasedExcelExtractor getExtractor(String sampleName) throws Exception { - return new XSSFBEventBasedExcelExtractor(XSSFTestDataSamples. - openSamplePackage(sampleName)); - } - - /** - * Get text out of the simple file - */ - @Test - void testGetSimpleText() throws Exception { - // a very simple file - try (XSSFEventBasedExcelExtractor extractor = getExtractor("sample.xlsb")) { - extractor.setIncludeCellComments(true); - extractor.getText(); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check sheet names - assertStartsWith(text, "Sheet1"); - assertEndsWith(text, "Sheet3\n"); - - // Now without, will have text - extractor.setIncludeSheetNames(false); - text = extractor.getText(); - String CHUNK1 = - "Lorem\t111\n" + - "ipsum\t222\n" + - "dolor\t333\n" + - "sit\t444\n" + - "amet\t555\n" + - "consectetuer\t666\n" + - "adipiscing\t777\n" + - "elit\t888\n" + - "Nunc\t999\n"; - String CHUNK2 = - "The quick brown fox jumps over the lazy dog\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n"; - assertEquals( - CHUNK1 + - "at\t4995\n" + - CHUNK2 - , text); - } - } - - /** - * Test text extraction from text box using getShapes() - */ - @Test - void testShapes() throws Exception { - try (XSSFEventBasedExcelExtractor ooxmlExtractor = getExtractor("WithTextBox.xlsb")) { - String text = ooxmlExtractor.getText(); - assertContains(text, "Line 1"); - assertContains(text, "Line 2"); - assertContains(text, "Line 3"); - } - } - - @Test - void testBeta() throws Exception { - try (XSSFEventBasedExcelExtractor extractor = getExtractor("Simple.xlsb")) { - extractor.setIncludeCellComments(true); - String text = extractor.getText(); - assertContains(text, - "This is an example spreadsheet created with Microsoft Excel 2007 Beta 2."); - } - } - - @Test - void test62815() throws Exception { - //test file based on http://oss.sheetjs.com/test_files/RkNumber.xlsb - try (XSSFEventBasedExcelExtractor extractor = getExtractor("62815.xlsb")) { - extractor.setIncludeCellComments(true); - String[] rows = extractor.getText().split("[\r\n]+"); - assertEquals(283, rows.length); - try (BufferedReader reader = Files.newBufferedReader(XSSFTestDataSamples.getSampleFile("62815.xlsb.txt").toPath(), - StandardCharsets.UTF_8)) { - String line = reader.readLine(); - for (String row : rows) { - assertEquals(line, row); - line = reader.readLine(); - while (line != null && line.startsWith("#")) { - line = reader.readLine(); - } - } - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java deleted file mode 100644 index 0de3611bc1..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java +++ /dev/null @@ -1,354 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.POITestCase.assertStartsWith; -import static org.apache.poi.POITestCase.assertEndsWith; -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.assertTrue; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.extractor.POITextExtractor; -import org.apache.poi.ooxml.extractor.POIXMLTextExtractor; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link XSSFEventBasedExcelExtractor} - */ -class TestXSSFEventBasedExcelExtractor { - protected XSSFEventBasedExcelExtractor getExtractor(String sampleName) throws Exception { - return new XSSFEventBasedExcelExtractor(XSSFTestDataSamples. - openSamplePackage(sampleName)); - } - - /** - * Get text out of the simple file - */ - @Test - void testGetSimpleText() throws Exception { - // a very simple file - XSSFEventBasedExcelExtractor extractor = getExtractor("sample.xlsx"); - extractor.getText(); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check sheet names - assertStartsWith(text, "Sheet1"); - assertEndsWith(text, "Sheet3\n"); - - // Now without, will have text - extractor.setIncludeSheetNames(false); - text = extractor.getText(); - String CHUNK1 = - "Lorem\t111\n" + - "ipsum\t222\n" + - "dolor\t333\n" + - "sit\t444\n" + - "amet\t555\n" + - "consectetuer\t666\n" + - "adipiscing\t777\n" + - "elit\t888\n" + - "Nunc\t999\n"; - String CHUNK2 = - "The quick brown fox jumps over the lazy dog\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n"; - assertEquals( - CHUNK1 + - "at\t4995\n" + - CHUNK2 - , text); - - // Now get formulas not their values - extractor.setFormulasNotResults(true); - text = extractor.getText(); - assertEquals( - CHUNK1 + - "at\tSUM(B1:B9)\n" + - CHUNK2, text); - - // With sheet names too - extractor.setIncludeSheetNames(true); - text = extractor.getText(); - assertEquals( - "Sheet1\n" + - CHUNK1 + - "at\tSUM(B1:B9)\n" + - "rich test\n" + - CHUNK2 + - "Sheet3\n" - , text); - - extractor.close(); - } - - @Test - void testGetComplexText() throws Exception { - // A fairly complex file - XSSFEventBasedExcelExtractor extractor = getExtractor("AverageTaxRates.xlsx"); - extractor.getText(); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Might not have all formatting it should do! - assertStartsWith(text, - "Avgtxfull\n" + - "(iii) AVERAGE TAX RATES ON ANNUAL" - ); - - extractor.close(); - } - - @Test - void testInlineStrings() throws Exception { - XSSFEventBasedExcelExtractor extractor = getExtractor("InlineStrings.xlsx"); - extractor.setFormulasNotResults(true); - String text = extractor.getText(); - - // Numbers - assertContains(text, "43"); - assertContains(text, "22"); - - // Strings - assertContains(text, "ABCDE"); - assertContains(text, "Long Text"); - - // Inline Strings - assertContains(text, "1st Inline String"); - assertContains(text, "And More"); - - // Formulas - assertContains(text, "A2"); - assertContains(text, "A5-A$2"); - - extractor.close(); - } - - /** - * Test that we return pretty much the same as - * ExcelExtractor does, when we're both passed - * the same file, just saved as xls and xlsx - */ - @Test - void testComparedToOLE2() throws Exception { - // A fairly simple file - ooxml - XSSFEventBasedExcelExtractor ooxmlExtractor = getExtractor("SampleSS.xlsx"); - - ExcelExtractor ole2Extractor = - new ExcelExtractor(HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")); - - POITextExtractor[] extractors = - new POITextExtractor[] { ooxmlExtractor, ole2Extractor }; - for (POITextExtractor extractor : extractors) { - String text = extractor.getText().replaceAll("[\r\t]", ""); - assertStartsWith(text, "First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n"); - Pattern pattern = Pattern.compile(".*13(\\.0+)?\\s+Sheet3.*", Pattern.DOTALL); - Matcher m = pattern.matcher(text); - assertTrue(m.matches()); - } - - ole2Extractor.close(); - ooxmlExtractor.close(); - } - - /** Test text extraction from text box using getShapes() */ - @Test - void testShapes() throws Exception{ - - try (XSSFEventBasedExcelExtractor ooxmlExtractor = getExtractor("WithTextBox.xlsx")) { - String text = ooxmlExtractor.getText(); - assertContains(text, "Line 1"); - assertContains(text, "Line 2"); - assertContains(text, "Line 3"); - } - } - - /** - * Test that we return the same output for unstyled numbers as the - * non-event-based XSSFExcelExtractor. - */ - @Test - void testUnstyledNumbersComparedToNonEventBasedExtractor() - throws Exception { - - String expectedOutput = "Sheet1\n99.99\n"; - - try (XSSFExcelExtractor extractor = new XSSFExcelExtractor( - XSSFTestDataSamples.openSampleWorkbook("56011.xlsx"))) { - assertEquals(expectedOutput, extractor.getText().replace(",", ".")); - } - - try (XSSFEventBasedExcelExtractor fixture = new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("56011.xlsx"))) { - assertEquals(expectedOutput, fixture.getText().replace(",", ".")); - } - } - - /** - * Test that we return the same output headers and footers as the - * non-event-based XSSFExcelExtractor. - */ - @Test - void testHeadersAndFootersComparedToNonEventBasedExtractor() - throws Exception { - - String expectedOutputWithHeadersAndFooters = - "Sheet1\n" + - "&\"Calibri,Regular\"&K000000top left\t&\"Calibri,Regular\"&K000000top center\t&\"Calibri,Regular\"&K000000top right\n" + - "abc\t123\n" + - "&\"Calibri,Regular\"&K000000bottom left\t&\"Calibri,Regular\"&K000000bottom center\t&\"Calibri,Regular\"&K000000bottom right\n"; - - String expectedOutputWithoutHeadersAndFooters = - "Sheet1\n" + - "abc\t123\n"; - - try (XSSFExcelExtractor extractor = new XSSFExcelExtractor( - XSSFTestDataSamples.openSampleWorkbook("headerFooterTest.xlsx"))) { - assertEquals(expectedOutputWithHeadersAndFooters, extractor.getText()); - extractor.setIncludeHeadersFooters(false); - assertEquals(expectedOutputWithoutHeadersAndFooters, extractor.getText()); - } - - try (XSSFEventBasedExcelExtractor fixture = new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("headerFooterTest.xlsx"))) { - assertEquals(expectedOutputWithHeadersAndFooters, fixture.getText()); - fixture.setIncludeHeadersFooters(false); - assertEquals(expectedOutputWithoutHeadersAndFooters, fixture.getText()); - } - } - - /** - * Test that XSSFEventBasedExcelExtractor outputs comments when specified. - * The output will contain two improvements over the output from - * XSSFExcelExtractor in that (1) comments from empty cells will be - * outputted, and (2) the author will not be outputted twice. - * <p> - * This test will need to be modified if these improvements are ported to - * XSSFExcelExtractor. - */ - @Test - void testCommentsComparedToNonEventBasedExtractor() - throws Exception { - - String expectedOutputWithoutComments = - "Sheet1\n" + - "\n" + - "abc\n" + - "\n" + - "123\n" + - "\n" + - "\n" + - "\n"; - - String nonEventBasedExtractorOutputWithComments = - "Sheet1\n" + - "\n" + - "abc Comment by Shaun Kalley: Shaun Kalley: Comment A2\n" + - "\n" + - "123 Comment by Shaun Kalley: Shaun Kalley: Comment B4\n" + - "\n" + - "\n" + - "\n"; - - String eventBasedExtractorOutputWithComments = - "Sheet1\n" + - "Comment by Shaun Kalley: Comment A1\tComment by Shaun Kalley: Comment B1\n" + - "abc Comment by Shaun Kalley: Comment A2\tComment by Shaun Kalley: Comment B2\n" + - "Comment by Shaun Kalley: Comment A3\tComment by Shaun Kalley: Comment B3\n" + - "Comment by Shaun Kalley: Comment A4\t123 Comment by Shaun Kalley: Comment B4\n" + - "Comment by Shaun Kalley: Comment A5\tComment by Shaun Kalley: Comment B5\n" + - "Comment by Shaun Kalley: Comment A7\tComment by Shaun Kalley: Comment B7\n" + - "Comment by Shaun Kalley: Comment A8\tComment by Shaun Kalley: Comment B8\n"; - - try (XSSFExcelExtractor extractor = new XSSFExcelExtractor( - XSSFTestDataSamples.openSampleWorkbook("commentTest.xlsx"))) { - assertEquals(expectedOutputWithoutComments, extractor.getText()); - extractor.setIncludeCellComments(true); - assertEquals(nonEventBasedExtractorOutputWithComments, extractor.getText()); - } - - try (XSSFEventBasedExcelExtractor fixture = new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("commentTest.xlsx"))) { - assertEquals(expectedOutputWithoutComments, fixture.getText()); - fixture.setIncludeCellComments(true); - assertEquals(eventBasedExtractorOutputWithComments, fixture.getText()); - } - } - - @Test - void testFile56278_normal() throws Exception { - // first with normal Text Extractor - try (POIXMLTextExtractor extractor = new XSSFExcelExtractor( - XSSFTestDataSamples.openSampleWorkbook("56278.xlsx"))) { - assertNotNull(extractor.getText()); - } - } - - @Test - void testFile56278_event() throws Exception { - // then with event based one - try (POIXMLTextExtractor extractor = getExtractor("56278.xlsx")) { - assertNotNull(extractor.getText()); - } - } - - @Test - void test59021() throws Exception { - XSSFEventBasedExcelExtractor ex = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("59021.xlsx")); - String text = ex.getText(); - assertContains(text, "Abkhazia - Fixed"); - assertContains(text, "10/02/2016"); - ex.close(); - } - - @Test - void test51519() throws Exception { - //default behavior: include phonetic runs - XSSFEventBasedExcelExtractor ex = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("51519.xlsx")); - String text = ex.getText(); - assertContains(text, "\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3"); - ex.close(); - - //now try turning them off - ex = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("51519.xlsx")); - ex.setConcatenatePhoneticRuns(false); - text = ex.getText(); - assertFalse(text.contains("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3"), - "should not be able to find appended phonetic run"); - ex.close(); - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java deleted file mode 100644 index 3dd4b83039..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.extractor; - -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.jupiter.api.AfterEach; - - -class TestXSSFEventBasedExcelExtractorUsingFactory extends TestXSSFEventBasedExcelExtractor { - @Override - protected final XSSFEventBasedExcelExtractor getExtractor(String sampleName) throws Exception { - ExtractorFactory.setAllThreadsPreferEventExtractors(true); - return (XSSFEventBasedExcelExtractor) ExtractorFactory.createExtractor(HSSFTestDataSamples.openSampleFileStream(sampleName)); - } - - @AfterEach - void tearDown() { - // reset setting to not affect other tests - ExtractorFactory.setAllThreadsPreferEventExtractors(null); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java deleted file mode 100644 index 2068a4a993..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java +++ /dev/null @@ -1,250 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.POITestCase.assertEndsWith; -import static org.apache.poi.POITestCase.assertNotContained; -import static org.apache.poi.POITestCase.assertStartsWith; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.extractor.POITextExtractor; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link XSSFExcelExtractor} - */ -class TestXSSFExcelExtractor { - protected XSSFExcelExtractor getExtractor(String sampleName) { - return new XSSFExcelExtractor(XSSFTestDataSamples.openSampleWorkbook(sampleName)); - } - - /** - * Get text out of the simple file - */ - @Test - void testGetSimpleText() throws IOException { - // a very simple file - XSSFExcelExtractor extractor = getExtractor("sample.xlsx"); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check sheet names - assertStartsWith(text, "Sheet1"); - assertEndsWith(text, "Sheet3\n"); - - // Now without, will have text - extractor.setIncludeSheetNames(false); - text = extractor.getText(); - String CHUNK1 = - "Lorem\t111\n" + - "ipsum\t222\n" + - "dolor\t333\n" + - "sit\t444\n" + - "amet\t555\n" + - "consectetuer\t666\n" + - "adipiscing\t777\n" + - "elit\t888\n" + - "Nunc\t999\n"; - String CHUNK2 = - "The quick brown fox jumps over the lazy dog\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n"; - assertEquals( - CHUNK1 + - "at\t4995\n" + - CHUNK2 - , text); - - // Now get formulas not their values - extractor.setFormulasNotResults(true); - text = extractor.getText(); - assertEquals( - CHUNK1 + - "at\tSUM(B1:B9)\n" + - CHUNK2, text); - - // With sheet names too - extractor.setIncludeSheetNames(true); - text = extractor.getText(); - assertEquals( - "Sheet1\n" + - CHUNK1 + - "at\tSUM(B1:B9)\n" + - "rich test\n" + - CHUNK2 + - "Sheet3\n" - , text); - - extractor.close(); - } - - @Test - void testGetComplexText() throws IOException { - // A fairly complex file - XSSFExcelExtractor extractor = getExtractor("AverageTaxRates.xlsx"); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Might not have all formatting it should do! - assertStartsWith(text, - "Avgtxfull\n" + - "\t(iii) AVERAGE TAX RATES ON ANNUAL" - ); - - extractor.close(); - } - - /** - * Test that we return pretty much the same as - * ExcelExtractor does, when we're both passed - * the same file, just saved as xls and xlsx - */ - @Test - void testComparedToOLE2() throws IOException { - // A fairly simple file - ooxml - XSSFExcelExtractor ooxmlExtractor = getExtractor("SampleSS.xlsx"); - - ExcelExtractor ole2Extractor = - new ExcelExtractor(HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")); - - Map<String, POITextExtractor> extractors = new HashMap<>(); - extractors.put("SampleSS.xlsx", ooxmlExtractor); - extractors.put("SampleSS.xls", ole2Extractor); - - for (final Entry<String, POITextExtractor> e : extractors.entrySet()) { - String filename = e.getKey(); - POITextExtractor extractor = e.getValue(); - String text = extractor.getText().replaceAll("[\r\t]", ""); - assertStartsWith(filename, text, "First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n"); - Pattern pattern = Pattern.compile(".*13(\\.0+)?\\s+Sheet3.*", Pattern.DOTALL); - Matcher m = pattern.matcher(text); - assertTrue(m.matches(), filename); - } - - ole2Extractor.close(); - ooxmlExtractor.close(); - } - - /** - * From bug #45540 - */ - @Test - void testHeaderFooter() throws IOException { - String[] files = new String[] { - "45540_classic_Header.xlsx", "45540_form_Header.xlsx", - "45540_classic_Footer.xlsx", "45540_form_Footer.xlsx", - }; - for(String sampleName : files) { - XSSFExcelExtractor extractor = getExtractor(sampleName); - String text = extractor.getText(); - - assertContains(sampleName, text, "testdoc"); - assertContains(sampleName, text, "test phrase"); - - extractor.close(); - } - } - - /** - * From bug #45544 - */ - @Test - void testComments() throws IOException { - XSSFExcelExtractor extractor = getExtractor("45544.xlsx"); - String text = extractor.getText(); - - // No comments there yet - assertNotContained(text, "testdoc"); - assertNotContained(text, "test phrase"); - - // Turn on comment extraction, will then be - extractor.setIncludeCellComments(true); - text = extractor.getText(); - assertContains(text, "testdoc"); - assertContains(text, "test phrase"); - - extractor.close(); - } - - @Test - void testInlineStrings() throws IOException { - XSSFExcelExtractor extractor = getExtractor("InlineStrings.xlsx"); - extractor.setFormulasNotResults(true); - String text = extractor.getText(); - - // Numbers - assertContains(text, "43"); - assertContains(text, "22"); - - // Strings - assertContains(text, "ABCDE"); - assertContains(text, "Long Text"); - - // Inline Strings - assertContains(text, "1st Inline String"); - assertContains(text, "And More"); - - // Formulas - assertContains(text, "A2"); - assertContains(text, "A5-A$2"); - - extractor.close(); - } - - /** - * Simple test for text box text - */ - @Test - void testTextBoxes() throws IOException { - try (XSSFExcelExtractor extractor = getExtractor("WithTextBox.xlsx")) { - extractor.setFormulasNotResults(true); - String text = extractor.getText(); - assertContains(text, "Line 1"); - assertContains(text, "Line 2"); - assertContains(text, "Line 3"); - } - } - - @Test - void testPhoneticRuns() throws Exception { - try (XSSFExcelExtractor extractor = getExtractor("51519.xlsx")) { - String text = extractor.getText(); - assertContains(text, "\u8C4A\u7530"); - //this shows up only as a phonetic run and should not appear - //in the extracted text - assertNotContained(text, "\u30CB\u30DB\u30F3"); - } - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java deleted file mode 100644 index 4ef8030119..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java +++ /dev/null @@ -1,44 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.jupiter.api.AfterEach; - -/** - * Tests for {@link XSSFExcelExtractor} - */ -public final class TestXSSFExcelExtractorUsingFactory extends TestXSSFExcelExtractor { - @Override - protected final XSSFExcelExtractor getExtractor(String sampleName) { - ExtractorFactory.setAllThreadsPreferEventExtractors(false); - ExtractorFactory.setThreadPrefersEventExtractors(false); - try { - return (XSSFExcelExtractor) ExtractorFactory.createExtractor(HSSFTestDataSamples.openSampleFileStream(sampleName)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @AfterEach - void tearDown() { - // reset setting to not affect other tests - ExtractorFactory.setAllThreadsPreferEventExtractors(null); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java deleted file mode 100644 index 5a6afb7e20..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java +++ /dev/null @@ -1,672 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -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.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.Date; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.xml.parsers.DocumentBuilder; - -import org.apache.poi.ooxml.POIXMLDocumentPart; -import org.apache.poi.ooxml.util.DocumentHelper; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.XMLHelper; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.MapInfo; -import org.apache.poi.xssf.usermodel.XSSFMap; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -/** - * @author Roberto Manicardi - */ -public final class TestXSSFExportToXML { - - @Test - void testExportToXML() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx")) { - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xml = os.toString("UTF-8"); - - assertNotNull(xml); - assertFalse(xml.isEmpty()); - - String docente = xml.split("<DOCENTE>")[1].split("</DOCENTE>")[0].trim(); - String nome = xml.split("<NOME>")[1].split("</NOME>")[0].trim(); - String tutor = xml.split("<TUTOR>")[1].split("</TUTOR>")[0].trim(); - String cdl = xml.split("<CDL>")[1].split("</CDL>")[0].trim(); - String durata = xml.split("<DURATA>")[1].split("</DURATA>")[0].trim(); - String argomento = xml.split("<ARGOMENTO>")[1].split("</ARGOMENTO>")[0].trim(); - String progetto = xml.split("<PROGETTO>")[1].split("</PROGETTO>")[0].trim(); - String crediti = xml.split("<CREDITI>")[1].split("</CREDITI>")[0].trim(); - - assertEquals("ro", docente); - assertEquals("ro", nome); - assertEquals("ds", tutor); - assertEquals("gs", cdl); - assertEquals("g", durata); - assertEquals("gvvv", argomento); - assertEquals("aaaa", progetto); - assertEquals("aa", crediti); - - parseXML(xml); - - found = true; - } - assertTrue(found); - } - } - - @Test - void testExportToXMLInverseOrder() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("CustomXmlMappings-inverse-order.xlsx")) { - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xml = os.toString("UTF-8"); - - assertNotNull(xml); - assertFalse(xml.isEmpty()); - - String docente = xml.split("<DOCENTE>")[1].split("</DOCENTE>")[0].trim(); - String nome = xml.split("<NOME>")[1].split("</NOME>")[0].trim(); - String tutor = xml.split("<TUTOR>")[1].split("</TUTOR>")[0].trim(); - String cdl = xml.split("<CDL>")[1].split("</CDL>")[0].trim(); - String durata = xml.split("<DURATA>")[1].split("</DURATA>")[0].trim(); - String argomento = xml.split("<ARGOMENTO>")[1].split("</ARGOMENTO>")[0].trim(); - String progetto = xml.split("<PROGETTO>")[1].split("</PROGETTO>")[0].trim(); - String crediti = xml.split("<CREDITI>")[1].split("</CREDITI>")[0].trim(); - - assertEquals("aa", nome); - assertEquals("aaaa", docente); - assertEquals("gvvv", tutor); - assertEquals("g", cdl); - assertEquals("gs", durata); - assertEquals("ds", argomento); - assertEquals("ro", progetto); - assertEquals("ro", crediti); - - parseXML(xml); - - found = true; - } - assertTrue(found); - } - } - - @Test - void testXPathOrdering() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("CustomXmlMappings-inverse-order.xlsx")) { - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (p instanceof MapInfo) { - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - XSSFExportToXml exporter = new XSSFExportToXml(map); - - assertEquals(1, exporter.compare("/CORSO/DOCENTE", "/CORSO/NOME")); - assertEquals(-1, exporter.compare("/CORSO/NOME", "/CORSO/DOCENTE")); - } - - found = true; - } - assertTrue(found); - } - } - - @Test - void testMultiTable() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("CustomXMLMappings-complex-type.xlsx")) { - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (p instanceof MapInfo) { - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(2); - - assertNotNull(map); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xml = os.toString("UTF-8"); - - assertNotNull(xml); - - String[] regexConditions = { - "<MapInfo", "</MapInfo>", - "<Schema ID=\"1\" Namespace=\"\" SchemaRef=\"\"/>", - "<Schema ID=\"4\" Namespace=\"\" SchemaRef=\"\"/>", - "DataBinding", - "Map Append=\"false\" AutoFit=\"false\" ID=\"1\"", - "Map Append=\"false\" AutoFit=\"false\" ID=\"5\"", - }; - - for (String condition : regexConditions) { - Pattern pattern = Pattern.compile(condition); - Matcher matcher = pattern.matcher(xml); - assertTrue(matcher.find()); - } - } - - found = true; - } - assertTrue(found); - } - } - - @Test - @Disabled(value="Fails, but I don't know if it is ok or not...") - void testExportToXMLSingleAttributeNamespace() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx")) { - - for (XSSFMap map : wb.getCustomXMLMappings()) { - XSSFExportToXml exporter = new XSSFExportToXml(map); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - } - } - } - - @Test - void test55850ComplexXmlExport() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55850.xlsx")) { - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(2); - - assertNotNull(map, "XSSFMap is null"); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.isEmpty()); - - String a = xmlData.split("<A>")[1].split("</A>")[0].trim(); - String b = a.split("<B>")[1].split("</B>")[0].trim(); - String c = b.split("<C>")[1].split("</C>")[0].trim(); - String d = c.split("<D>")[1].split("</Dd>")[0].trim(); - String e = d.split("<E>")[1].split("</EA>")[0].trim(); - - String euro = e.split("<EUR>")[1].split("</EUR>")[0].trim(); - String chf = e.split("<CHF>")[1].split("</CHF>")[0].trim(); - - assertEquals("15", euro); - assertEquals("19", chf); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - } - - @Test - void testFormulaCells_Bugzilla_55927() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55927.xlsx")) { - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - - assertNotNull(map, "XSSFMap is null"); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.isEmpty()); - - assertEquals("2012-01-13", xmlData.split("<DATE>")[1].split("</DATE>")[0].trim()); - assertEquals("2012-02-16", xmlData.split("<FORMULA_DATE>")[1].split("</FORMULA_DATE>")[0].trim()); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - } - - @Test - void testFormulaCells_Bugzilla_55926() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55926.xlsx")) { - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - - assertNotNull(map, "XSSFMap is null"); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.isEmpty()); - - String a = xmlData.split("<A>")[1].split("</A>")[0].trim(); - String doubleValue = a.split("<DOUBLE>")[1].split("</DOUBLE>")[0].trim(); - String stringValue = a.split("<STRING>")[1].split("</STRING>")[0].trim(); - - assertEquals("Hello World", stringValue); - assertEquals("5.1", doubleValue); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - } - - @Test - void testXmlExportIgnoresEmptyCells_Bugzilla_55924() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55924.xlsx")) { - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - - assertNotNull(map, "XSSFMap is null"); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.isEmpty()); - - String a = xmlData.split("<A>")[1].split("</A>")[0].trim(); - String euro = a.split("<EUR>")[1].split("</EUR>")[0].trim(); - assertEquals("1", euro); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - } - - @Test - void testXmlExportSchemaWithXSAllTag_Bugzilla_56169() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56169.xlsx")) { - - for (XSSFMap map : wb.getCustomXMLMappings()) { - XSSFExportToXml exporter = new XSSFExportToXml(map); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.isEmpty()); - - String a = xmlData.split("<A>")[1].split("</A>")[0].trim(); - String a_b = a.split("<B>")[1].split("</B>")[0].trim(); - String a_b_c = a_b.split("<C>")[1].split("</C>")[0].trim(); - String a_b_c_e = a_b_c.split("<E>")[1].split("</EA>")[0].trim(); - String a_b_c_e_euro = a_b_c_e.split("<EUR>")[1].split("</EUR>")[0].trim(); - String a_b_c_e_chf = a_b_c_e.split("<CHF>")[1].split("</CHF>")[0].trim(); - - assertEquals("1", a_b_c_e_euro); - assertEquals("2", a_b_c_e_chf); - - String a_b_d = a_b.split("<D>")[1].split("</Dd>")[0].trim(); - String a_b_d_e = a_b_d.split("<E>")[1].split("</EA>")[0].trim(); - - String a_b_d_e_euro = a_b_d_e.split("<EUR>")[1].split("</EUR>")[0].trim(); - String a_b_d_e_chf = a_b_d_e.split("<CHF>")[1].split("</CHF>")[0].trim(); - - assertEquals("3", a_b_d_e_euro); - assertEquals("4", a_b_d_e_chf); - } - } - } - - @SuppressWarnings("EqualsWithItself") - @Test - void testXmlExportCompare_Bug_55923() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55923.xlsx")) { - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(4); - - assertNotNull(map, "XSSFMap is null"); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - assertEquals(0, exporter.compare("", "")); - assertEquals(0, exporter.compare("/", "/")); - assertEquals(0, exporter.compare("//", "//")); - assertEquals(0, exporter.compare("/a/", "/b/")); - - assertEquals(-1, exporter.compare("/ns1:Entry/ns1:A/ns1:B/ns1:C/ns1:E/ns1:EUR", - "/ns1:Entry/ns1:A/ns1:B/ns1:C/ns1:E/ns1:CHF")); - - found = true; - } - assertTrue(found); - } - } - - @Test - void testXmlExportSchemaOrderingBug_Bugzilla_55923() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55923.xlsx")) { - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(4); - - assertNotNull(map, "XSSFMap is null"); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.isEmpty()); - - String a = xmlData.split("<A>")[1].split("</A>")[0].trim(); - String a_b = a.split("<B>")[1].split("</B>")[0].trim(); - String a_b_c = a_b.split("<C>")[1].split("</C>")[0].trim(); - String a_b_c_e = a_b_c.split("<E>")[1].split("</EA>")[0].trim(); - String a_b_c_e_euro = a_b_c_e.split("<EUR>")[1].split("</EUR>")[0].trim(); - String a_b_c_e_chf = a_b_c_e.split("<CHF>")[1].split("</CHF>")[0].trim(); - - assertEquals("1", a_b_c_e_euro); - assertEquals("2", a_b_c_e_chf); - - String a_b_d = a_b.split("<D>")[1].split("</Dd>")[0].trim(); - String a_b_d_e = a_b_d.split("<E>")[1].split("</EA>")[0].trim(); - - String a_b_d_e_euro = a_b_d_e.split("<EUR>")[1].split("</EUR>")[0].trim(); - String a_b_d_e_chf = a_b_d_e.split("<CHF>")[1].split("</CHF>")[0].trim(); - - assertEquals("3", a_b_d_e_euro); - assertEquals("4", a_b_d_e_chf); - - found = true; - } - assertTrue(found); - } - } - - private void parseXML(String xmlData) throws IOException, SAXException { - DocumentBuilder docBuilder = XMLHelper.newDocumentBuilder(); - docBuilder.parse(new ByteArrayInputStream(xmlData.getBytes(StandardCharsets.UTF_8))); - } - - @Test - void testExportDataTypes() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55923.xlsx")) { - - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - - Cell cString = row.createCell(0); - cString.setCellValue("somestring"); - - Cell cBoolean = row.createCell(1); - cBoolean.setCellValue(true); - - Cell cError = row.createCell(2); - cError.setCellErrorValue(FormulaError.NUM.getCode()); - - Cell cFormulaString = row.createCell(3); - cFormulaString.setCellFormula("A1"); - - Cell cFormulaNumeric = row.createCell(4); - cFormulaNumeric.setCellFormula("F1"); - - Cell cNumeric = row.createCell(5); - cNumeric.setCellValue(1.2); - - Cell cDate = row.createCell(6); - cDate.setCellValue(new Date()); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(4); - - assertNotNull(map, "XSSFMap is null"); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.isEmpty()); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - } - - @Test - void testValidateFalse() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55923.xlsx")) { - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(4); - - assertNotNull(map, "XSSFMap is null"); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, false); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.isEmpty()); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - } - - @Test - void testRefElementsInXmlSchema_Bugzilla_56730() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56730.xlsx")) { - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - - assertNotNull(map, "XSSFMap is null"); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.isEmpty()); - - assertEquals("2014-12-31", xmlData.split("<DATE>")[1].split("</DATE>")[0].trim()); - assertEquals("12.5", xmlData.split("<REFELEMENT>")[1].split("</REFELEMENT>")[0].trim()); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - } - - @Test - void testBug59026() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("59026.xlsx")) { - Collection<XSSFMap> mappings = wb.getCustomXMLMappings(); - assertTrue(mappings.size() > 0); - for (XSSFMap map : mappings) { - XSSFExportToXml exporter = new XSSFExportToXml(map); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, false); - assertNotNull(os.toString("UTF-8")); - } - } - } - - @Test - void testExportTableWithNonMappedColumn_Bugzilla_61281() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("61281.xlsx")) { - for (XSSFMap map : wb.getCustomXMLMappings()) { - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - exporter.exportToXML(bos, true); - assertNotNull(DocumentHelper.readDocument(new ByteArrayInputStream(bos.toByteArray()))); - String exportedXml = bos.toString("UTF-8"); - assertEquals("<Test><Test>1</Test></Test>", exportedXml.replaceAll("\\s+", "")); - } - } - } - - @Test - void testXXEInSchema() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("xxe_in_schema.xlsx")) { - for (XSSFMap map : wb.getCustomXMLMappings()) { - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - assertThrows(SAXParseException.class, () -> exporter.exportToXML(bos, true)); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java deleted file mode 100644 index 7e526810e8..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java +++ /dev/null @@ -1,243 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; -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 java.io.IOException; -import java.text.DateFormatSymbols; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import javax.xml.xpath.XPathExpressionException; - -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFMap; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; -import org.xml.sax.SAXException; - -class TestXSSFImportFromXML { - - @Test - void testImportFromXML() throws IOException, XPathExpressionException, SAXException{ - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx")) { - String name = "name"; - String teacher = "teacher"; - String tutor = "tutor"; - String cdl = "cdl"; - String duration = "duration"; - String topic = "topic"; - String project = "project"; - String credits = "credits"; - - String testXML = "<CORSO>" + - "<NOME>" + name + "</NOME>" + - "<DOCENTE>" + teacher + "</DOCENTE>" + - "<TUTOR>" + tutor + "</TUTOR>" + - "<CDL>" + cdl + "</CDL>" + - "<DURATA>" + duration + "</DURATA>" + - "<ARGOMENTO>" + topic + "</ARGOMENTO>" + - "<PROGETTO>" + project + "</PROGETTO>" + - "<CREDITI>" + credits + "</CREDITI>" + - "</CORSO>\u0000"; - - XSSFMap map = wb.getMapInfo().getXSSFMapByName("CORSO_mapping"); - assertNotNull(map); - XSSFImportFromXML importer = new XSSFImportFromXML(map); - - importer.importFromXML(testXML); - - XSSFSheet sheet = wb.getSheetAt(0); - - XSSFRow row = sheet.getRow(0); - assertEquals(row.getCell(0).getStringCellValue(), name); - assertEquals(row.getCell(1).getStringCellValue(), teacher); - assertEquals(row.getCell(2).getStringCellValue(), tutor); - assertEquals(row.getCell(3).getStringCellValue(), cdl); - assertEquals(row.getCell(4).getStringCellValue(), duration); - assertEquals(row.getCell(5).getStringCellValue(), topic); - assertEquals(row.getCell(6).getStringCellValue(), project); - assertEquals(row.getCell(7).getStringCellValue(), credits); - } - } - - @Timeout(value = 60, unit = SECONDS) - @Test - void testMultiTable() throws IOException, XPathExpressionException, SAXException{ - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx")) { - String cellC6 = "c6"; - String cellC7 = "c7"; - String cellC8 = "c8"; - String cellC9 = "c9"; - - StringBuilder testXML = new StringBuilder("<ns1:MapInfo xmlns:ns1=\"" + NS_SPREADSHEETML + "\" SelectionNamespaces=\"\">" + - "<ns1:Schema ID=\"" + cellC6 + "\" SchemaRef=\"a\" />" + - "<ns1:Schema ID=\"" + cellC7 + "\" SchemaRef=\"b\" />" + - "<ns1:Schema ID=\"" + cellC8 + "\" SchemaRef=\"c\" />" + - "<ns1:Schema ID=\"" + cellC9 + "\" SchemaRef=\"d\" />"); - - int cellOffset = 10; // cell C10 - for (int i = 0; i < 10000; i++) { - testXML.append("<ns1:Schema ID=\"c").append(i + cellOffset).append("\" SchemaRef=\"d\" />"); - } - - testXML.append("<ns1:Map ID=\"1\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">" + "<ns1:DataBinding DataBindingLoadMode=\"\" />" + "</ns1:Map>" + "<ns1:Map ID=\"2\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">" + "<ns1:DataBinding DataBindingLoadMode=\"\" />" + "</ns1:Map>" + "<ns1:Map ID=\"3\" Name=\"\" RootElement=\"\" SchemaID=\"\" ShowImportExportValidationErrors=\"\" AutoFit=\"\" Append=\"\" PreserveSortAFLayout=\"\" PreserveFormat=\"\">" + "<ns1:DataBinding DataBindingLoadMode=\"\" />" + "</ns1:Map>" + "</ns1:MapInfo>\u0000"); - - XSSFMap map = wb.getMapInfo().getXSSFMapByName("MapInfo_mapping"); - assertNotNull(map); - XSSFImportFromXML importer = new XSSFImportFromXML(map); - - importer.importFromXML(testXML.toString()); - - //Check for Schema element - XSSFSheet sheet = wb.getSheetAt(1); - - - // check table size (+1 for the header row) - assertEquals(3 + 1, wb.getTable("Tabella1").getRowCount()); - assertEquals(10004 + 1, wb.getTable("Tabella2").getRowCount()); - - // table1 size was reduced, check that former table cells have been cleared - assertEquals(CellType.BLANK, wb.getSheetAt(0).getRow(8).getCell(5).getCellType()); - - // table2 size was increased, check that new table cells have been cleared - assertEquals(CellType.BLANK, sheet.getRow(10).getCell(3).getCellType()); - - assertEquals(cellC6, sheet.getRow(5).getCell(2).getStringCellValue()); - assertEquals(cellC7, sheet.getRow(6).getCell(2).getStringCellValue()); - assertEquals(cellC8, sheet.getRow(7).getCell(2).getStringCellValue()); - assertEquals(cellC9, sheet.getRow(8).getCell(2).getStringCellValue()); - assertEquals("c5001", sheet.getRow(5000).getCell(2).getStringCellValue()); - } - } - - - @Test - void testSingleAttributeCellWithNamespace() throws IOException, XPathExpressionException, SAXException{ - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx")) { - int id = 1; - String displayName = "dispName"; - String ref = "19"; - int count = 21; - - String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>" + - "<ns1:table xmlns:ns1=\"" + NS_SPREADSHEETML + "\" id=\"" + id + "\" displayName=\"" + displayName + "\" ref=\"" + ref + "\">" + - "<ns1:tableColumns count=\"" + count + "\" />" + - "</ns1:table>\u0000"; - XSSFMap map = wb.getMapInfo().getXSSFMapByName("table_mapping"); - assertNotNull(map); - XSSFImportFromXML importer = new XSSFImportFromXML(map); - importer.importFromXML(testXML); - - //Check for Schema element - XSSFSheet sheet = wb.getSheetAt(0); - - assertEquals(id, sheet.getRow(28).getCell(1).getNumericCellValue(), 0); - assertEquals(displayName, sheet.getRow(11).getCell(5).getStringCellValue()); - assertEquals(ref, sheet.getRow(14).getCell(7).getStringCellValue()); - assertEquals(count, sheet.getRow(18).getCell(3).getNumericCellValue(), 0); - } - } - - @Test - void testOptionalFields_Bugzilla_55864() throws IOException, XPathExpressionException, SAXException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55864.xlsx")) { - String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + - "<PersonInfoRoot>" + - "<PersonData>" + - "<FirstName>Albert</FirstName>" + - "<LastName>Einstein</LastName>" + - "<BirthDate>1879-03-14</BirthDate>" + - "</PersonData>" + - "</PersonInfoRoot>"; - - XSSFMap map = wb.getMapInfo().getXSSFMapByName("PersonInfoRoot_Map"); - assertNotNull(map); - XSSFImportFromXML importer = new XSSFImportFromXML(map); - - importer.importFromXML(testXML); - - XSSFSheet sheet = wb.getSheetAt(0); - - XSSFRow rowHeadings = sheet.getRow(0); - XSSFRow rowData = sheet.getRow(1); - - assertEquals("FirstName", rowHeadings.getCell(0).getStringCellValue()); - assertEquals("Albert", rowData.getCell(0).getStringCellValue()); - - assertEquals("LastName", rowHeadings.getCell(1).getStringCellValue()); - assertEquals("Einstein", rowData.getCell(1).getStringCellValue()); - - assertEquals("BirthDate", rowHeadings.getCell(2).getStringCellValue()); - assertEquals("1879-03-14", rowData.getCell(2).getStringCellValue()); - - // Value for OptionalRating is declared optional (minOccurs=0) in 55864.xlsx - assertEquals("OptionalRating", rowHeadings.getCell(3).getStringCellValue()); - assertNull(rowData.getCell(3), ""); - } - } - - @Test - void testOptionalFields_Bugzilla_57890() throws IOException, ParseException, XPathExpressionException, SAXException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57890.xlsx"); - - String testXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<TestInfoRoot>" - + "<TestData>" + "<Int>" + Integer.MIN_VALUE + "</Int>" + "<UnsignedInt>12345</UnsignedInt>" - + "<double>1.0000123</double>" + "<Date>1991-03-14</Date>" + "</TestData>" + "</TestInfoRoot>"; - - XSSFMap map = wb.getMapInfo().getXSSFMapByName("TestInfoRoot_Map"); - assertNotNull(map); - XSSFImportFromXML importer = new XSSFImportFromXML(map); - - importer.importFromXML(testXML); - - XSSFSheet sheet = wb.getSheetAt(0); - - XSSFRow rowHeadings = sheet.getRow(0); - XSSFRow rowData = sheet.getRow(1); - - assertEquals("Date", rowHeadings.getCell(0).getStringCellValue()); - Date date = new SimpleDateFormat("yyyy-MM-dd", DateFormatSymbols.getInstance(Locale.ROOT)).parse("1991-3-14"); - assertEquals(date, rowData.getCell(0).getDateCellValue()); - - assertEquals("Amount Int", rowHeadings.getCell(1).getStringCellValue()); - assertEquals(Integer.MIN_VALUE, rowData.getCell(1).getNumericCellValue(), 0); - - assertEquals("Amount Double", rowHeadings.getCell(2).getStringCellValue()); - assertEquals(1.0000123, rowData.getCell(2).getNumericCellValue(), 0); - - assertEquals("Amount UnsignedInt", rowHeadings.getCell(3).getStringCellValue()); - assertEquals(12345d, rowData.getCell(3).getNumericCellValue(), 0); - - wb.close(); - } - - - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/io/TestLoadSaveXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/io/TestLoadSaveXSSF.java deleted file mode 100644 index 3d74eba030..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/io/TestLoadSaveXSSF.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.io; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.usermodel.XSSFPictureData; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - - -class TestLoadSaveXSSF { - private static final POIDataSamples _ssSamples = POIDataSamples.getSpreadSheetInstance(); - - @Test - void testLoadSample() throws Exception { - try (XSSFWorkbook workbook = new XSSFWorkbook(_ssSamples.openResourceAsStream("sample.xlsx"))) { - assertEquals(3, workbook.getNumberOfSheets()); - assertEquals("Sheet1", workbook.getSheetName(0)); - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell((short) 1); - assertNotNull(cell); - assertEquals(111.0, cell.getNumericCellValue(), 0.0); - cell = row.getCell((short) 0); - assertEquals("Lorem", cell.getRichStringCellValue().getString()); - } - } - - @Test - void testLoadStyles() throws Exception { - try (XSSFWorkbook workbook = new XSSFWorkbook(_ssSamples.openResourceAsStream("styles.xlsx"))) { - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell((short) 0); - CellStyle style = cell.getCellStyle(); - assertNotNull(style); - } - } - - @Test - void testLoadPictures() throws Exception { - try (XSSFWorkbook workbook = new XSSFWorkbook(_ssSamples.openResourceAsStream("picture.xlsx"))) { - List<XSSFPictureData> pictures = workbook.getAllPictures(); - assertEquals(1, pictures.size()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCalculationChain.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestCalculationChain.java deleted file mode 100644 index 8f89223e73..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCalculationChain.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell; - -public final class TestCalculationChain { - - @Test - void test46535() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("46535.xlsx")) { - - CalculationChain chain = wb.getCalculationChain(); - //the bean holding the reference to the formula to be deleted - CTCalcCell c = chain.getCTCalcChain().getCArray(0); - int cnt = chain.getCTCalcChain().sizeOfCArray(); - assertEquals(10, c.getI()); - assertEquals("E1", c.getR()); - - XSSFSheet sheet = wb.getSheet("Test"); - XSSFCell cell = sheet.getRow(0).getCell(4); - - assertEquals(CellType.FORMULA, cell.getCellType()); - cell.setCellFormula(null); - - //the count of items is less by one - c = chain.getCTCalcChain().getCArray(0); - int cnt2 = chain.getCTCalcChain().sizeOfCArray(); - assertEquals(cnt - 1, cnt2); - //the first item in the calculation chain is the former second one - assertEquals(10, c.getI()); - assertEquals("C1", c.getR()); - - assertEquals(CellType.STRING, cell.getCellType()); - cell.setCellValue("ABC"); - assertEquals(CellType.STRING, cell.getCellType()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java deleted file mode 100644 index a02da05778..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java +++ /dev/null @@ -1,323 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; -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.util.CellAddress; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComment; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCommentList; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComments; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; - - -class TestCommentsTable { - - private static final String TEST_A2_TEXT = "test A2 text"; - private static final String TEST_A1_TEXT = "test A1 text"; - private static final String TEST_AUTHOR = "test author"; - - @Test - void findAuthor() { - CommentsTable sheetComments = new CommentsTable(); - assertEquals(1, sheetComments.getNumberOfAuthors()); - assertEquals(0, sheetComments.findAuthor("")); - assertEquals("", sheetComments.getAuthor(0)); - - assertEquals(1, sheetComments.findAuthor(TEST_AUTHOR)); - assertEquals(2, sheetComments.findAuthor("another author")); - assertEquals(1, sheetComments.findAuthor(TEST_AUTHOR)); - assertEquals(3, sheetComments.findAuthor("YAA")); - assertEquals(2, sheetComments.findAuthor("another author")); - } - - @Test - void getCellComment() { - CommentsTable sheetComments = new CommentsTable(); - - CTComments comments = sheetComments.getCTComments(); - CTCommentList commentList = comments.getCommentList(); - - // Create 2 comments for A1 and A" cells - CTComment comment0 = commentList.insertNewComment(0); - comment0.setRef("A1"); - CTRst ctrst0 = CTRst.Factory.newInstance(); - ctrst0.setT(TEST_A1_TEXT); - comment0.setText(ctrst0); - CTComment comment1 = commentList.insertNewComment(0); - comment1.setRef("A2"); - CTRst ctrst1 = CTRst.Factory.newInstance(); - ctrst1.setT(TEST_A2_TEXT); - comment1.setText(ctrst1); - - // test finding the right comment for a cell - assertSame(comment0, sheetComments.getCTComment(new CellAddress("A1"))); - assertSame(comment1, sheetComments.getCTComment(new CellAddress("A2"))); - assertNull(sheetComments.getCTComment(new CellAddress("A3"))); - } - - - @Test - void existing() throws IOException { - try (Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { - Sheet sheet1 = workbook.getSheetAt(0); - Sheet sheet2 = workbook.getSheetAt(1); - - assertTrue(((XSSFSheet) sheet1).hasComments()); - assertFalse(((XSSFSheet) sheet2).hasComments()); - - // Comments should be in C5 and C7 - Row r5 = sheet1.getRow(4); - Row r7 = sheet1.getRow(6); - assertNotNull(r5.getCell(2).getCellComment()); - assertNotNull(r7.getCell(2).getCellComment()); - - // Check they have what we expect - // TODO: Rich text formatting - Comment cc5 = r5.getCell(2).getCellComment(); - Comment cc7 = r7.getCell(2).getCellComment(); - - assertEquals("Nick Burch", cc5.getAuthor()); - assertEquals("Nick Burch:\nThis is a comment", cc5.getString().getString()); - assertEquals(4, cc5.getRow()); - assertEquals(2, cc5.getColumn()); - - assertEquals("Nick Burch", cc7.getAuthor()); - assertEquals("Nick Burch:\nComment #1\n", cc7.getString().getString()); - assertEquals(6, cc7.getRow()); - assertEquals(2, cc7.getColumn()); - } - } - - @Test - void writeRead() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx")) { - XSSFSheet sheet1 = workbook.getSheetAt(0); - XSSFSheet sheet2 = workbook.getSheetAt(1); - - assertTrue(sheet1.hasComments()); - assertFalse(sheet2.hasComments()); - - // Change on comment on sheet 1, and add another into - // sheet 2 - Row r5 = sheet1.getRow(4); - Comment cc5 = r5.getCell(2).getCellComment(); - cc5.setAuthor("Apache POI"); - cc5.setString(new XSSFRichTextString("Hello!")); - - Row r2s2 = sheet2.createRow(2); - Cell c1r2s2 = r2s2.createCell(1); - assertNull(c1r2s2.getCellComment()); - - Drawing<?> dg = sheet2.createDrawingPatriarch(); - Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); - cc2.setAuthor("Also POI"); - cc2.setString(new XSSFRichTextString("A new comment")); - c1r2s2.setCellComment(cc2); - - // Save, and re-load the file - try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { - // Check we still have comments where we should do - sheet1 = workbookBack.getSheetAt(0); - sheet2 = workbookBack.getSheetAt(1); - assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); - assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); - assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); - - // And check they still have the contents they should do - assertEquals("Apache POI", - sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); - assertEquals("Nick Burch", - sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); - assertEquals("Also POI", - sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); - - assertEquals("Hello!", - sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); - } - } - } - - @Test - void readWriteMultipleAuthors() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx")) { - XSSFSheet sheet1 = workbook.getSheetAt(0); - XSSFSheet sheet2 = workbook.getSheetAt(1); - - assertTrue(sheet1.hasComments()); - assertFalse(sheet2.hasComments()); - - assertEquals("Nick Burch", - sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); - assertEquals("Nick Burch", - sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); - assertEquals("Torchbox", - sheet1.getRow(12).getCell(2).getCellComment().getAuthor()); - - // Save, and re-load the file - try (XSSFWorkbook workbookBack = XSSFTestDataSamples.writeOutAndReadBack(workbook)) { - - // Check we still have comments where we should do - sheet1 = workbookBack.getSheetAt(0); - assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); - assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); - assertNotNull(sheet1.getRow(12).getCell(2).getCellComment()); - - // And check they still have the contents they should do - assertEquals("Nick Burch", - sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); - assertEquals("Nick Burch", - sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); - assertEquals("Torchbox", - sheet1.getRow(12).getCell(2).getCellComment().getAuthor()); - - // Todo - check text too, once bug fixed - } - } - } - - @Test - void removeComment() { - final CellAddress addrA1 = new CellAddress("A1"); - final CellAddress addrA2 = new CellAddress("A2"); - final CellAddress addrA3 = new CellAddress("A3"); - - CommentsTable sheetComments = new CommentsTable(); - CTComment a1 = sheetComments.newComment(addrA1); - CTComment a2 = sheetComments.newComment(addrA2); - CTComment a3 = sheetComments.newComment(addrA3); - - assertSame(a1, sheetComments.getCTComment(addrA1)); - assertSame(a2, sheetComments.getCTComment(addrA2)); - assertSame(a3, sheetComments.getCTComment(addrA3)); - assertEquals(3, sheetComments.getNumberOfComments()); - - assertTrue(sheetComments.removeComment(addrA1)); - assertEquals(2, sheetComments.getNumberOfComments()); - assertNull(sheetComments.getCTComment(addrA1)); - assertSame(a2, sheetComments.getCTComment(addrA2)); - assertSame(a3, sheetComments.getCTComment(addrA3)); - - assertTrue(sheetComments.removeComment(addrA2)); - assertEquals(1, sheetComments.getNumberOfComments()); - assertNull(sheetComments.getCTComment(addrA1)); - assertNull(sheetComments.getCTComment(addrA2)); - assertSame(a3, sheetComments.getCTComment(addrA3)); - - assertTrue(sheetComments.removeComment(addrA3)); - assertEquals(0, sheetComments.getNumberOfComments()); - assertNull(sheetComments.getCTComment(addrA1)); - assertNull(sheetComments.getCTComment(addrA2)); - assertNull(sheetComments.getCTComment(addrA3)); - } - - @Test - void bug54920() throws IOException { - final Workbook workbook = new XSSFWorkbook(); - final Sheet sheet = workbook.createSheet("sheet01"); - // create anchor - CreationHelper helper = sheet.getWorkbook().getCreationHelper(); - ClientAnchor anchor = helper.createClientAnchor(); - - // place comment in A1 - // NOTE - only occurs if a comment is placed in A1 first - Cell A1 = getCell(sheet, 0, 0); - //Cell A1 = getCell(sheet, 2, 2); - Drawing<?> drawing = sheet.createDrawingPatriarch(); - setComment(A1, drawing, "for A1", helper, anchor); - - // find comment in A1 before we set the comment in B2 - Comment commentA1 = A1.getCellComment(); - assertNotNull(commentA1, "Should still find the previous comment in A1, but had null"); - assertEquals("for A1", commentA1.getString().getString(), "should find correct comment in A1, but had null: " + commentA1); - - // place comment in B2, according to Bug 54920 this removes the comment in A1! - Cell B2 = getCell(sheet, 1, 1); - setComment(B2, drawing, "for B2", helper, anchor); - - // find comment in A1 - Comment commentB2 = B2.getCellComment(); - assertEquals("for B2", commentB2.getString().getString(), "should find correct comment in B2, but had null: " + commentB2); - - // find comment in A1 - commentA1 = A1.getCellComment(); - assertNotNull(commentA1, "Should still find the previous comment in A1, but had null"); - assertEquals("for A1", commentA1.getString().getString(), "should find correct comment in A1, but had null: " + commentA1); - - workbook.close(); - } - - // Set the comment on a sheet - // - private static void setComment(Cell cell, Drawing<?> drawing, String commentText, CreationHelper helper, ClientAnchor anchor) { - anchor.setCol1(cell.getColumnIndex()); - anchor.setCol2(cell.getColumnIndex()); - anchor.setRow1(cell.getRowIndex()); - anchor.setRow2(cell.getRowIndex()); - - // get comment, or create if it does not exist - // NOTE - only occurs if getCellComment is called first - Comment comment = cell.getCellComment(); - //Comment comment = null; - if (comment == null) { - comment = drawing.createCellComment(anchor); - } - comment.setAuthor("Test"); - - // attach the comment to the cell - comment.setString(helper.createRichTextString(commentText)); - cell.setCellComment(comment); - } - - // Get a cell, create as needed - // - private static Cell getCell(Sheet sheet, int rowIndex, int colIndex) { - Row row = sheet.getRow(rowIndex); - if (row == null) { - row = sheet.createRow(rowIndex); - } - - Cell cell = row.getCell(colIndex); - if (cell == null) { - cell = row.createCell(colIndex); - } - - return cell; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestExternalLinksTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestExternalLinksTable.java deleted file mode 100644 index 045a03601b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestExternalLinksTable.java +++ /dev/null @@ -1,146 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -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 java.io.IOException; - -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -public final class TestExternalLinksTable { - @Test - void none() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("SampleSS.xlsx")) { - assertNotNull(wb.getExternalLinksTable()); - assertEquals(0, wb.getExternalLinksTable().size()); - } - } - - @Test - void basicRead() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("ref-56737.xlsx")) { - assertNotNull(wb.getExternalLinksTable()); - assertEquals(1, wb.getExternalLinksTable().size()); - - ExternalLinksTable links = wb.getExternalLinksTable().get(0); - assertEquals(3, links.getSheetNames().size()); - assertEquals(2, links.getDefinedNames().size()); - - assertEquals("Uses", links.getSheetNames().get(0)); - assertEquals("Defines", links.getSheetNames().get(1)); - assertEquals("56737", links.getSheetNames().get(2)); - - Name name = links.getDefinedNames().get(0); - assertEquals("NR_Global_B2", name.getNameName()); - assertEquals(-1, name.getSheetIndex()); - assertNull(name.getSheetName()); - assertEquals("'Defines'!$B$2", name.getRefersToFormula()); - - name = links.getDefinedNames().get(1); - assertEquals("NR_To_A1", name.getNameName()); - assertEquals(1, name.getSheetIndex()); - assertEquals("Defines", name.getSheetName()); - assertEquals("'Defines'!$A$1", name.getRefersToFormula()); - - assertEquals("56737.xlsx", links.getLinkedFileName()); - } - } - - @Test - void basicReadWriteRead() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("ref-56737.xlsx")) { - Name name = wb.getExternalLinksTable().get(0).getDefinedNames().get(1); - name.setNameName("Testing"); - name.setRefersToFormula("$A$1"); - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(1, wbBack.getExternalLinksTable().size()); - ExternalLinksTable links = wbBack.getExternalLinksTable().get(0); - - name = links.getDefinedNames().get(0); - assertEquals("NR_Global_B2", name.getNameName()); - assertEquals(-1, name.getSheetIndex()); - assertNull(name.getSheetName()); - assertEquals("'Defines'!$B$2", name.getRefersToFormula()); - - name = links.getDefinedNames().get(1); - assertEquals("Testing", name.getNameName()); - assertEquals(1, name.getSheetIndex()); - assertEquals("Defines", name.getSheetName()); - assertEquals("$A$1", name.getRefersToFormula()); - } - } - - @Test - void readWithReferencesToTwoExternalBooks() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("ref2-56737.xlsx")) { - assertNotNull(wb.getExternalLinksTable()); - assertEquals(2, wb.getExternalLinksTable().size()); - - // Check the first one, links to 56737.xlsx - ExternalLinksTable links = wb.getExternalLinksTable().get(0); - assertEquals("56737.xlsx", links.getLinkedFileName()); - assertEquals(3, links.getSheetNames().size()); - assertEquals(2, links.getDefinedNames().size()); - - assertEquals("Uses", links.getSheetNames().get(0)); - assertEquals("Defines", links.getSheetNames().get(1)); - assertEquals("56737", links.getSheetNames().get(2)); - - Name name = links.getDefinedNames().get(0); - assertEquals("NR_Global_B2", name.getNameName()); - assertEquals(-1, name.getSheetIndex()); - assertNull(name.getSheetName()); - assertEquals("'Defines'!$B$2", name.getRefersToFormula()); - - name = links.getDefinedNames().get(1); - assertEquals("NR_To_A1", name.getNameName()); - assertEquals(1, name.getSheetIndex()); - assertEquals("Defines", name.getSheetName()); - assertEquals("'Defines'!$A$1", name.getRefersToFormula()); - - - // Check the second one, links to 56737.xls, slightly differently - links = wb.getExternalLinksTable().get(1); - assertEquals("56737.xls", links.getLinkedFileName()); - assertEquals(2, links.getSheetNames().size()); - assertEquals(2, links.getDefinedNames().size()); - - assertEquals("Uses", links.getSheetNames().get(0)); - assertEquals("Defines", links.getSheetNames().get(1)); - - name = links.getDefinedNames().get(0); - assertEquals("NR_Global_B2", name.getNameName()); - assertEquals(-1, name.getSheetIndex()); - assertNull(name.getSheetName()); - assertEquals("'Defines'!$B$2", name.getRefersToFormula()); - - name = links.getDefinedNames().get(1); - assertEquals("NR_To_A1", name.getNameName()); - assertEquals(1, name.getSheetIndex()); - assertEquals("Defines", name.getSheetName()); - assertEquals("'Defines'!$A$1", name.getRefersToFormula()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestMapInfo.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestMapInfo.java deleted file mode 100644 index 290e5fcd0c..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestMapInfo.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.ooxml.POIXMLDocumentPart; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFMap; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMapInfo; -import org.w3c.dom.Node; - -/** - * @author Roberto Manicardi - */ -public final class TestMapInfo { - @Test - void testMapInfoExists() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx")) { - - MapInfo mapInfo = null; - SingleXmlCells singleXMLCells = null; - - for (POIXMLDocumentPart p : wb.getRelations()) { - - - if (p instanceof MapInfo) { - mapInfo = (MapInfo) p; - - - CTMapInfo ctMapInfo = mapInfo.getCTMapInfo(); - - assertNotNull(ctMapInfo); - - assertEquals(1, ctMapInfo.sizeOfSchemaArray()); - - for (XSSFMap map : mapInfo.getAllXSSFMaps()) { - Node xmlSchema = map.getSchema(); - assertNotNull(xmlSchema); - } - } - } - - XSSFSheet sheet1 = wb.getSheetAt(0); - - for (POIXMLDocumentPart p : sheet1.getRelations()) { - - if (p instanceof SingleXmlCells) { - singleXMLCells = (SingleXmlCells) p; - } - - } - assertNotNull(mapInfo); - assertNotNull(singleXMLCells); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestSharedStringsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestSharedStringsTable.java deleted file mode 100644 index ae9d6398d4..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestSharedStringsTable.java +++ /dev/null @@ -1,244 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -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.XSSFFont; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRElt; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; - -/** - * Test {@link SharedStringsTable}, the cache of strings in a workbook - */ -public final class TestSharedStringsTable { - @Test - void testCreateNew() { - SharedStringsTable sst = new SharedStringsTable(); - - CTRst st; - int idx; - - // Check defaults - assertEquals(0, sst.getCount()); - assertEquals(0, sst.getCount()); - assertEquals(0, sst.getUniqueCount()); - - st = CTRst.Factory.newInstance(); - st.setT("Hello, World!"); - - idx = sst.addEntry(st); - assertEquals(0, idx); - assertEquals(1, sst.getCount()); - assertEquals(1, sst.getUniqueCount()); - - //add the same entry again - idx = sst.addEntry(st); - assertEquals(0, idx); - assertEquals(2, sst.getCount()); - assertEquals(1, sst.getUniqueCount()); - - //and again - idx = sst.addEntry(st); - assertEquals(0, idx); - assertEquals(3, sst.getCount()); - assertEquals(1, sst.getUniqueCount()); - - st = CTRst.Factory.newInstance(); - st.setT("Second string"); - - idx = sst.addEntry(st); - assertEquals(1, idx); - assertEquals(4, sst.getCount()); - assertEquals(2, sst.getUniqueCount()); - - //add the same entry again - idx = sst.addEntry(st); - assertEquals(1, idx); - assertEquals(5, sst.getCount()); - assertEquals(2, sst.getUniqueCount()); - - st = CTRst.Factory.newInstance(); - CTRElt r = st.addNewR(); - CTRPrElt pr = r.addNewRPr(); - pr.addNewColor().setRgb(new byte[]{(byte)0xFF, 0, 0}); //red - pr.addNewI().setVal(true); //bold - pr.addNewB().setVal(true); //italic - r.setT("Second string"); - - idx = sst.addEntry(st); - assertEquals(2, idx); - assertEquals(6, sst.getCount()); - assertEquals(3, sst.getUniqueCount()); - - idx = sst.addEntry(st); - assertEquals(2, idx); - assertEquals(7, sst.getCount()); - assertEquals(3, sst.getUniqueCount()); - - //OK. the sst table is filled, check the contents - assertEquals("Hello, World!", sst.getItemAt(0).toString()); - assertEquals("Second string", sst.getItemAt(1).toString()); - assertEquals("Second string", sst.getItemAt(2).toString()); - } - - @Test - void testCreateUsingRichTextStrings() { - SharedStringsTable sst = new SharedStringsTable(); - - // Check defaults - assertNotNull(sst.getSharedStringItems()); - assertEquals(0, sst.getSharedStringItems().size()); - assertEquals(0, sst.getCount()); - assertEquals(0, sst.getUniqueCount()); - - int idx; - - XSSFRichTextString rts = new XSSFRichTextString("Hello, World!"); - - idx = sst.addSharedStringItem(rts); - assertEquals(0, idx); - assertEquals(1, sst.getCount()); - assertEquals(1, sst.getUniqueCount()); - - //add the same entry again - idx = sst.addSharedStringItem(rts); - assertEquals(0, idx); - assertEquals(2, sst.getCount()); - assertEquals(1, sst.getUniqueCount()); - - //and again - idx = sst.addSharedStringItem(rts); - assertEquals(0, idx); - assertEquals(3, sst.getCount()); - assertEquals(1, sst.getUniqueCount()); - - rts = new XSSFRichTextString("Second string"); - - idx = sst.addSharedStringItem(rts); - assertEquals(1, idx); - assertEquals(4, sst.getCount()); - assertEquals(2, sst.getUniqueCount()); - - //add the same entry again - idx = sst.addSharedStringItem(rts); - assertEquals(1, idx); - assertEquals(5, sst.getCount()); - assertEquals(2, sst.getUniqueCount()); - - rts = new XSSFRichTextString("Second string"); - XSSFFont font = new XSSFFont(); - font.setFontName("Arial"); - font.setBold(true); - rts.applyFont(font); - - idx = sst.addSharedStringItem(rts); - assertEquals(2, idx); - assertEquals(6, sst.getCount()); - assertEquals(3, sst.getUniqueCount()); - - idx = sst.addSharedStringItem(rts); - assertEquals(2, idx); - assertEquals(7, sst.getCount()); - assertEquals(3, sst.getUniqueCount()); - - //OK. the sst table is filled, check the contents - assertEquals(3, sst.getSharedStringItems().size()); - assertEquals("Hello, World!", sst.getItemAt(0).toString()); - assertEquals("Second string", sst.getItemAt(1).toString()); - assertEquals("Second string", sst.getItemAt(2).toString()); - } - - @Test - void testReadWrite() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx"); - SharedStringsTable sst1 = wb1.getSharedStringSource(); - - //serialize, read back and compare with the original - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - SharedStringsTable sst2 = wb2.getSharedStringSource(); - - assertEquals(sst1.getCount(), sst2.getCount()); - assertEquals(sst1.getUniqueCount(), sst2.getUniqueCount()); - - assertEquals(sst1.getCount(), sst2.getCount()); - - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - assertNotNull(wb3); - wb3.close(); - wb2.close(); - wb1.close(); - } - - /** - * Test for Bugzilla 48936 - * - * A specific sequence of strings can result in broken CDATA section in sharedStrings.xml file. - */ - @Test - void testBug48936() throws IOException { - Workbook w1 = new XSSFWorkbook(); - Sheet s = w1.createSheet(); - int i = 0; - - Path path = XSSFTestDataSamples.getSampleFile("48936-strings.txt").toPath(); - - final List<String> lst; - try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) { - lst = lines - .map(String::trim) - .filter(((Predicate<String>) String::isEmpty).negate()) - .collect(Collectors.toList()); - } - - for (String str : lst) { - s.createRow(i++).createCell(0).setCellValue(str); - } - - Workbook w2 = XSSFTestDataSamples.writeOutAndReadBack(w1); - w1.close(); - s = w2.getSheetAt(0); - i = 0; - for (String str : lst) { - String val = s.getRow(i++).getCell(0).getStringCellValue(); - assertEquals(str, val); - } - - Workbook w3 = XSSFTestDataSamples.writeOutAndReadBack(w2); - w2.close(); - assertNotNull(w3); - w3.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestStylesTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestStylesTable.java deleted file mode 100644 index a18313b577..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestStylesTable.java +++ /dev/null @@ -1,340 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -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 static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; -import java.util.Map; - -import org.apache.poi.ss.usermodel.BuiltinFormats; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public final class TestStylesTable { - private static final String testFile = "Formatting.xlsx"; - private static final String customDataFormat = "YYYY-mm-dd"; - - @BeforeAll - public static void assumeCustomDataFormatIsNotBuiltIn() { - assertEquals(-1, BuiltinFormats.getBuiltinFormat(customDataFormat)); - } - - @Test - void testCreateNew() { - StylesTable st = new StylesTable(); - - // Check defaults - assertNotNull(st.getCTStylesheet()); - assertEquals(1, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(0, st.getNumDataFormats()); - } - - @Test - void testCreateSaveLoad() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - StylesTable st = wb.getStylesSource(); - - assertNotNull(st.getCTStylesheet()); - assertEquals(1, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(0, st.getNumDataFormats()); - - st = XSSFTestDataSamples.writeOutAndReadBack(wb).getStylesSource(); - - assertNotNull(st.getCTStylesheet()); - assertEquals(1, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(0, st.getNumDataFormats()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } - } - - @Test - void testLoadExisting() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook(testFile)) { - assertNotNull(workbook.getStylesSource()); - - StylesTable st = workbook.getStylesSource(); - - doTestExisting(st); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(workbook)); - } - } - - @Test - void testLoadSaveLoad() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook(testFile)) { - assertNotNull(workbook.getStylesSource()); - - StylesTable st = workbook.getStylesSource(); - doTestExisting(st); - - st = XSSFTestDataSamples.writeOutAndReadBack(workbook).getStylesSource(); - doTestExisting(st); - } - } - - void doTestExisting(StylesTable st) { - // Check contents - assertNotNull(st.getCTStylesheet()); - assertEquals(11, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(8, st.getNumDataFormats()); - - assertEquals(2, st.getFonts().size()); - assertEquals(2, st.getFills().size()); - assertEquals(1, st.getBorders().size()); - - assertEquals("yyyy/mm/dd", st.getNumberFormatAt((short)165)); - assertEquals("yy/mm/dd", st.getNumberFormatAt((short)167)); - - assertNotNull(st.getStyleAt(0)); - assertNotNull(st.getStyleAt(1)); - assertNotNull(st.getStyleAt(2)); - - assertEquals(0, st.getStyleAt(0).getDataFormat()); - assertEquals(14, st.getStyleAt(1).getDataFormat()); - assertEquals(0, st.getStyleAt(2).getDataFormat()); - assertEquals(165, st.getStyleAt(3).getDataFormat()); - - assertEquals("yyyy/mm/dd", st.getStyleAt(3).getDataFormatString()); - assertEquals("[]", st.getExplicitTableStyleNames().toString()); - } - - @Test - void populateNew() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - StylesTable st = wb.getStylesSource(); - - assertNotNull(st.getCTStylesheet()); - assertEquals(1, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(0, st.getNumDataFormats()); - - int nf1 = st.putNumberFormat("yyyy-mm-dd"); - int nf2 = st.putNumberFormat("yyyy-mm-DD"); - assertEquals(nf1, st.putNumberFormat("yyyy-mm-dd")); - - st.putStyle(new XSSFCellStyle(st)); - - // Save and re-load - st = XSSFTestDataSamples.writeOutAndReadBack(wb).getStylesSource(); - - assertNotNull(st.getCTStylesheet()); - assertEquals(2, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(2, st.getNumDataFormats()); - - assertEquals("yyyy-mm-dd", st.getNumberFormatAt((short) nf1)); - assertEquals(nf1, st.putNumberFormat("yyyy-mm-dd")); - assertEquals(nf2, st.putNumberFormat("yyyy-mm-DD")); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } - } - - @Test - void populateExisting() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook(testFile)) { - assertNotNull(workbook.getStylesSource()); - - StylesTable st = workbook.getStylesSource(); - assertEquals(11, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(8, st.getNumDataFormats()); - - int nf1 = st.putNumberFormat("YYYY-mm-dd"); - int nf2 = st.putNumberFormat("YYYY-mm-DD"); - assertEquals(nf1, st.putNumberFormat("YYYY-mm-dd")); - - st = XSSFTestDataSamples.writeOutAndReadBack(workbook).getStylesSource(); - - assertEquals(11, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(10, st.getNumDataFormats()); - - assertEquals("YYYY-mm-dd", st.getNumberFormatAt((short) nf1)); - assertEquals(nf1, st.putNumberFormat("YYYY-mm-dd")); - assertEquals(nf2, st.putNumberFormat("YYYY-mm-DD")); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(workbook)); - } - } - - @Test - void exceedNumberFormatLimit() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - StylesTable styles = wb.getStylesSource(); - for (int i = 0; i < styles.getMaxNumberOfDataFormats(); i++) { - styles.putNumberFormat("\"test" + i + " \"0"); - } - IllegalStateException e = assertThrows(IllegalStateException.class, - () -> styles.putNumberFormat("\"anotherformat \"0")); - assertTrue(e.getMessage().startsWith("The maximum number of Data Formats was exceeded.")); - } - } - - private static <K,V> void assertNotContainsKey(Map<K,V> map, K key) { - assertFalse(map.containsKey(key)); - } - private static <K,V> void assertNotContainsValue(Map<K,V> map, V value) { - assertFalse(map.containsValue(value)); - } - - @Test - void removeNumberFormat() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - final String fmt = customDataFormat; - final short fmtIdx = (short) wb1.getStylesSource().putNumberFormat(fmt); - - Cell cell = wb1.createSheet("test").createRow(0).createCell(0); - cell.setCellValue(5.25); - CellStyle style = wb1.createCellStyle(); - style.setDataFormat(fmtIdx); - cell.setCellStyle(style); - - assertEquals(fmt, cell.getCellStyle().getDataFormatString()); - assertEquals(fmt, wb1.getStylesSource().getNumberFormatAt(fmtIdx)); - - // remove the number format from the workbook - assertTrue(wb1.getStylesSource().removeNumberFormat(fmt), "The format is removed on first call"); - assertThrows(IllegalStateException.class, () -> wb1.getStylesSource().removeNumberFormat(fmt)); - - // number format in CellStyles should be restored to default number format - final short defaultFmtIdx = 0; - final String defaultFmt = BuiltinFormats.getBuiltinFormat(0); - assertEquals(defaultFmtIdx, style.getDataFormat()); - assertEquals(defaultFmt, style.getDataFormatString()); - - // The custom number format should be entirely removed from the workbook - Map<Short, String> numberFormats = wb1.getStylesSource().getNumberFormats(); - assertNotContainsKey(numberFormats, fmtIdx); - assertNotContainsValue(numberFormats, fmt); - - // The default style shouldn't be added back to the styles source because it's built-in - assertEquals(0, wb1.getStylesSource().getNumDataFormats()); - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutCloseAndReadBack(wb1)) { - - cell = wb2.getSheet("test").getRow(0).getCell(0); - style = cell.getCellStyle(); - - // number format in CellStyles should be restored to default number format - assertEquals(defaultFmtIdx, style.getDataFormat()); - assertEquals(defaultFmt, style.getDataFormatString()); - - // The custom number format should be entirely removed from the workbook - numberFormats = wb2.getStylesSource().getNumberFormats(); - assertNotContainsKey(numberFormats, fmtIdx); - assertNotContainsValue(numberFormats, fmt); - - // The default style shouldn't be added back to the styles source because it's built-in - assertEquals(0, wb2.getStylesSource().getNumDataFormats()); - } - } - } - - @Test - void maxNumberOfDataFormats() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - StylesTable styles = wb.getStylesSource(); - - // Check default limit - int n = styles.getMaxNumberOfDataFormats(); - // https://support.office.com/en-us/article/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 - assertTrue(200 <= n); - assertTrue(n <= 250); - - // Check upper limit - n = Integer.MAX_VALUE; - styles.setMaxNumberOfDataFormats(n); - assertEquals(n, styles.getMaxNumberOfDataFormats()); - - // Check negative (illegal) limits - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> styles.setMaxNumberOfDataFormats(-1), - "Expected to get an IllegalArgumentException(\"Maximum Number of Data Formats must be greater than or equal to 0\")"); - assertTrue(e.getMessage().startsWith("Maximum Number of Data Formats must be greater than or equal to 0")); - } - } - - @Test - void addDataFormatsBeyondUpperLimit() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - StylesTable styles = wb.getStylesSource(); - styles.setMaxNumberOfDataFormats(0); - - // Try adding a format beyond the upper limit - IllegalStateException e = assertThrows(IllegalStateException.class, () -> styles.putNumberFormat("\"test \"0")); - assertTrue(e.getMessage().startsWith("The maximum number of Data Formats was exceeded.")); - } - } - - @Test - void decreaseUpperLimitBelowCurrentNumDataFormats() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - StylesTable styles = wb.getStylesSource(); - styles.putNumberFormat(customDataFormat); - - // Try decreasing the upper limit below the current number of formats - IllegalStateException e = assertThrows(IllegalStateException.class, () -> styles.setMaxNumberOfDataFormats(0)); - assertTrue(e.getMessage().startsWith("Cannot set the maximum number of data formats less than the current quantity.")); - } - } - - @Test - void testLoadWithAlternateContent() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("style-alternate-content.xlsx")) { - assertNotNull(workbook.getStylesSource()); - - StylesTable st = workbook.getStylesSource(); - assertNotNull(st); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(workbook)); - } - } - - @Test - void testReplaceStyle() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("style-alternate-content.xlsx")) { - assertNotNull(workbook.getStylesSource()); - - StylesTable st = workbook.getStylesSource(); - assertNotNull(st); - - st.replaceCellStyleXfAt(0, st.getCellStyleXfAt(1)); - st.replaceCellStyleXfAt(1, st.getCellStyleXfAt(1)); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(workbook)); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java deleted file mode 100644 index b50d691185..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java +++ /dev/null @@ -1,268 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.commons.codec.binary.Hex; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.ThemesTable.ThemeElement; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFFont; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; - -class TestThemesTable { - private static final String testFileComplex = "Themes2.xlsx"; - // TODO .xls version available too, add HSSF support then check - - // For offline testing - private static final boolean createFiles = false; - - // What colours they should show up as - private static final String[] rgbExpected = { - "ffffff", // Lt1 - "000000", // Dk1 - "eeece1", // Lt2 - "1f497d", // DK2 - "4f81bd", // Accent1 - "c0504d", // Accent2 - "9bbb59", // Accent3 - "8064a2", // Accent4 - "4bacc6", // Accent5 - "f79646", // Accent6 - "0000ff", // Hlink - "800080" // FolHlink - }; - - @Test - void testThemesTableColors() throws Exception { - // Load our two test workbooks - String testFileSimple = "Themes.xlsx"; - XSSFWorkbook simple = XSSFTestDataSamples.openSampleWorkbook(testFileSimple); - XSSFWorkbook complex = XSSFTestDataSamples.openSampleWorkbook(testFileComplex); - // Save and re-load them, to check for stability across that - XSSFWorkbook simpleRS = XSSFTestDataSamples.writeOutAndReadBack(simple); - XSSFWorkbook complexRS = XSSFTestDataSamples.writeOutAndReadBack(complex); - // Fetch fresh copies to test with - simple.close(); - simple = XSSFTestDataSamples.openSampleWorkbook(testFileSimple); - complex.close(); - complex = XSSFTestDataSamples.openSampleWorkbook(testFileComplex); - // Files and descriptions - Map<String,XSSFWorkbook> workbooks = new LinkedHashMap<>(); - workbooks.put(testFileSimple, simple); - workbooks.put("Re-Saved_" + testFileSimple, simpleRS); - workbooks.put(testFileComplex, complex); - workbooks.put("Re-Saved_" + testFileComplex, complexRS); - - // Sanity check - assertEquals(12, rgbExpected.length); - - // Check each workbook in turn, and verify that the colours - // for the theme-applied cells in Column A are correct - for (String whatWorkbook : workbooks.keySet()) { - XSSFWorkbook workbook = workbooks.get(whatWorkbook); - XSSFSheet sheet = workbook.getSheetAt(0); - int startRN = 0; - if (whatWorkbook.endsWith(testFileComplex)) startRN++; - - for (int rn=startRN; rn<rgbExpected.length+startRN; rn++) { - XSSFRow row = sheet.getRow(rn); - assertNotNull(row, "Missing row " + rn + " in " + whatWorkbook); - String ref = (new CellReference(rn, 0)).formatAsString(); - XSSFCell cell = row.getCell(0); - assertNotNull(cell, "Missing cell " + ref + " in " + whatWorkbook); - - int expectedThemeIdx = rn-startRN; - ThemeElement themeElem = ThemeElement.byId(expectedThemeIdx); - assertEquals(themeElem.name.toLowerCase(Locale.ROOT), cell.getStringCellValue(), - "Wrong theme at " + ref + " in " + whatWorkbook); - - // Fonts are theme-based in their colours - XSSFFont font = cell.getCellStyle().getFont(); - CTColor ctColor = font.getCTFont().getColorArray(0); - assertNotNull(ctColor); - assertTrue(ctColor.isSetTheme()); - assertEquals(themeElem.idx, ctColor.getTheme()); - - // Get the colour, via the theme - XSSFColor color = font.getXSSFColor(); - // Theme colours aren't tinted - assertFalse(color.hasTint()); - // Check the RGB part (no tint) - assertEquals(rgbExpected[expectedThemeIdx], Hex.encodeHexString(color.getRGB()), - "Wrong theme colour " + themeElem.name + " on " + whatWorkbook); - long themeIdx = font.getCTFont().getColorArray(0).getTheme(); - assertEquals(expectedThemeIdx, themeIdx, - "Wrong theme index " + expectedThemeIdx + " on " + whatWorkbook); - - if (createFiles) { - XSSFCellStyle cs = row.getSheet().getWorkbook().createCellStyle(); - cs.setFillForegroundColor(color); - cs.setFillPattern(FillPatternType.SOLID_FOREGROUND); - row.createCell(1).setCellStyle(cs); - } - } - - if (createFiles) { - FileOutputStream fos = new FileOutputStream("Generated_"+whatWorkbook); - workbook.write(fos); - fos.close(); - } - } - - simpleRS.close(); - simple.close(); - complexRS.close(); - complex.close(); - } - - /** - * Ensure that, for a file with themes, we can correctly - * read both the themed and non-themed colours back. - * Column A = Theme Foreground - * Column B = Theme Foreground - * Column C = Explicit Colour Foreground - * Column E = Explicit Colour Background, Black Foreground - * Column G = Conditional Formatting Backgrounds - * - * Note - Grey Row has an odd way of doing the styling... - */ - @Test - void themedAndNonThemedColours() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(testFileComplex)) { - XSSFSheet sheet = wb.getSheetAt(0); - - String[] names = {"White", "Black", "Grey", "Dark Blue", "Blue", "Red", "Green"}; - String[] explicitFHexes = {"FFFFFFFF", "FF000000", "FFC0C0C0", "FF002060", - "FF0070C0", "FFFF0000", "FF00B050"}; - String[] explicitBHexes = {"FFFFFFFF", "FF000000", "FFC0C0C0", "FF002060", - "FF0000FF", "FFFF0000", "FF00FF00"}; - assertEquals(7, names.length); - - // Check the non-CF colours in Columns A, B, C and E - for (int rn = 1; rn < 8; rn++) { - int idx = rn - 1; - XSSFRow row = sheet.getRow(rn); - assertNotNull(row, "Missing row " + rn); - - // Theme cells come first - XSSFCell themeCell = row.getCell(0); - ThemeElement themeElem = ThemeElement.byId(idx); - assertCellContents(themeElem.name, themeCell); - - // Sanity check names - assertCellContents(names[idx], row.getCell(1)); - assertCellContents(names[idx], row.getCell(2)); - assertCellContents(names[idx], row.getCell(4)); - - - // Check the colours - - // A: Theme Based, Foreground - XSSFCellStyle style = themeCell.getCellStyle(); - XSSFColor color = style.getFont().getXSSFColor(); - assertTrue(color.isThemed()); - assertEquals(idx, color.getTheme()); - assertEquals(rgbExpected[idx], Hex.encodeHexString(color.getRGB())); - - // B: Theme Based, Foreground - XSSFCell cell = row.getCell(1); - style = cell.getCellStyle(); - color = style.getFont().getXSSFColor(); - assertTrue(color.isThemed()); - if (idx != 2) { - assertEquals(idx, color.getTheme()); - assertEquals(rgbExpected[idx], Hex.encodeHexString(color.getRGB())); - } else { - assertEquals(1, color.getTheme()); - assertEquals(0.50, color.getTint(), 0.001); - } - - // C: Explicit, Foreground - cell = row.getCell(2); - style = cell.getCellStyle(); - color = style.getFont().getXSSFColor(); - assertFalse(color.isThemed()); - assertEquals(explicitFHexes[idx], color.getARGBHex()); - - // E: Explicit Background, Foreground all Black - cell = row.getCell(4); - style = cell.getCellStyle(); - - color = style.getFont().getXSSFColor(); - assertTrue(color.isThemed()); - assertEquals("FF000000", color.getARGBHex()); - - color = style.getFillForegroundXSSFColor(); - assertFalse(color.isThemed()); - assertEquals(explicitBHexes[idx], color.getARGBHex()); - color = style.getFillBackgroundColorColor(); - assertFalse(color.isThemed()); - assertNull(color.getARGBHex()); - } - } - - // Check the CF colours - // TODO - } - private static void assertCellContents(String expected, XSSFCell cell) { - assertNotNull(cell); - assertEquals(expected.toLowerCase(Locale.ROOT), - cell.getStringCellValue().toLowerCase(Locale.ROOT)); - } - - @Test - @SuppressWarnings("resource") - void testAddNew() { - XSSFWorkbook wb = new XSSFWorkbook(); - wb.createSheet(); - assertNull(wb.getTheme()); - - StylesTable styles = wb.getStylesSource(); - assertNull(styles.getTheme()); - - styles.ensureThemesTable(); - - assertNotNull(styles.getTheme()); - assertNotNull(wb.getTheme()); - - wb = XSSFTestDataSamples.writeOutAndReadBack(wb); - styles = wb.getStylesSource(); - assertNotNull(styles.getTheme()); - assertNotNull(wb.getTheme()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TempFileRecordingSXSSFWorkbookWithCustomZipEntrySource.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TempFileRecordingSXSSFWorkbookWithCustomZipEntrySource.java deleted file mode 100644 index 68398310f0..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TempFileRecordingSXSSFWorkbookWithCustomZipEntrySource.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.streaming; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.poifs.crypt.temp.SXSSFWorkbookWithCustomZipEntrySource; -import org.apache.poi.poifs.crypt.temp.SheetDataWriterWithDecorator; - -// a class to record a list of temporary files that are written to disk -// afterwards, a test function can check whether these files were encrypted or not -public class TempFileRecordingSXSSFWorkbookWithCustomZipEntrySource extends SXSSFWorkbookWithCustomZipEntrySource { - - private final List<File> tempFiles = new ArrayList<>(); - - List<File> getTempFiles() { - return new ArrayList<>(tempFiles); - } - - @Override - protected SheetDataWriter createSheetDataWriter() throws IOException { - return new TempFileRecordingSheetDataWriterWithDecorator(); - } - - class TempFileRecordingSheetDataWriterWithDecorator extends SheetDataWriterWithDecorator { - - TempFileRecordingSheetDataWriterWithDecorator() throws IOException { - super(); - tempFiles.add(getTempFile()); - } - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestAutoSizeColumnTracker.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestAutoSizeColumnTracker.java deleted file mode 100644 index f7161fd0e9..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestAutoSizeColumnTracker.java +++ /dev/null @@ -1,225 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.streaming; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetUtil; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - - -/** - * Tests the auto-sizing behaviour of {@link SXSSFSheet} when not all - * rows fit into the memory window size etc. - * - * see Bug #57450 which reported the original misbehaviour - */ -class TestAutoSizeColumnTracker { - - private SXSSFSheet sheet; - private SXSSFWorkbook workbook; - private AutoSizeColumnTracker tracker; - private static final SortedSet<Integer> columns; - static { - SortedSet<Integer>_columns = new TreeSet<>(); - _columns.add(0); - _columns.add(1); - _columns.add(3); - columns = Collections.unmodifiableSortedSet(_columns); - } - private static final String SHORT_MESSAGE = "short"; - private static final String LONG_MESSAGE = "This is a test of a long message! This is a test of a long message!"; - - @BeforeEach - void setUpSheetAndWorkbook() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - tracker = new AutoSizeColumnTracker(sheet); - } - - @AfterEach - void tearDownSheetAndWorkbook() throws IOException { - if (sheet != null) { - sheet.dispose(); - } - if (workbook != null) { - workbook.close(); - } - } - - @Test - void trackAndUntrackColumn() { - assumeTrue(tracker.getTrackedColumns().isEmpty()); - tracker.trackColumn(0); - Set<Integer> expected = new HashSet<>(); - expected.add(0); - assertEquals(expected, tracker.getTrackedColumns()); - tracker.untrackColumn(0); - assertTrue(tracker.getTrackedColumns().isEmpty()); - } - - @Test - void trackAndUntrackColumns() { - assumeTrue(tracker.getTrackedColumns().isEmpty()); - tracker.trackColumns(columns); - assertEquals(columns, tracker.getTrackedColumns()); - tracker.untrackColumn(3); - tracker.untrackColumn(0); - tracker.untrackColumn(1); - assertTrue(tracker.getTrackedColumns().isEmpty()); - tracker.trackColumn(0); - tracker.trackColumns(columns); - tracker.untrackColumn(4); - assertEquals(columns, tracker.getTrackedColumns()); - tracker.untrackColumns(columns); - assertTrue(tracker.getTrackedColumns().isEmpty()); - } - - @Test - void trackAndUntrackAllColumns() { - createColumnsAndTrackThemAll(); - tracker.untrackAllColumns(); - assertTrue(tracker.getTrackedColumns().isEmpty()); - } - - @Test - void isColumnTracked() { - assumeFalse(tracker.isColumnTracked(0)); - tracker.trackColumn(0); - assertTrue(tracker.isColumnTracked(0)); - tracker.untrackColumn(0); - assertFalse(tracker.isColumnTracked(0)); - } - - @Test - void isColumnTrackedAndTrackAllColumns() { - createColumnsAndTrackThemAll(); - tracker.untrackColumn(0); - SortedSet<Integer> _newColumns = new TreeSet<>(); - _newColumns.add(1); - _newColumns.add(3); - SortedSet<Integer> newColumns = Collections.unmodifiableSortedSet(_newColumns); - assertEquals(newColumns, tracker.getTrackedColumns()); - assertFalse(tracker.isColumnTracked(0)); - } - - @Test - void getTrackedColumns() { - assumeTrue(tracker.getTrackedColumns().isEmpty()); - - for (int column : columns) { - tracker.trackColumn(column); - } - - assertEquals(3, tracker.getTrackedColumns().size()); - assertEquals(columns, tracker.getTrackedColumns()); - } - - @Test - void isAllColumnsTracked() { - assertFalse(tracker.isAllColumnsTracked()); - tracker.trackAllColumns(); - assertTrue(tracker.isAllColumnsTracked()); - tracker.untrackAllColumns(); - assertFalse(tracker.isAllColumnsTracked()); - } - - @Test - void updateColumnWidths_and_getBestFitColumnWidth() { - tracker.trackAllColumns(); - Row row1 = sheet.createRow(0); - Row row2 = sheet.createRow(1); - // A1, B1, D1 - for (int column : columns) { - row1.createCell(column).setCellValue(LONG_MESSAGE); - row2.createCell(column+1).setCellValue(SHORT_MESSAGE); - } - tracker.updateColumnWidths(row1); - tracker.updateColumnWidths(row2); - assertEquals(0, sheet.addMergedRegion(CellRangeAddress.valueOf("D1:E1"))); - - assumeRequiredFontsAreInstalled(workbook, row1.getCell(columns.iterator().next())); - - // Excel 2013 and LibreOffice 4.2.8.2 both treat columns with merged regions as blank - /* A B C D E - * 1 LONG LONG LONGMERGE - * 2 SHORT SHORT SHORT - */ - - // measured in Excel 2013. Sizes may vary. - final int longMsgWidth = (int) (57.43*256); - final int shortMsgWidth = (int) (4.86*256); - - checkColumnWidth(longMsgWidth, 0, true); - checkColumnWidth(longMsgWidth, 0, false); - checkColumnWidth(longMsgWidth, 1, true); - checkColumnWidth(longMsgWidth, 1, false); - checkColumnWidth(shortMsgWidth, 2, true); - checkColumnWidth(shortMsgWidth, 2, false); - checkColumnWidth(-1, 3, true); - checkColumnWidth(longMsgWidth, 3, false); - checkColumnWidth(shortMsgWidth, 4, true); //but is it really? shouldn't autosizing column E use "" from E1 and SHORT from E2? - checkColumnWidth(shortMsgWidth, 4, false); - } - - private void checkColumnWidth(int expectedWidth, int column, boolean useMergedCells) { - final int bestFitWidth = tracker.getBestFitColumnWidth(column, useMergedCells); - if (bestFitWidth < 0 && expectedWidth < 0) return; - final double abs_error = Math.abs(bestFitWidth-expectedWidth); - final double rel_error = abs_error / expectedWidth; - assertTrue(rel_error <= 0.25, "check column width: " + rel_error + ", " + abs_error + ", " + expectedWidth + ", " + bestFitWidth); - } - - private static void assumeRequiredFontsAreInstalled(final Workbook workbook, final Cell cell) { - // autoSize will fail if required fonts are not installed, skip this test then - Font font = workbook.getFontAt(cell.getCellStyle().getFontIndex()); - assumeTrue(SheetUtil.canComputeColumnWidth(font), - "Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font); - } - - private void createColumnsAndTrackThemAll() { - assumeTrue(tracker.getTrackedColumns().isEmpty()); - tracker.trackAllColumns(); - assertTrue(tracker.getTrackedColumns().isEmpty()); - - Row row = sheet.createRow(0); - for (int column : columns) { - row.createCell(column); - } - // implicitly track the columns - tracker.updateColumnWidths(row); - assertEquals(columns, tracker.getTrackedColumns()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestDeferredSXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestDeferredSXSSFWorkbook.java deleted file mode 100644 index 74df887a50..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestDeferredSXSSFWorkbook.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -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; - -import org.apache.poi.ss.tests.usermodel.BaseTestXWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.DeferredSXSSFITestDataProvider; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -public final class TestDeferredSXSSFWorkbook extends BaseTestXWorkbook { - - public TestDeferredSXSSFWorkbook() { - super(DeferredSXSSFITestDataProvider.instance); - } - - @AfterEach - void tearDown() { - ((DeferredSXSSFITestDataProvider) _testDataProvider).cleanup(); - } - - /** - * cloning of sheets is not supported in SXSSF - */ - @Override - @Test - protected void cloneSheet() throws IOException { - RuntimeException e = assertThrows(RuntimeException.class, () -> super.cloneSheet()); - assertEquals("Not Implemented", e.getMessage()); - } - - /** - * cloning of sheets is not supported in SXSSF - */ - @Override - @Test - protected void sheetClone() throws IOException { - RuntimeException e = assertThrows(RuntimeException.class, () -> super.sheetClone()); - assertEquals("Not Implemented", e.getMessage()); - } - - /** - * Skip this test, as SXSSF doesn't update formulas on sheet name changes. - */ - @Override - @Disabled("SXSSF doesn't update formulas on sheet name changes, as most cells probably aren't in memory at the time") - protected void setSheetName() {} - - @Override - @Disabled("DeferredSXSSF code disposes rows in a way that breaks this test") - protected void parentReferences() {} - - @Override - @Disabled("DeferredSXSSF code disposes rows in a way that breaks this test") - protected void unicodeInAll() {} - - @Test - void existingWorkbook() throws IOException { - XSSFWorkbook xssfWb1 = new XSSFWorkbook(); - xssfWb1.createSheet("S1"); - DeferredSXSSFWorkbook wb1 = new DeferredSXSSFWorkbook(xssfWb1); - XSSFWorkbook xssfWb2 = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); - assertTrue(wb1.dispose()); - - DeferredSXSSFWorkbook wb2 = new DeferredSXSSFWorkbook(xssfWb2); - assertEquals(1, wb2.getNumberOfSheets()); - Sheet sheet = wb2.getStreamingSheetAt(0); - assertNotNull(sheet); - assertEquals("S1", sheet.getSheetName()); - assertTrue(wb2.dispose()); - xssfWb2.close(); - xssfWb1.close(); - - wb2.close(); - wb1.close(); - } - - @Test - void addToExistingWorkbook() throws IOException { - XSSFWorkbook xssfWb1 = new XSSFWorkbook(); - xssfWb1.createSheet("S1"); - Sheet sheet = xssfWb1.createSheet("S2"); - Row row = sheet.createRow(1); - Cell cell = row.createCell(1); - cell.setCellValue("value 2_1_1"); - DeferredSXSSFWorkbook wb1 = new DeferredSXSSFWorkbook(xssfWb1); - XSSFWorkbook xssfWb2 = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); - assertTrue(wb1.dispose()); - xssfWb1.close(); - - DeferredSXSSFWorkbook wb2 = new DeferredSXSSFWorkbook(xssfWb2); - // Add a row to the existing empty sheet - DeferredSXSSFSheet ssheet1 = wb2.getStreamingSheetAt(0); - ssheet1.setRowGenerator((ssxSheet) -> { - Row row1_1 = ssxSheet.createRow(1); - Cell cell1_1_1 = row1_1.createCell(1); - cell1_1_1.setCellValue("value 1_1_1"); - }); - - // Add a row to the existing non-empty sheet - DeferredSXSSFSheet ssheet2 = wb2.getStreamingSheetAt(1); - ssheet2.setRowGenerator((ssxSheet) -> { - Row row2_2 = ssxSheet.createRow(2); - Cell cell2_2_1 = row2_2.createCell(1); - cell2_2_1.setCellValue("value 2_2_1"); - }); - // Add a sheet with one row - DeferredSXSSFSheet ssheet3 = wb2.createSheet("S3"); - ssheet3.setRowGenerator((ssxSheet) -> { - Row row3_1 = ssxSheet.createRow(1); - Cell cell3_1_1 = row3_1.createCell(1); - cell3_1_1.setCellValue("value 3_1_1"); - }); - - XSSFWorkbook xssfWb3 = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb2); - wb2.close(); - - assertEquals(3, xssfWb3.getNumberOfSheets()); - // Verify sheet 1 - XSSFSheet sheet1 = xssfWb3.getSheetAt(0); - assertEquals("S1", sheet1.getSheetName()); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - XSSFRow row1_1 = sheet1.getRow(1); - assertNotNull(row1_1); - XSSFCell cell1_1_1 = row1_1.getCell(1); - assertNotNull(cell1_1_1); - assertEquals("value 1_1_1", cell1_1_1.getStringCellValue()); - // Verify sheet 2 - XSSFSheet sheet2 = xssfWb3.getSheetAt(1); - assertEquals("S2", sheet2.getSheetName()); - assertEquals(2, sheet2.getPhysicalNumberOfRows()); - Row row2_1 = sheet2.getRow(1); - assertNotNull(row2_1); - Cell cell2_1_1 = row2_1.getCell(1); - assertNotNull(cell2_1_1); - assertEquals("value 2_1_1", cell2_1_1.getStringCellValue()); - XSSFRow row2_2 = sheet2.getRow(2); - assertNotNull(row2_2); - XSSFCell cell2_2_1 = row2_2.getCell(1); - assertNotNull(cell2_2_1); - assertEquals("value 2_2_1", cell2_2_1.getStringCellValue()); - // Verify sheet 3 - XSSFSheet sheet3 = xssfWb3.getSheetAt(2); - assertEquals("S3", sheet3.getSheetName()); - assertEquals(1, sheet3.getPhysicalNumberOfRows()); - XSSFRow row3_1 = sheet3.getRow(1); - assertNotNull(row3_1); - XSSFCell cell3_1_1 = row3_1.getCell(1); - assertNotNull(cell3_1_1); - assertEquals("value 3_1_1", cell3_1_1.getStringCellValue()); - - xssfWb2.close(); - xssfWb3.close(); - wb1.close(); - } - - @Test - void sheetdataWriter() throws IOException { - DeferredSXSSFWorkbook wb = new DeferredSXSSFWorkbook(); - SXSSFSheet sh = wb.createSheet(); - assertSame(sh.getClass(), DeferredSXSSFSheet.class); - SheetDataWriter wr = sh.getSheetDataWriter(); - assertNull(wr); - wb.close(); - } - - @Test - void removeSheet() throws IOException { - try (DeferredSXSSFWorkbook wb = new DeferredSXSSFWorkbook()) { - DeferredSXSSFSheet sheet1 = wb.createSheet("sheet1"); - sheet1.setRowGenerator((sh) -> { - Row row = sh.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue("sheet1"); - }); - DeferredSXSSFSheet sheet2 = wb.createSheet("sheet2"); - sheet2.setRowGenerator((sh) -> { - Row row = sh.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue("sheet2"); - }); - wb.removeSheetAt(0); - try (XSSFWorkbook wb2 = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb)) { - assertNull(wb2.getSheet( "sheet1")); - XSSFSheet xssfSheet = wb2.getSheet( "sheet2"); - assertNotNull(xssfSheet); - assertEquals("sheet2", xssfSheet.getRow(0).getCell(0).getStringCellValue()); - } - } - } - - @Test - void gzipSheetdataWriter() throws IOException { - DeferredSXSSFWorkbook wb = new DeferredSXSSFWorkbook(); - - final int rowNum = 1000; - final int sheetNum = 5; - populateData(wb, 1000, 5); - - XSSFWorkbook xwb = DeferredSXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - for (int i = 0; i < sheetNum; i++) { - Sheet sh = xwb.getSheetAt(i); - assertEquals("sheet" + i, sh.getSheetName()); - for (int j = 0; j < rowNum; j++) { - Row row = sh.getRow(j); - assertNotNull(row, "row[" + j + "]"); - Cell cell1 = row.getCell(0); - assertEquals(new CellReference(cell1).formatAsString(), cell1.getStringCellValue()); - - Cell cell2 = row.getCell(1); - assertEquals(i, (int) cell2.getNumericCellValue()); - - Cell cell3 = row.getCell(2); - assertEquals(j, (int) cell3.getNumericCellValue()); - } - } - - assertTrue(wb.dispose()); - xwb.close(); - wb.close(); - } - - @Test - void workbookDispose() throws IOException { - DeferredSXSSFWorkbook wb1 = new DeferredSXSSFWorkbook(); - // the underlying writer is SheetDataWriter - assertWorkbookDispose(wb1); - wb1.close(); - - DeferredSXSSFWorkbook wb2 = new DeferredSXSSFWorkbook(); - wb2.setCompressTempFiles(true); - // the underlying writer is GZIPSheetDataWriter - assertWorkbookDispose(wb2); - wb2.close(); - } - - private static void assertWorkbookDispose(DeferredSXSSFWorkbook wb) { - populateData(wb, 1000, 5); - - for (Sheet sheet : wb) { - DeferredSXSSFSheet sxSheet = (DeferredSXSSFSheet) sheet; - assertNull(sxSheet.getSheetDataWriter()); - } - - assertTrue(wb.dispose()); - - for (Sheet sheet : wb) { - DeferredSXSSFSheet sxSheet = (DeferredSXSSFSheet) sheet; - assertNull(sxSheet.getSheetDataWriter()); - } - } - - private static void populateData(DeferredSXSSFWorkbook wb, final int rowNum, final int sheetNum) { - for (int i = 0; i < sheetNum; i++) { - DeferredSXSSFSheet sheet = wb.createSheet("sheet" + i); - int index = i; - sheet.setRowGenerator((sh) -> { - for (int j = 0; j < rowNum; j++) { - Row row = sh.createRow(j); - Cell cell1 = row.createCell(0); - cell1.setCellValue(new CellReference(cell1).formatAsString()); - - Cell cell2 = row.createCell(1); - cell2.setCellValue(index); - - Cell cell3 = row.createCell(2); - cell3.setCellValue(j); - } - }); - } - } - - void changeSheetNameWithSharedFormulas() { - /* not implemented */ - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestOutlining.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestOutlining.java deleted file mode 100644 index 2132956a66..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestOutlining.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -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.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -public final class TestOutlining { - @Test - void testSetRowGroupCollapsed() throws IOException { - SXSSFWorkbook wb2 = new SXSSFWorkbook(100); - wb2.setCompressTempFiles(true); - SXSSFSheet sheet2 = wb2.createSheet("new sheet"); - - int rowCount = 20; - for (int i = 0; i < rowCount; i++) { - sheet2.createRow(i); - } - - sheet2.groupRow(4, 9); - sheet2.groupRow(11, 19); - - sheet2.setRowGroupCollapsed(4, true); - - SXSSFRow r = sheet2.getRow(8); - assertTrue(r.getHidden()); - r = sheet2.getRow(10); - assertTrue(r.getCollapsed()); - r = sheet2.getRow(12); - assertNull(r.getHidden()); - wb2.dispose(); - - wb2.close(); - } - - @Test - void testSetRowGroupCollapsedError() throws IOException { - SXSSFWorkbook wb2 = new SXSSFWorkbook(100); - wb2.setCompressTempFiles(true); - SXSSFSheet sheet2 = wb2.createSheet("new sheet"); - - int rowCount = 20; - for (int i = 0; i < rowCount; i++) { - sheet2.createRow(i); - } - - sheet2.groupRow(4, 9); - sheet2.groupRow(11, 19); - - IllegalArgumentException e; - e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(3, true)); - assertTrue(e.getMessage().contains("row (3)")); - - e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(10, true)); - assertTrue(e.getMessage().contains("row (10)")); - - e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(0, true)); - assertTrue(e.getMessage().contains("row (0)")); - - e = assertThrows(IllegalArgumentException.class, () -> sheet2.setRowGroupCollapsed(20, true)); - assertTrue(e.getMessage().contains("Row does not exist"), "Had: " + e.getMessage()); - - SXSSFRow r = sheet2.getRow(8); - assertNotNull(r); - assertNull(r.getHidden()); - r = sheet2.getRow(10); - assertNull(r.getCollapsed()); - r = sheet2.getRow(12); - assertNull(r.getHidden()); - wb2.dispose(); - - wb2.close(); - } - - @Test - void testOutlineGettersHSSF() throws IOException { - HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); - HSSFSheet hssfSheet = hssfWorkbook.createSheet(); - hssfSheet.createRow(0); - hssfSheet.createRow(1); - hssfSheet.createRow(2); - hssfSheet.createRow(3); - hssfSheet.createRow(4); - hssfSheet.groupRow(1, 3); - hssfSheet.groupRow(2, 3); - - assertEquals(0, hssfSheet.getRow(0).getOutlineLevel()); - assertEquals(1, hssfSheet.getRow(1).getOutlineLevel()); - assertEquals(2, hssfSheet.getRow(2).getOutlineLevel()); - assertEquals(2, hssfSheet.getRow(3).getOutlineLevel()); - assertEquals(0, hssfSheet.getRow(4).getOutlineLevel()); - hssfWorkbook.close(); - } - - @Test - void testOutlineGettersXSSF() throws IOException { - XSSFWorkbook xssfWorkbook = new XSSFWorkbook(); - XSSFSheet xssfSheet = xssfWorkbook.createSheet(); - xssfSheet.createRow(0); - xssfSheet.createRow(1); - xssfSheet.createRow(2); - xssfSheet.createRow(3); - xssfSheet.createRow(4); - xssfSheet.groupRow(1, 3); - xssfSheet.groupRow(2, 3); - - assertEquals(0, xssfSheet.getRow(0).getOutlineLevel()); - assertEquals(1, xssfSheet.getRow(1).getOutlineLevel()); - assertEquals(2, xssfSheet.getRow(2).getOutlineLevel()); - assertEquals(2, xssfSheet.getRow(3).getOutlineLevel()); - assertEquals(0, xssfSheet.getRow(4).getOutlineLevel()); - xssfWorkbook.close(); - } - - @Test - void testOutlineGettersSXSSF() throws IOException { - SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(); - SXSSFSheet sxssfSheet = sxssfWorkbook.createSheet(); - sxssfSheet.createRow(0); - sxssfSheet.createRow(1); - sxssfSheet.createRow(2); - sxssfSheet.createRow(3); - sxssfSheet.createRow(4); - sxssfSheet.createRow(5); - - // nothing happens with empty row-area - sxssfSheet.groupRow(1, 0); - assertEquals(0, sxssfSheet.getRow(0).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(1).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(2).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(3).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(4).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - - sxssfSheet.groupRow(1, 3); - sxssfSheet.groupRow(2, 3); - - assertEquals(0, sxssfSheet.getRow(0).getOutlineLevel()); - assertEquals(1, sxssfSheet.getRow(1).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(2).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(3).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(4).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - - // add tests for direct setting - add row 4 to deepest group - sxssfSheet.setRowOutlineLevel(4, 2); - assertEquals(0, sxssfSheet.getRow(0).getOutlineLevel()); - assertEquals(1, sxssfSheet.getRow(1).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(2).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(3).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(4).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - - sxssfWorkbook.dispose(); - sxssfWorkbook.close(); - } - - @Test - void testOutlineGettersSXSSFSetOutlineLevel() throws IOException { - SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(); - SXSSFSheet sxssfSheet = sxssfWorkbook.createSheet(); - sxssfSheet.createRow(0); - sxssfSheet.createRow(1); - sxssfSheet.createRow(2); - sxssfSheet.createRow(3); - sxssfSheet.createRow(4); - sxssfSheet.createRow(5); - - // what happens with level below 1 - sxssfSheet.setRowOutlineLevel(0, -2); - assertEquals(-2, sxssfSheet.getRow(0).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(1).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(2).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(3).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(4).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - - // add tests for direct setting - sxssfSheet.setRowOutlineLevel(4, 2); - assertEquals(-2, sxssfSheet.getRow(0).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(1).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(2).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(3).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(4).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - - sxssfWorkbook.dispose(); - sxssfWorkbook.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFCell.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFCell.java deleted file mode 100644 index a1377a3b5d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFCell.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.spy; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -import javax.xml.namespace.QName; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.tests.usermodel.BaseTestXCell; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.xmlbeans.XmlCursor; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; - -/** - * Tests various functionality having to do with {@link SXSSFCell}. For instance support for - * particular datatypes, etc. - */ -class TestSXSSFCell extends BaseTestXCell { - - public TestSXSSFCell() { - super(SXSSFITestDataProvider.instance); - } - - @AfterAll - public static void tearDownClass() { - SXSSFITestDataProvider.instance.cleanup(); - } - - @Test - void testPreserveSpaces() throws IOException { - String[] samplesWithSpaces = { - " POI", - "POI ", - " POI ", - "\nPOI", - "\n\nPOI \n", - }; - for (String str : samplesWithSpaces) { - Workbook swb = _testDataProvider.createWorkbook(); - Cell sCell = swb.createSheet().createRow(0).createCell(0); - sCell.setCellValue(str); - assertEquals(sCell.getStringCellValue(), str); - - // read back as XSSF and check that xml:spaces="preserve" is set - XSSFWorkbook xwb = (XSSFWorkbook) _testDataProvider.writeOutAndReadBack(swb); - XSSFCell xCell = xwb.getSheetAt(0).getRow(0).getCell(0); - - CTRst is = xCell.getCTCell().getIs(); - assertNotNull(is); - XmlCursor c = is.newCursor(); - c.toNextToken(); - String t = c.getAttributeText(new QName("http://www.w3.org/XML/1998/namespace", "space")); - c.dispose(); - assertEquals( "preserve", t, "expected xml:spaces=\"preserve\" \"" + str + "\"" ); - xwb.close(); - swb.close(); - } - } - - @Test - void getCachedFormulaResultType_throwsISE_whenNotAFormulaCell() { - SXSSFCell instance = new SXSSFCell(null, CellType.BLANK); - assertThrows(IllegalStateException.class, instance::getCachedFormulaResultType); - } - - - @Test - void setCellValue_withTooLongRichTextString_throwsIAE() { - Cell cell = spy(new SXSSFCell(null, CellType.BLANK)); - int length = SpreadsheetVersion.EXCEL2007.getMaxTextLength() + 1; - String string = new String(new byte[length], StandardCharsets.UTF_8).replace("\0", "x"); - RichTextString richTextString = new XSSFRichTextString(string); - assertThrows(IllegalArgumentException.class, () -> cell.setCellValue(richTextString)); - } - - @Test - void getArrayFormulaRange_returnsNull() { - Cell cell = new SXSSFCell(null, CellType.BLANK); - CellRangeAddress result = cell.getArrayFormulaRange(); - assertNull(result); - } - - @Test - void isPartOfArrayFormulaGroup_returnsFalse() { - Cell cell = new SXSSFCell(null, CellType.BLANK); - boolean result = cell.isPartOfArrayFormulaGroup(); - assertFalse(result); - } - - @Test - void getErrorCellValue_returns0_onABlankCell() { - Cell cell = new SXSSFCell(null, CellType.BLANK); - assertEquals(CellType.BLANK, cell.getCellType()); - byte result = cell.getErrorCellValue(); - assertEquals(0, result); - } - - /** - * For now, {@link SXSSFCell} doesn't support array formulas. - * However, this test should be enabled if array formulas are implemented for SXSSF. - */ - @Override - @Disabled - protected void setBlank_removesArrayFormula_ifCellIsPartOfAnArrayFormulaGroupContainingOnlyThisCell() { - } - - /** - * For now, {@link SXSSFCell} doesn't support array formulas. - * However, this test should be enabled if array formulas are implemented for SXSSF. - */ - @Override - @Disabled - protected void setBlank_throwsISE_ifCellIsPartOfAnArrayFormulaGroupContainingOtherCells() { - } - - @Override - @Disabled - protected void setCellFormula_throwsISE_ifCellIsPartOfAnArrayFormulaGroupContainingOtherCells() { - } - - @Override - @Disabled - protected void removeFormula_turnsCellToBlank_whenFormulaWasASingleCellArrayFormula() { - } - - @Override - @Disabled - protected void setCellFormula_onASingleCellArrayFormulaCell_preservesTheValue() { - } - - @Disabled - protected void setCellFormula_isExceptionSafe_onBlankCell() { - } - - @Disabled - protected void setCellType_FORMULA_onAnArrayFormulaCell_doesNothing() { - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java deleted file mode 100644 index a344cb115f..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.streaming; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.List; - -import org.apache.poi.ss.usermodel.BaseTestDataValidation; -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.junit.jupiter.api.Test; - -class TestSXSSFDataValidation extends BaseTestDataValidation { - - public TestSXSSFDataValidation(){ - super(SXSSFITestDataProvider.instance); - } - - @Test - void test53965() throws Exception { - try (SXSSFWorkbook wb = new SXSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - List<? extends DataValidation> lst = sheet.getDataValidations(); //<-- works - assertEquals(0, lst.size()); - - //create the cell that will have the validation applied - sheet.createRow(0).createCell(0); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("SUM($A$1:$A$1) <= 3500"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - // this line caused XmlValueOutOfRangeException , see Bugzilla 3965 - lst = sheet.getDataValidations(); - assertEquals(1, lst.size()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFEvaluationSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFEvaluationSheet.java deleted file mode 100644 index 3600479f31..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFEvaluationSheet.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.streaming; - -import org.apache.poi.ss.formula.EvaluationSheet; -import org.apache.poi.ss.usermodel.BaseTestXEvaluationSheet; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.AfterEach; - -import java.io.IOException; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -class TestSXSSFEvaluationSheet extends BaseTestXEvaluationSheet { - private List<Workbook> workbooksToClose = new ArrayList<>(); - - @AfterEach - void closeWorkbooks() throws IOException { - for (Workbook workbook : workbooksToClose) { - workbook.close(); - } - } - - @Override - protected Map.Entry<Sheet, EvaluationSheet> getInstance() { - SXSSFWorkbook workbook = new SXSSFWorkbook(); - workbooksToClose.add(workbook); - - SXSSFSheet sheet = workbook.createSheet(); - return new AbstractMap.SimpleEntry<>(sheet, new SXSSFEvaluationSheet(sheet)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFFormulaEvaluation.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFFormulaEvaluation.java deleted file mode 100644 index b007d9b905..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFFormulaEvaluation.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.streaming.SXSSFFormulaEvaluator.RowFlushedException; -import org.apache.poi.xssf.streaming.SXSSFFormulaEvaluator.SheetsFlushedException; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * Formula Evaluation with SXSSF. - * - * Note that SXSSF can only evaluate formulas where the - * cell is in the current window, and all references - * from the cell are in the current window - */ -public final class TestSXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { - - public TestSXSSFFormulaEvaluation() { - super(SXSSFITestDataProvider.instance); - } - - void testSharedFormulas() throws IOException { - /* not implemented */ - } - - /** - * EvaluateAll will normally fail, as any reference or - * formula outside of the window will fail, and any - * non-active sheets will fail - */ - @Test - void testEvaluateAllFails() throws IOException { - try (SXSSFWorkbook wb = new SXSSFWorkbook(5)) { - SXSSFSheet s = wb.createSheet(); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - s.createRow(0).createCell(0).setCellFormula("1+2"); - s.createRow(1).createCell(0).setCellFormula("A21"); - for (int i = 2; i < 19; i++) { - s.createRow(i); - } - - // Cells outside window will fail, whether referenced or not - s.createRow(19).createCell(0).setCellFormula("A1+A2"); - s.createRow(20).createCell(0).setCellFormula("A1+A11+100"); - assertThrows(RowFlushedException.class, eval::evaluateAll, - "Evaluate All shouldn't work, as some cells outside the window"); - } - - // Inactive sheets will fail - try (XSSFWorkbook xwb = new XSSFWorkbook()) { - xwb.createSheet("Open"); - xwb.createSheet("Closed"); - - try (SXSSFWorkbook wb = new SXSSFWorkbook(xwb, 5)) { - SXSSFSheet s = wb.getSheet("Closed"); - s.flushRows(); - s = wb.getSheet("Open"); - s.createRow(0).createCell(0).setCellFormula("1+2"); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - assertThrows(SheetsFlushedException.class, eval::evaluateAll, "Evaluate All shouldn't work, as sheets flushed"); - } - } - } - - @Test - void testEvaluateRefOutsideWindowFails() throws IOException { - try (SXSSFWorkbook wb = new SXSSFWorkbook(5)) { - SXSSFSheet s = wb.createSheet(); - - s.createRow(0).createCell(0).setCellFormula("1+2"); - assertFalse(s.areAllRowsFlushed()); - assertEquals(-1, s.getLastFlushedRowNum()); - - for (int i = 1; i <= 19; i++) { - s.createRow(i); - } - Cell c = s.createRow(20).createCell(0); - c.setCellFormula("A1+100"); - - assertFalse(s.areAllRowsFlushed()); - assertEquals(15, s.getLastFlushedRowNum()); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - assertThrows(RowFlushedException.class, () -> eval.evaluateFormulaCell(c), - "Evaluate shouldn't work, as reference outside the window"); - } - } - - /** - * If all formula cells + their references are inside the window, - * then evaluation works - */ - @Test - void testEvaluateAllInWindow() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(5); - SXSSFSheet s = wb.createSheet(); - s.createRow(0).createCell(0).setCellFormula("1+2"); - s.createRow(1).createCell(1).setCellFormula("A1+10"); - s.createRow(2).createCell(2).setCellFormula("B2+100"); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - eval.evaluateAll(); - - assertEquals(3, (int)s.getRow(0).getCell(0).getNumericCellValue()); - assertEquals(13, (int)s.getRow(1).getCell(1).getNumericCellValue()); - assertEquals(113, (int)s.getRow(2).getCell(2).getNumericCellValue()); - - wb.close(); - } - - @Test - void testEvaluateRefInsideWindow() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(5); - SXSSFSheet s = wb.createSheet(); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - SXSSFCell c = s.createRow(0).createCell(0); - c.setCellValue(1.5); - - c = s.createRow(1).createCell(0); - c.setCellFormula("A1*2"); - - assertEquals(0, (int)c.getNumericCellValue()); - eval.evaluateFormulaCell(c); - assertEquals(3, (int)c.getNumericCellValue()); - - wb.close(); - } - - @Test - void testEvaluateSimple() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(5); - SXSSFSheet s = wb.createSheet(); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - SXSSFCell c = s.createRow(0).createCell(0); - c.setCellFormula("1+2"); - assertEquals(0, (int)c.getNumericCellValue()); - eval.evaluateFormulaCell(c); - assertEquals(3, (int)c.getNumericCellValue()); - - c = s.createRow(1).createCell(0); - c.setCellFormula("CONCATENATE(\"hello\",\" \",\"world\")"); - eval.evaluateFormulaCell(c); - assertEquals("hello world", c.getStringCellValue()); - - wb.close(); - } - - @Disabled( - "This test is disabled because it fails for SXSSF because " + - "handling of errors in formulas is slightly different than in XSSF, " + - "but this proved to be non-trivial to solve..." - ) - void testUpdateCachedFormulaResultFromErrorToNumber_bug46479() { - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFHyperlink.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFHyperlink.java deleted file mode 100644 index a29d0166e3..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFHyperlink.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import org.junit.jupiter.api.AfterEach; - -import org.apache.poi.ss.usermodel.BaseTestHyperlink; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.usermodel.XSSFHyperlink; - -/** - * Test setting hyperlinks in SXSSF - * - * @author Yegor Kozlov - */ -class TestSXSSFHyperlink extends BaseTestHyperlink { - - public TestSXSSFHyperlink() { - super(SXSSFITestDataProvider.instance); - } - - - @AfterEach - void tearDown(){ - SXSSFITestDataProvider.instance.cleanup(); - } - - @Override - public XSSFHyperlink copyHyperlink(Hyperlink link) { - // FIXME: replace with SXSSFHyperlink if it ever gets created - return new XSSFHyperlink(link); - } - -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java deleted file mode 100644 index 59a18bc7e5..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import org.apache.poi.ss.tests.usermodel.BaseTestXRow; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -/** - * Tests for XSSFRow - */ -public final class TestSXSSFRow extends BaseTestXRow { - - public TestSXSSFRow() { - super(SXSSFITestDataProvider.instance); - } - - - @AfterEach - void tearDown() { - ((SXSSFITestDataProvider) _testDataProvider).cleanup(); - } - - @Override - @Disabled("see <https://bz.apache.org/bugzilla/show_bug.cgi?id=62030#c1>") - protected void testCellShiftingRight(){ - // Remove when SXSSFRow.shiftCellsRight() is implemented. - } - - @Override - @Disabled("see <https://bz.apache.org/bugzilla/show_bug.cgi?id=62030#c1>") - protected void testCellShiftingLeft(){ - // Remove when SXSSFRow.shiftCellsLeft() is implemented. - } - - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java deleted file mode 100644 index 2d483e6185..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; - -import org.apache.poi.ss.tests.usermodel.BaseTestXSheet; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -public final class TestSXSSFSheet extends BaseTestXSheet { - - public TestSXSSFSheet() { - super(SXSSFITestDataProvider.instance); - } - - - @AfterEach - void tearDown(){ - SXSSFITestDataProvider.instance.cleanup(); - } - - @Override - protected void trackColumnsForAutoSizingIfSXSSF(Sheet sheet) { - SXSSFSheet sxSheet = (SXSSFSheet) sheet; - sxSheet.trackAllColumnsForAutoSizing(); - } - - - /** - * cloning of sheets is not supported in SXSSF - */ - @Override - @Test - protected void cloneSheet() { - RuntimeException ex = assertThrows(RuntimeException.class, () -> super.cloneSheet()); - assertEquals("Not Implemented", ex.getMessage()); - } - - @Override - @Test - protected void cloneSheetMultipleTimes() { - RuntimeException ex = assertThrows(RuntimeException.class, () -> super.cloneSheetMultipleTimes()); - assertEquals("Not Implemented", ex.getMessage()); - } - - /** - * shifting rows is not supported in SXSSF - */ - @Override - @Test - protected void shiftMerged() { - RuntimeException ex = assertThrows(RuntimeException.class, () -> super.shiftMerged()); - assertEquals("Not Implemented", ex.getMessage()); - } - - /** - * Bug 35084: cloning cells with formula - * - * The test is disabled because cloning of sheets is not supported in SXSSF - */ - @Override - @Test - protected void bug35084() { - RuntimeException ex = assertThrows(RuntimeException.class, () -> super.bug35084()); - assertEquals("Not Implemented", ex.getMessage()); - } - - @Override - protected void getCellComment() { - // TODO: reading cell comments via Sheet does not work currently as it tries - // to access the underlying sheet for this, but comments are stored as - // properties on Cells... - } - - @Disabled - @Override - protected void defaultColumnStyle() { - //TODO column styles are not yet supported by XSSF - } - - @Test - void overrideFlushedRows() throws IOException { - try (Workbook wb = new SXSSFWorkbook(3)) { - Sheet sheet = wb.createSheet(); - - sheet.createRow(1); - sheet.createRow(2); - sheet.createRow(3); - sheet.createRow(4); - - Throwable ex = assertThrows(Throwable.class, () -> sheet.createRow(1)); - assertEquals("Attempting to write a row[1] in the range [0,1] that is already written to disk.", ex.getMessage()); - } - } - - @Test - void overrideRowsInTemplate() throws IOException { - try (XSSFWorkbook template = new XSSFWorkbook()) { - template.createSheet().createRow(1); - try (Workbook wb = new SXSSFWorkbook(template);) { - Sheet sheet = wb.getSheetAt(0); - Throwable e; - e = assertThrows(Throwable.class, () -> sheet.createRow(1)); - assertEquals("Attempting to write a row[1] in the range [0,1] that is already written to disk.", e.getMessage()); - - e = assertThrows(Throwable.class, () -> sheet.createRow(0)); - assertEquals("Attempting to write a row[0] in the range [0,1] that is already written to disk.", e.getMessage()); - - sheet.createRow(2); - } - } - } - - @Test - void changeRowNum() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(3); - SXSSFSheet sheet = wb.createSheet(); - SXSSFRow row0 = sheet.createRow(0); - SXSSFRow row1 = sheet.createRow(1); - sheet.changeRowNum(row0, 2); - - assertEquals(1, row1.getRowNum(), "Row 1 knows its row number"); - assertEquals(2, row0.getRowNum(), "Row 2 knows its row number"); - assertEquals(1, sheet.getRowNum(row1), "Sheet knows Row 1's row number"); - assertEquals(2, sheet.getRowNum(row0), "Sheet knows Row 2's row number"); - assertEquals(row1, sheet.iterator().next(), "Sheet row iteratation order should be ascending"); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheetAutoSizeColumn.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheetAutoSizeColumn.java deleted file mode 100644 index cfb520e508..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheetAutoSizeColumn.java +++ /dev/null @@ -1,358 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.streaming; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.IOException; -import java.util.Collections; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.stream.Stream; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Font; -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.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetUtil; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - - -/** - * Tests the auto-sizing behaviour of {@link SXSSFSheet} when not all - * rows fit into the memory window size etc. - * - * see Bug #57450 which reported the original misbehaviour - */ -class TestSXSSFSheetAutoSizeColumn { - - private static final String SHORT_CELL_VALUE = "Ben"; - private static final String LONG_CELL_VALUE = "B Be Ben Beni Benif Benify Benif Beni Ben Be B"; - - // Approximate threshold to decide whether test is PASS or FAIL: - // shortCellValue ends up with approx column width 1_000 (on my machine), - // longCellValue ends up with approx. column width 10_000 (on my machine) - // so shortCellValue can be expected to be < 5000 for all fonts - // and longCellValue can be expected to be > 5000 for all fonts - private static final int COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG = 4000; - private static final int MAX_COLUMN_WIDTH = 255*256; - - private static final SortedSet<Integer> columns; - static { - SortedSet<Integer>_columns = new TreeSet<>(); - _columns.add(0); - _columns.add(1); - _columns.add(3); - columns = Collections.unmodifiableSortedSet(_columns); - } - - - private SXSSFSheet sheet; - private SXSSFWorkbook workbook; - - public static Stream<Arguments> data() { - return Stream.of(Arguments.of(false), Arguments.of(true)); - } - - @AfterEach - void tearDownSheetAndWorkbook() throws IOException { - if (sheet != null) { - sheet.dispose(); - } - if (workbook != null) { - workbook.close(); - } - } - - @ParameterizedTest - @MethodSource("data") - void test_EmptySheet_NoException(boolean useMergedCells) { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - for (int i = 0; i < 10; i++) { - int i2 = i; - assertDoesNotThrow(() -> sheet.autoSizeColumn(i2, useMergedCells)); - } - } - - @ParameterizedTest - @MethodSource("data") - void test_WindowSizeDefault_AllRowsFitIntoWindowSize(boolean useMergedCells) { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - final Cell cellRow0 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); - - assumeRequiredFontsAreInstalled(workbook, cellRow0); - - createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE); - - sheet.autoSizeColumn(0, useMergedCells); - - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); - } - - @ParameterizedTest - @MethodSource("data") - void test_WindowSizeEqualsOne_ConsiderFlushedRows(boolean useMergedCells) { - workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - final Cell cellRow0 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); - - assumeRequiredFontsAreInstalled(workbook, cellRow0); - - createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE); - - sheet.autoSizeColumn(0, useMergedCells); - - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); - } - - @ParameterizedTest - @MethodSource("data") - void test_WindowSizeEqualsOne_lastRowIsNotWidest(boolean useMergedCells) { - workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - final Cell cellRow0 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); - - assumeRequiredFontsAreInstalled(workbook, cellRow0); - - createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE); - - sheet.autoSizeColumn(0, useMergedCells); - - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); - } - - @ParameterizedTest - @MethodSource("data") - void test_WindowSizeEqualsOne_lastRowIsWidest(boolean useMergedCells) { - workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - final Cell cellRow0 = createRowWithCellValues(sheet, 0, SHORT_CELL_VALUE); - - assumeRequiredFontsAreInstalled(workbook, cellRow0); - - createRowWithCellValues(sheet, 1, LONG_CELL_VALUE); - - sheet.autoSizeColumn(0, useMergedCells); - - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); - } - - // fails only for useMergedCell=true - @ParameterizedTest - @MethodSource("data") - void test_WindowSizeEqualsOne_flushedRowHasMergedCell(boolean useMergedCells) { - workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - Cell a1 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); - - assumeRequiredFontsAreInstalled(workbook, a1); - assertEquals(0, sheet.addMergedRegion(CellRangeAddress.valueOf("A1:B1"))); - - createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE, SHORT_CELL_VALUE); - - /* - * A B - * 1 LONGMERGED - * 2 SHORT SHORT - */ - - sheet.autoSizeColumn(0, useMergedCells); - sheet.autoSizeColumn(1, useMergedCells); - - if (useMergedCells) { - // Excel and LibreOffice behavior: ignore merged cells for auto-sizing. - // POI behavior: evenly distribute the column width among the merged columns. - // each column must be auto-sized in order for the column widths - // to add up to the best fit width. - final int colspan = 2; - final int expectedWidth = (10000 + 1000)/colspan; //average of 1_000 and 10_000 - final int minExpectedWidth = expectedWidth / 2; - final int maxExpectedWidth = expectedWidth * 3 / 2; - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), minExpectedWidth, maxExpectedWidth); //short - } else { - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); //long - } - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(1), 0, COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG); //short - } - - @ParameterizedTest - @MethodSource("data") - void autoSizeColumn_trackColumnForAutoSizing(boolean useMergedCells) { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - sheet.trackColumnForAutoSizing(0); - - SortedSet<Integer> expected = new TreeSet<>(); - expected.add(0); - assertEquals(expected, sheet.getTrackedColumnsForAutoSizing()); - - sheet.autoSizeColumn(0, useMergedCells); - assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(1, useMergedCells), - "Should not be able to auto-size an untracked column"); - } - - @ParameterizedTest - @MethodSource("data") - void autoSizeColumn_trackColumnsForAutoSizing(boolean useMergedCells) { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackColumnsForAutoSizing(columns); - SortedSet<Integer> sorted = new TreeSet<>(columns); - assertEquals(sorted, sheet.getTrackedColumnsForAutoSizing()); - - sheet.autoSizeColumn(sorted.first(), useMergedCells); - assumeFalse(columns.contains(5)); - - assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(5, useMergedCells), - "Should not be able to auto-size an untracked column"); - } - - @ParameterizedTest - @MethodSource("data") - void autoSizeColumn_untrackColumnForAutoSizing(boolean useMergedCells) { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackColumnsForAutoSizing(columns); - sheet.untrackColumnForAutoSizing(columns.first()); - - assumeTrue(sheet.getTrackedColumnsForAutoSizing().contains(columns.last())); - sheet.autoSizeColumn(columns.last(), useMergedCells); - assumeFalse(sheet.getTrackedColumnsForAutoSizing().contains(columns.first())); - - assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(columns.first(), useMergedCells), - "Should not be able to auto-size an untracked column"); - } - - @ParameterizedTest - @MethodSource("data") - void autoSizeColumn_untrackColumnsForAutoSizing(boolean useMergedCells) { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackColumnForAutoSizing(15); - sheet.trackColumnsForAutoSizing(columns); - sheet.untrackColumnsForAutoSizing(columns); - - assumeTrue(sheet.getTrackedColumnsForAutoSizing().contains(15)); - sheet.autoSizeColumn(15, useMergedCells); - assumeFalse(sheet.getTrackedColumnsForAutoSizing().contains(columns.first())); - - assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(columns.first(), useMergedCells), - "Should not be able to auto-size an untracked column"); - } - - @Test - void autoSizeColumn_isColumnTrackedForAutoSizing() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackColumnsForAutoSizing(columns); - for (int column : columns) { - assertTrue(sheet.isColumnTrackedForAutoSizing(column)); - - assumeFalse(columns.contains(column+10)); - assertFalse(sheet.isColumnTrackedForAutoSizing(column+10)); - } - } - - @ParameterizedTest - @MethodSource("data") - void autoSizeColumn_trackAllColumns(boolean useMergedCells) { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackAllColumnsForAutoSizing(); - sheet.autoSizeColumn(0, useMergedCells); - - sheet.untrackAllColumnsForAutoSizing(); - assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(0, useMergedCells), - "Should not be able to auto-size an implicitly untracked column"); - } - - @ParameterizedTest - @MethodSource("data") - void autoSizeColumn_trackAllColumns_explicitUntrackColumn(boolean useMergedCells) { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackColumnsForAutoSizing(columns); - sheet.trackAllColumnsForAutoSizing(); - - boolean untracked = sheet.untrackColumnForAutoSizing(0); - assertTrue(untracked); - assertThrows(IllegalStateException.class, () -> sheet.autoSizeColumn(0, useMergedCells), - "Should not be able to auto-size an explicitly untracked column"); - } - - - private static void assumeRequiredFontsAreInstalled(final Workbook workbook, final Cell cell) { - // autoSize will fail if required fonts are not installed, skip this test then - Font font = workbook.getFontAt(cell.getCellStyle().getFontIndex()); - assumeTrue(SheetUtil.canComputeColumnWidth(font), - "Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font); - } - - private static Cell createRowWithCellValues(final Sheet sheet, final int rowNumber, final String... cellValues) { - Row row = sheet.createRow(rowNumber); - int cellIndex = 0; - Cell firstCell = null; - for (final String cellValue : cellValues) { - Cell cell = row.createCell(cellIndex++); - if (firstCell == null) { - firstCell = cell; - } - cell.setCellValue(cellValue); - } - return firstCell; - } - - private static void assertColumnWidthStrictlyWithinRange(final int actualColumnWidth, final int lowerBoundExclusive, final int upperBoundExclusive) { - assertTrue(actualColumnWidth > lowerBoundExclusive, - "Expected a column width greater than " + lowerBoundExclusive + " but found " + actualColumnWidth); - assertTrue(actualColumnWidth < upperBoundExclusive, - "Expected column width less than " + upperBoundExclusive + " but found " + actualColumnWidth); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFUnicodeSurrogates.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFUnicodeSurrogates.java deleted file mode 100644 index aba3a2f376..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFUnicodeSurrogates.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -class TestSXSSFUnicodeSurrogates { - - // "𝝊𝝋𝝌𝝍𝝎𝝏𝝐𝝑𝝒𝝓𝝔𝝕𝝖𝝗𝝘𝝙𝝚𝝛𝝜𝝝𝝞𝝟𝝠𝝡𝝢𝝣𝝤𝝥𝝦𝝧𝝨𝝩𝝪𝝫𝝬𝝭𝝮𝝯𝝰𝝱𝝲𝝳𝝴𝝵𝝶𝝷𝝸𝝹𝝺"; - private static final String unicodeText = - "\uD835\uDF4A\uD835\uDF4B\uD835\uDF4C\uD835\uDF4D\uD835\uDF4E\uD835\uDF4F\uD835\uDF50\uD835" + - "\uDF51\uD835\uDF52\uD835\uDF53\uD835\uDF54\uD835\uDF55\uD835\uDF56\uD835\uDF57\uD835\uDF58" + - "\uD835\uDF59\uD835\uDF5A\uD835\uDF5B\uD835\uDF5C\uD835\uDF5D\uD835\uDF5E\uD835\uDF5F\uD835" + - "\uDF60\uD835\uDF61\uD835\uDF62\uD835\uDF63\uD835\uDF64\uD835\uDF65\uD835\uDF66\uD835\uDF67" + - "\uD835\uDF68\uD835\uDF69\uD835\uDF6A\uD835\uDF6B\uD835\uDF6C\uD835\uDF6D\uD835\uDF6E\uD835" + - "\uDF6F\uD835\uDF70\uD835\uDF71\uD835\uDF72\uD835\uDF73\uD835\uDF74\uD835\uDF75\uD835\uDF76" + - "\uD835\uDF77\uD835\uDF78\uD835\uDF79\uD835\uDF7A"; - - @Test - void testWriteUnicodeSurrogates() throws IOException { - String sheetName = "Sheet1"; - File tf = TempFile.createTempFile("poi-xmlbeans-test", ".xlsx"); - try (SXSSFWorkbook wb = new SXSSFWorkbook()) { - Sheet sheet = wb.createSheet(sheetName); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(unicodeText); - try (FileOutputStream os = new FileOutputStream(tf)) { - wb.write(os); - } - try (FileInputStream fis = new FileInputStream(tf); - XSSFWorkbook wb2 = new XSSFWorkbook(fis)) { - Sheet sheet2 = wb2.getSheet(sheetName); - Cell cell2 = sheet2.getRow(0).getCell(0); - assertEquals(unicodeText, cell2.getStringCellValue()); - } - } finally { - tf.delete(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java deleted file mode 100644 index e065b26adb..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java +++ /dev/null @@ -1,537 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import static org.apache.poi.POITestCase.assertEndsWith; -import static org.apache.poi.POITestCase.assertStartsWith; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -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.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.ss.tests.usermodel.BaseTestXWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.NullOutputStream; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -public final class TestSXSSFWorkbook extends BaseTestXWorkbook { - - public TestSXSSFWorkbook() { - super(SXSSFITestDataProvider.instance); - } - - @AfterEach - void tearDown(){ - ((SXSSFITestDataProvider)_testDataProvider).cleanup(); - } - - /** - * cloning of sheets is not supported in SXSSF - */ - @Override - @Test - protected void cloneSheet() throws IOException { - RuntimeException e = assertThrows(RuntimeException.class, () -> super.cloneSheet()); - assertEquals("Not Implemented", e.getMessage()); - } - - /** - * cloning of sheets is not supported in SXSSF - */ - @Override - @Test - protected void sheetClone() { - RuntimeException e = assertThrows(RuntimeException.class, () -> super.sheetClone()); - assertEquals("Not Implemented", e.getMessage()); - } - - /** - * Skip this test, as SXSSF doesn't update formulas on sheet name - * changes. - */ - @Override - @Disabled("SXSSF doesn't update formulas on sheet name changes, as most cells probably aren't in memory at the time") - protected void setSheetName() { - } - - @Test - void existingWorkbook() throws IOException { - XSSFWorkbook xssfWb1 = new XSSFWorkbook(); - xssfWb1.createSheet("S1"); - SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1); - XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); - assertTrue(wb1.dispose()); - - SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2); - assertEquals(1, wb2.getNumberOfSheets()); - Sheet sheet = wb2.getSheetAt(0); - assertNotNull(sheet); - assertEquals("S1", sheet.getSheetName()); - assertTrue(wb2.dispose()); - xssfWb2.close(); - xssfWb1.close(); - - wb2.close(); - wb1.close(); - } - - @Test - void useSharedStringsTable() throws Exception { - SXSSFWorkbook wb = new SXSSFWorkbook(null, 10, false, true); - - SharedStringsTable sss = wb.getSharedStringSource(); - - assertNotNull(sss); - - Row row = wb.createSheet("S1").createRow(0); - - row.createCell(0).setCellValue("A"); - row.createCell(1).setCellValue("B"); - row.createCell(2).setCellValue("A"); - - XSSFWorkbook xssfWorkbook = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - sss = wb.getSharedStringSource(); - assertEquals(2, sss.getUniqueCount()); - assertTrue(wb.dispose()); - - Sheet sheet1 = xssfWorkbook.getSheetAt(0); - assertEquals("S1", sheet1.getSheetName()); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - row = sheet1.getRow(0); - assertNotNull(row); - Cell cell = row.getCell(0); - assertNotNull(cell); - assertEquals("A", cell.getStringCellValue()); - cell = row.getCell(1); - assertNotNull(cell); - assertEquals("B", cell.getStringCellValue()); - cell = row.getCell(2); - assertNotNull(cell); - assertEquals("A", cell.getStringCellValue()); - - xssfWorkbook.close(); - wb.close(); - } - - @Test - void addToExistingWorkbook() throws IOException { - XSSFWorkbook xssfWb1 = new XSSFWorkbook(); - xssfWb1.createSheet("S1"); - Sheet sheet = xssfWb1.createSheet("S2"); - Row row = sheet.createRow(1); - Cell cell = row.createCell(1); - cell.setCellValue("value 2_1_1"); - SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1); - XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); - assertTrue(wb1.dispose()); - xssfWb1.close(); - - SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2); - // Add a row to the existing empty sheet - Sheet sheet1 = wb2.getSheetAt(0); - Row row1_1 = sheet1.createRow(1); - Cell cell1_1_1 = row1_1.createCell(1); - cell1_1_1.setCellValue("value 1_1_1"); - - // Add a row to the existing non-empty sheet - Sheet sheet2 = wb2.getSheetAt(1); - Row row2_2 = sheet2.createRow(2); - Cell cell2_2_1 = row2_2.createCell(1); - cell2_2_1.setCellValue("value 2_2_1"); - - // Add a sheet with one row - Sheet sheet3 = wb2.createSheet("S3"); - Row row3_1 = sheet3.createRow(1); - Cell cell3_1_1 = row3_1.createCell(1); - cell3_1_1.setCellValue("value 3_1_1"); - - XSSFWorkbook xssfWb3 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb2); - wb2.close(); - - assertEquals(3, xssfWb3.getNumberOfSheets()); - // Verify sheet 1 - sheet1 = xssfWb3.getSheetAt(0); - assertEquals("S1", sheet1.getSheetName()); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - row1_1 = sheet1.getRow(1); - assertNotNull(row1_1); - cell1_1_1 = row1_1.getCell(1); - assertNotNull(cell1_1_1); - assertEquals("value 1_1_1", cell1_1_1.getStringCellValue()); - // Verify sheet 2 - sheet2 = xssfWb3.getSheetAt(1); - assertEquals("S2", sheet2.getSheetName()); - assertEquals(2, sheet2.getPhysicalNumberOfRows()); - Row row2_1 = sheet2.getRow(1); - assertNotNull(row2_1); - Cell cell2_1_1 = row2_1.getCell(1); - assertNotNull(cell2_1_1); - assertEquals("value 2_1_1", cell2_1_1.getStringCellValue()); - row2_2 = sheet2.getRow(2); - assertNotNull(row2_2); - cell2_2_1 = row2_2.getCell(1); - assertNotNull(cell2_2_1); - assertEquals("value 2_2_1", cell2_2_1.getStringCellValue()); - // Verify sheet 3 - sheet3 = xssfWb3.getSheetAt(2); - assertEquals("S3", sheet3.getSheetName()); - assertEquals(1, sheet3.getPhysicalNumberOfRows()); - row3_1 = sheet3.getRow(1); - assertNotNull(row3_1); - cell3_1_1 = row3_1.getCell(1); - assertNotNull(cell3_1_1); - assertEquals("value 3_1_1", cell3_1_1.getStringCellValue()); - - xssfWb2.close(); - xssfWb3.close(); - wb1.close(); - } - - @Test - void sheetdataWriter() throws IOException{ - SXSSFWorkbook wb = new SXSSFWorkbook(); - SXSSFSheet sh = wb.createSheet(); - SheetDataWriter wr = sh.getSheetDataWriter(); - assertSame(wr.getClass(), SheetDataWriter.class); - File tmp = wr.getTempFile(); - assertStartsWith(tmp.getName(), "poi-sxssf-sheet"); - assertEndsWith(tmp.getName(), ".xml"); - assertTrue(wb.dispose()); - wb.close(); - - wb = new SXSSFWorkbook(); - wb.setCompressTempFiles(true); - sh = wb.createSheet(); - wr = sh.getSheetDataWriter(); - assertSame(wr.getClass(), GZIPSheetDataWriter.class); - tmp = wr.getTempFile(); - assertStartsWith(tmp.getName(), "poi-sxssf-sheet-xml"); - assertEndsWith(tmp.getName(), ".gz"); - assertTrue(wb.dispose()); - wb.close(); - - //Test escaping of Unicode control characters - wb = new SXSSFWorkbook(); - wb.createSheet("S1").createRow(0).createCell(0).setCellValue("value\u0019"); - XSSFWorkbook xssfWorkbook = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - Cell cell = xssfWorkbook.getSheet("S1").getRow(0).getCell(0); - assertEquals("value?", cell.getStringCellValue()); - - assertTrue(wb.dispose()); - wb.close(); - xssfWorkbook.close(); - } - - @Test - void gzipSheetdataWriter() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(); - wb.setCompressTempFiles(true); - - final int rowNum = 1000; - final int sheetNum = 5; - populateData(wb, 1000, 5); - - XSSFWorkbook xwb = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - for(int i = 0; i < sheetNum; i++){ - Sheet sh = xwb.getSheetAt(i); - assertEquals("sheet" + i, sh.getSheetName()); - for(int j = 0; j < rowNum; j++){ - Row row = sh.getRow(j); - assertNotNull(row, "row[" + j + "]"); - Cell cell1 = row.getCell(0); - assertEquals(new CellReference(cell1).formatAsString(), cell1.getStringCellValue()); - - Cell cell2 = row.getCell(1); - assertEquals(i, (int)cell2.getNumericCellValue()); - - Cell cell3 = row.getCell(2); - assertEquals(j, (int)cell3.getNumericCellValue()); - } - } - - assertTrue(wb.dispose()); - xwb.close(); - wb.close(); - } - - private static void assertWorkbookDispose(SXSSFWorkbook wb) - { - populateData(wb, 1000, 5); - - for (Sheet sheet : wb) { - SXSSFSheet sxSheet = (SXSSFSheet) sheet; - assertTrue(sxSheet.getSheetDataWriter().getTempFile().exists()); - } - - assertTrue(wb.dispose()); - - for (Sheet sheet : wb) { - SXSSFSheet sxSheet = (SXSSFSheet) sheet; - assertFalse(sxSheet.getSheetDataWriter().getTempFile().exists()); - } - } - - private static void populateData(Workbook wb, final int rowNum, final int sheetNum) { - for(int i = 0; i < sheetNum; i++){ - Sheet sh = wb.createSheet("sheet" + i); - for(int j = 0; j < rowNum; j++){ - Row row = sh.createRow(j); - Cell cell1 = row.createCell(0); - cell1.setCellValue(new CellReference(cell1).formatAsString()); - - Cell cell2 = row.createCell(1); - cell2.setCellValue(i); - - Cell cell3 = row.createCell(2); - cell3.setCellValue(j); - } - } - } - - @Test - void workbookDispose() throws IOException { - SXSSFWorkbook wb1 = new SXSSFWorkbook(); - // the underlying writer is SheetDataWriter - assertWorkbookDispose(wb1); - wb1.close(); - - SXSSFWorkbook wb2 = new SXSSFWorkbook(); - wb2.setCompressTempFiles(true); - // the underlying writer is GZIPSheetDataWriter - assertWorkbookDispose(wb2); - wb2.close(); - } - - @Test - void bug53515() throws Exception { - try (Workbook wb1 = new SXSSFWorkbook(10)) { - populateWorkbook(wb1); - saveTwice(wb1); - try (Workbook wb2 = new XSSFWorkbook()) { - populateWorkbook(wb2); - saveTwice(wb2); - } - } - } - - @Disabled("Crashes the JVM because of documented JVM behavior with concurrent writing/reading of zip-files, " - + "see http://www.oracle.com/technetwork/java/javase/documentation/overview-156328.html") - void bug53515a() throws Exception { - File out = new File("Test.xlsx"); - assertTrue(!out.exists() || out.delete()); - for (int i = 0; i < 2; i++) { - final SXSSFWorkbook wb; - if (out.exists()) { - wb = new SXSSFWorkbook( - (XSSFWorkbook) WorkbookFactory.create(out)); - } else { - wb = new SXSSFWorkbook(10); - } - - try { - FileOutputStream outSteam = new FileOutputStream(out); - if (i == 0) { - populateWorkbook(wb); - } else { - System.gc(); - System.gc(); - System.gc(); - } - - wb.write(outSteam); - // assertTrue(wb.dispose()); - outSteam.close(); - } finally { - assertTrue(wb.dispose()); - } - wb.close(); - } - assertTrue(out.exists()); - assertTrue(out.delete()); - } - - private static void populateWorkbook(Workbook wb) { - Sheet sh = wb.createSheet(); - for (int rownum = 0; rownum < 100; rownum++) { - Row row = sh.createRow(rownum); - for (int cellnum = 0; cellnum < 10; cellnum++) { - Cell cell = row.createCell(cellnum); - String address = new CellReference(cell).formatAsString(); - cell.setCellValue(address); - } - } - } - - private static void saveTwice(Workbook wb) throws Exception { - for (int i = 0; i < 2; i++) { - try (NullOutputStream out = new NullOutputStream()) { - wb.write(out); - } catch (Exception e) { - throw new Exception("ERROR: failed on " + (i + 1) - + "th time calling " + wb.getClass().getName() - + ".write() with exception " + e.getMessage(), e); - } - } - } - - @Test - void closeDoesNotModifyWorkbook() throws IOException { - final String filename = "SampleSS.xlsx"; - final File file = POIDataSamples.getSpreadSheetInstance().getFile(filename); - - // Some tests commented out because close() modifies the file - // See bug 58779 - - // String - //wb = new SXSSFWorkbook(new XSSFWorkbook(file.getPath())); - //assertCloseDoesNotModifyFile(filename, wb); - - // File - //wb = new SXSSFWorkbook(new XSSFWorkbook(file)); - //assertCloseDoesNotModifyFile(filename, wb); - - // InputStream - - try (FileInputStream fis = new FileInputStream(file); - XSSFWorkbook xwb = new XSSFWorkbook(fis); - SXSSFWorkbook wb = new SXSSFWorkbook(xwb)) { - assertCloseDoesNotModifyFile(filename, wb); - } - - // OPCPackage - //wb = new SXSSFWorkbook(new XSSFWorkbook(OPCPackage.open(file))); - //assertCloseDoesNotModifyFile(filename, wb); - } - - /** - * Bug #59743 - * - * this is only triggered on other files apart of sheet[1,2,...].xml - * as those are either copied uncompressed or with the use of GZIPInputStream - * so we use shared strings - */ - @Test - void testZipBombNotTriggeredOnUselessContent() throws IOException { - try (SXSSFWorkbook swb = new SXSSFWorkbook(null, 1, true, true)) { - SXSSFSheet s = swb.createSheet(); - char[] useless = new char[32767]; - Arrays.fill(useless, ' '); - - for (int row = 0; row < 1; row++) { - Row r = s.createRow(row); - for (int col = 0; col < 10; col++) { - char[] prefix = Integer.toHexString(row * 1000 + col).toCharArray(); - Arrays.fill(useless, 0, 10, ' '); - System.arraycopy(prefix, 0, useless, 0, prefix.length); - String ul = new String(useless); - r.createCell(col, CellType.STRING).setCellValue(ul); - } - } - - assertDoesNotThrow(() -> swb.write(new NullOutputStream())); - swb.dispose(); - } - } - - /** - * To avoid accident changes to the template, you should be able - * to create a SXSSFWorkbook from a read-only XSSF one, then - * change + save that (only). See bug #60010 - * TODO Fix this to work! - */ - @Test - @Disabled - void createFromReadOnlyWorkbook() throws Exception { - String sheetName = "Test SXSSF"; - File input = XSSFTestDataSamples.getSampleFile("sample.xlsx"); - - try (OPCPackage pkg = OPCPackage.open(input, PackageAccess.READ)) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (XSSFWorkbook xssf = new XSSFWorkbook(pkg)) { - try (SXSSFWorkbook wb = new SXSSFWorkbook(xssf, 2)) { - Sheet s = wb.createSheet(sheetName); - for (int i = 0; i < 10; i++) { - Row r = s.createRow(i); - r.createCell(0).setCellValue(true); - r.createCell(1).setCellValue(2.4); - r.createCell(2).setCellValue("Test Row " + i); - } - assertEquals(10, s.getLastRowNum()); - - wb.write(bos); - wb.dispose(); - } - } - - try (XSSFWorkbook xssf = new XSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { - Sheet s = xssf.getSheet(sheetName); - assertEquals(10, s.getLastRowNum()); - assertTrue(s.getRow(0).getCell(0).getBooleanCellValue()); - assertEquals("Test Row 9", s.getRow(9).getCell(2).getStringCellValue()); - } - } - } - - - @Test - void test56557() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56557.xlsx"); - - // Using streaming XSSFWorkbook makes the output file invalid - wb = new SXSSFWorkbook(((XSSFWorkbook) wb)); - - // Should not throw POIXMLException: java.io.IOException: Unable to parse xml bean when reading back - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wbBack); - wbBack.close(); - - wb.close(); - } - - void changeSheetNameWithSharedFormulas() { - /* not implemented */ - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java deleted file mode 100644 index b1fa40fe69..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.util.ZipEntrySource; -import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource; -import org.apache.poi.poifs.crypt.temp.EncryptedTempData; -import org.apache.poi.poifs.crypt.temp.SXSSFWorkbookWithCustomZipEntrySource; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * This class tests that an SXSSFWorkbook can be written and read where all temporary disk I/O - * is encrypted, but the final saved workbook is not encrypted - */ -public final class TestSXSSFWorkbookWithCustomZipEntrySource { - - final String sheetName = "TestSheet1"; - final String cellValue = "customZipEntrySource"; - - // write an unencrypted workbook to disk, but any temporary files are encrypted - @Test - void customZipEntrySource() throws IOException { - SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource(); - SXSSFSheet sheet1 = workbook.createSheet(sheetName); - SXSSFRow row1 = sheet1.createRow(1); - SXSSFCell cell1 = row1.createCell(1); - cell1.setCellValue(cellValue); - ByteArrayOutputStream os = new ByteArrayOutputStream(8192); - workbook.write(os); - workbook.close(); - workbook.dispose(); - XSSFWorkbook xwb = new XSSFWorkbook(new ByteArrayInputStream(os.toByteArray())); - XSSFSheet xs1 = xwb.getSheetAt(0); - assertEquals(sheetName, xs1.getSheetName()); - XSSFRow xr1 = xs1.getRow(1); - XSSFCell xc1 = xr1.getCell(1); - assertEquals(cellValue, xc1.getStringCellValue()); - xwb.close(); - } - - // write an encrypted workbook to disk, and encrypt any temporary files as well - @Test - void customZipEntrySourceForWriteAndRead() throws IOException, InvalidFormatException { - SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource(); - SXSSFSheet sheet1 = workbook.createSheet(sheetName); - SXSSFRow row1 = sheet1.createRow(1); - SXSSFCell cell1 = row1.createCell(1); - cell1.setCellValue(cellValue); - EncryptedTempData tempData = new EncryptedTempData(); - try (OutputStream os = tempData.getOutputStream()) { - workbook.write(os); - } - workbook.close(); - workbook.dispose(); - try (InputStream is = tempData.getInputStream(); - ZipEntrySource zipEntrySource = AesZipFileZipEntrySource.createZipEntrySource(is)) { - tempData.dispose(); - try (OPCPackage opc = OPCPackage.open(zipEntrySource); - XSSFWorkbook xwb = new XSSFWorkbook(opc)) { - XSSFSheet xs1 = xwb.getSheetAt(0); - assertEquals(sheetName, xs1.getSheetName()); - XSSFRow xr1 = xs1.getRow(1); - XSSFCell xc1 = xr1.getCell(1); - assertEquals(cellValue, xc1.getStringCellValue()); - } - } - } - - @Test - void validateTempFilesAreEncrypted() throws IOException { - TempFileRecordingSXSSFWorkbookWithCustomZipEntrySource workbook = new TempFileRecordingSXSSFWorkbookWithCustomZipEntrySource(); - SXSSFSheet sheet1 = workbook.createSheet(sheetName); - SXSSFRow row1 = sheet1.createRow(1); - SXSSFCell cell1 = row1.createCell(1); - cell1.setCellValue(cellValue); - ByteArrayOutputStream os = new ByteArrayOutputStream(8192); - workbook.write(os); - workbook.close(); - List<File> tempFiles = workbook.getTempFiles(); - assertEquals(1, tempFiles.size()); - File tempFile = tempFiles.get(0); - assertTrue(tempFile.exists(), "tempFile exists?"); - try (InputStream stream = new FileInputStream(tempFile)) { - byte[] data = IOUtils.toByteArray(stream); - String text = new String(data, UTF_8); - assertFalse(text.contains(sheetName)); - assertFalse(text.contains(cellValue)); - } - workbook.dispose(); - assertFalse(tempFile.exists(), "tempFile deleted after dispose?"); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java deleted file mode 100644 index 864ec3bc0d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -import org.apache.poi.util.IOUtils; -import org.junit.jupiter.api.Test; - -public final class TestSheetDataWriter { - - final String unicodeSurrogates = "\uD835\uDF4A\uD835\uDF4B\uD835\uDF4C\uD835\uDF4D\uD835\uDF4E" - + "\uD835\uDF4F\uD835\uDF50\uD835\uDF51\uD835\uDF52\uD835\uDF53\uD835\uDF54\uD835" - + "\uDF55\uD835\uDF56\uD835\uDF57\uD835\uDF58\uD835\uDF59\uD835\uDF5A\uD835\uDF5B" - + "\uD835\uDF5C\uD835\uDF5D\uD835\uDF5E\uD835\uDF5F\uD835\uDF60\uD835\uDF61\uD835" - + "\uDF62\uD835\uDF63\uD835\uDF64\uD835\uDF65\uD835\uDF66\uD835\uDF67\uD835\uDF68" - + "\uD835\uDF69\uD835\uDF6A\uD835\uDF6B\uD835\uDF6C\uD835\uDF6D\uD835\uDF6E\uD835" - + "\uDF6F\uD835\uDF70\uD835\uDF71\uD835\uDF72\uD835\uDF73\uD835\uDF74\uD835\uDF75" - + "\uD835\uDF76\uD835\uDF77\uD835\uDF78\uD835\uDF79\uD835\uDF7A"; - - @Test - void testReplaceWithQuestionMark() { - for(int i = 0; i < unicodeSurrogates.length(); i++) { - assertFalse(SheetDataWriter.replaceWithQuestionMark(unicodeSurrogates.charAt(i))); - } - assertTrue(SheetDataWriter.replaceWithQuestionMark('\uFFFE')); - assertTrue(SheetDataWriter.replaceWithQuestionMark('\uFFFF')); - assertTrue(SheetDataWriter.replaceWithQuestionMark('\u0000')); - assertTrue(SheetDataWriter.replaceWithQuestionMark('\u000F')); - assertTrue(SheetDataWriter.replaceWithQuestionMark('\u001F')); - } - - @Test - void testWriteUnicodeSurrogates() throws IOException { - SheetDataWriter writer = new SheetDataWriter(); - try { - writer.outputEscapedString(unicodeSurrogates); - writer.close(); - File file = writer.getTempFile(); - try (FileInputStream is = new FileInputStream(file)) { - String text = new String(IOUtils.toByteArray(is), StandardCharsets.UTF_8); - assertEquals(unicodeSurrogates, text); - } - } finally { - IOUtils.closeQuietly(writer); - } - } - @Test - void testWriteNewLines() throws IOException { - SheetDataWriter writer = new SheetDataWriter(); - try { - writer.outputEscapedString("\r\n"); - writer.close(); - File file = writer.getTempFile(); - try (FileInputStream is = new FileInputStream(file)) { - String text = new String(IOUtils.toByteArray(is), StandardCharsets.UTF_8); - assertEquals("
", text); - } - } finally { - IOUtils.closeQuietly(writer); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java deleted file mode 100644 index dfc129a47f..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java +++ /dev/null @@ -1,324 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -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.assertThrows; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DataConsolidateFunction; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageField; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageFields; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotFields; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotTableDefinition; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataConsolidateFunction; - -public abstract class BaseTestXSSFPivotTable { - private static final XSSFITestDataProvider _testDataProvider = XSSFITestDataProvider.instance; - protected XSSFWorkbook wb; - protected XSSFPivotTable pivotTable; - protected XSSFPivotTable offsetPivotTable; - protected Cell offsetOuterCell; - - /** - * required to set up the test pivot tables and cell reference, either by name or reference. - */ - @BeforeEach - protected abstract void setUp(); - - @AfterEach - void tearDown() throws IOException { - if (wb != null) { - XSSFWorkbook wb2 = _testDataProvider.writeOutAndReadBack(wb); - wb.close(); - wb2.close(); - } - } - - /** - * Verify that when creating a row label it's created on the correct row - * and the count is increased by one. - */ - @Test - void testAddRowLabelToPivotTable() { - int columnIndex = 0; - - assertEquals(0, pivotTable.getRowLabelColumns().size()); - - pivotTable.addRowLabel(columnIndex); - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getRowFields().getFieldArray(0).getX(), columnIndex); - assertEquals(defintion.getRowFields().getCount(), 1); - assertEquals(1, pivotTable.getRowLabelColumns().size()); - - columnIndex = 1; - pivotTable.addRowLabel(columnIndex); - assertEquals(2, pivotTable.getRowLabelColumns().size()); - - assertEquals(0, (int)pivotTable.getRowLabelColumns().get(0)); - assertEquals(1, (int)pivotTable.getRowLabelColumns().get(1)); - } - - /** - * Verify that it's not possible to create a row label outside of the referenced area. - */ - @Test - void testAddRowLabelOutOfRangeThrowsException() { - assertThrows(IndexOutOfBoundsException.class, () -> pivotTable.addRowLabel(5)); - } - - /** - * Verify that when creating one column label, no col fields are being created. - */ - @Test - void testAddOneColumnLabelToPivotTableDoesNotCreateColField() { - int columnIndex = 0; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnIndex); - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertNull(defintion.getColFields()); - } - - /** - * Verify that it's possible to create three column labels with different DataConsolidateFunction - */ - @Test - void testAddThreeDifferentColumnLabelsToPivotTable() { - int columnOne = 0; - int columnTwo = 1; - int columnThree = 2; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnOne); - pivotTable.addColumnLabel(DataConsolidateFunction.MAX, columnTwo); - pivotTable.addColumnLabel(DataConsolidateFunction.MIN, columnThree); - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getDataFields().getDataFieldList().size(), 3); - } - - - /** - * Verify that it's possible to create three column labels with the same DataConsolidateFunction - */ - @Test - void testAddThreeSametColumnLabelsToPivotTable() { - int columnOne = 0; - int columnTwo = 1; - int columnThree = 2; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnOne); - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnTwo); - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnThree); - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getDataFields().getDataFieldList().size(), 3); - } - - /** - * Verify that when creating two column labels, a col field is being created and X is set to -2. - */ - @Test - void testAddTwoColumnLabelsToPivotTable() { - int columnOne = 0; - int columnTwo = 1; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnOne); - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnTwo); - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getColFields().getFieldArray(0).getX(), -2); - } - - /** - * Verify that a data field is created when creating a data column - */ - @Test - void testColumnLabelCreatesDataField() { - int columnIndex = 0; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnIndex); - - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getDataFields().getDataFieldArray(0).getFld(), columnIndex); - assertEquals(defintion.getDataFields().getDataFieldArray(0).getSubtotal(), - STDataConsolidateFunction.Enum.forInt(DataConsolidateFunction.SUM.getValue())); - } - - /** - * Verify that it's possible to set a custom name when creating a data column - */ - @Test - void testColumnLabelSetCustomName() { - int columnIndex = 0; - - String customName = "Custom Name"; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnIndex, customName); - - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getDataFields().getDataFieldArray(0).getFld(), columnIndex); - assertEquals(defintion.getDataFields().getDataFieldArray(0).getName(), customName); - } - - /** - * Verify that it's possible to set the format to the data column - */ - @Test - void testColumnLabelSetDataFormat() { - int columnIndex = 0; - - String format = "#,##0.0"; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnIndex, null, format); - - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getDataFields().getDataFieldArray(0).getFld(), columnIndex); - assertEquals(defintion.getDataFields().getDataFieldArray(0).getNumFmtId(), wb.createDataFormat().getFormat(format)); - } - - /** - * Verify that it's not possible to create a column label outside of the referenced area. - */ - @Test - void testAddColumnLabelOutOfRangeThrowsException() { - assertThrows(IndexOutOfBoundsException.class, () -> pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 5)); - } - - /** - * Verify when creating a data column set to a data field, the data field with the corresponding - * column index will be set to true. - */ - @Test - void testAddDataColumn() { - int columnIndex = 0; - boolean isDataField = true; - - pivotTable.addDataColumn(columnIndex, isDataField); - CTPivotFields pivotFields = pivotTable.getCTPivotTableDefinition().getPivotFields(); - assertEquals(pivotFields.getPivotFieldArray(columnIndex).getDataField(), isDataField); - } - - /** - * Verify that it's not possible to create a data column outside of the referenced area. - */ - @Test - void testAddDataColumnOutOfRangeThrowsException() { - assertThrows(IndexOutOfBoundsException.class, () -> pivotTable.addDataColumn(5, true)); - } - - /** - * Verify that it's possible to create a new filter - */ - @Test - void testAddReportFilter() { - int columnIndex = 0; - - pivotTable.addReportFilter(columnIndex); - CTPageFields fields = pivotTable.getCTPivotTableDefinition().getPageFields(); - CTPageField field = fields.getPageFieldArray(0); - assertEquals(field.getFld(), columnIndex); - assertEquals(field.getHier(), -1); - assertEquals(fields.getCount(), 1); - } - - /** - * Verify that it's not possible to create a new filter outside of the referenced area. - */ - @Test - void testAddReportFilterOutOfRangeThrowsException() { - assertThrows(IndexOutOfBoundsException.class, () -> pivotTable.addReportFilter(5)); - } - - /** - * Verify that the Pivot Table operates only within the referenced area, even when the - * first column of the referenced area is not index 0. - */ - @Test - void testAddDataColumnWithOffsetData() { - offsetPivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1); - assertEquals(CellType.NUMERIC, offsetOuterCell.getCellType()); - - offsetPivotTable.addColumnLabel(DataConsolidateFunction.SUM, 0); - } - - @Test - void testPivotTableSheetNamesAreCaseInsensitive() { - wb.setSheetName(0, "original"); - wb.setSheetName(1, "offset"); - XSSFSheet original = wb.getSheet("OriginaL"); - XSSFSheet offset = wb.getSheet("OffseT"); - // assume sheets are accessible via case-insensitive name - assertNotNull(original); - assertNotNull(offset); - - AreaReference source = wb.getCreationHelper().createAreaReference("ORIGinal!A1:C2"); - // create a pivot table on the same sheet, case insensitive - original.createPivotTable(source, new CellReference("W1")); - // create a pivot table on a different sheet, case insensitive - offset.createPivotTable(source, new CellReference("W1")); - } - - - /** - * Verify that when creating a col label it's created on the correct column - * and the count is increased by one. - */ - @Test - void testAddColLabelToPivotTable() { - int columnIndex = 0; - - assertEquals(0, pivotTable.getColLabelColumns().size()); - - pivotTable.addColLabel(columnIndex); - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getColFields().getFieldArray(0).getX(), columnIndex); - assertEquals(defintion.getColFields().getCount(), 1); - assertEquals(1, pivotTable.getColLabelColumns().size()); - - columnIndex = 1; - pivotTable.addColLabel(columnIndex); - assertEquals(2, pivotTable.getColLabelColumns().size()); - - assertEquals(0, (int)pivotTable.getColLabelColumns().get(0)); - assertEquals(1, (int)pivotTable.getColLabelColumns().get(1)); - } - - /** - * Verify that it's not possible to create a col label outside of the referenced area. - */ - @Test - void testAddColLabelOutOfRangeThrowsException() { - assertThrows(IndexOutOfBoundsException.class, () -> pivotTable.addColLabel(5)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java deleted file mode 100644 index 600ce5c31d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java +++ /dev/null @@ -1,266 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.logging.log4j.util.Unbox.box; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeFalse; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.stream.Stream; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.ss.formula.eval.TestFormulasFromSpreadsheet; -import org.apache.poi.ss.formula.functions.BaseTestNumeric; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.LocaleUtil; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Performs much the same role as {@link TestFormulasFromSpreadsheet}, - * except for a XSSF spreadsheet, not a HSSF one. - * This allows us to check that all our Formula Evaluation code - * is able to work for XSSF, as well as for HSSF. - * - * Periodically, you should open FormulaEvalTestData.xls in - * Excel 2007, and re-save it as FormulaEvalTestData_Copy.xlsx - * - */ -public final class TestFormulaEvaluatorOnXSSF { - private static final Logger LOG = LogManager.getLogger(TestFormulaEvaluatorOnXSSF.class); - - private static XSSFWorkbook workbook; - private static Sheet sheet; - private static FormulaEvaluator evaluator; - private static Locale userLocale; - - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - private interface SS { - - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - String FILENAME = "FormulaEvalTestData_Copy.xlsx"; - /** - * Row (zero-based) in the test spreadsheet where the operator examples start. - */ - int START_OPERATORS_ROW_INDEX = 22; // Row '23' - /** - * Row (zero-based) in the test spreadsheet where the function examples start. - */ - int START_FUNCTIONS_ROW_INDEX = 95; // Row '96' - /** - * Index of the column that contains the function names - */ - int COLUMN_INDEX_FUNCTION_NAME = 1; // Column 'B' - - /** - * Used to indicate when there are no more functions left - */ - String FUNCTION_NAMES_END_SENTINEL = "<END-OF-FUNCTIONS>"; - - /** - * Index of the column where the test values start (for each function) - */ - short COLUMN_INDEX_FIRST_TEST_VALUE = 3; // Column 'D' - - /** - * Each function takes 4 rows in the test spreadsheet - */ - int NUMBER_OF_ROWS_PER_FUNCTION = 4; - } - - @AfterAll - public static void closeResource() throws Exception { - LocaleUtil.setUserLocale(userLocale); - workbook.close(); - } - - public static Stream<Arguments> data() throws Exception { - // Function "Text" uses custom-formats which are locale specific - // can't set the locale on a per-testrun execution, as some settings have been - // already set, when we would try to change the locale by then - userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.ROOT); - - workbook = new XSSFWorkbook( OPCPackage.open(HSSFTestDataSamples.getSampleFile(SS.FILENAME), PackageAccess.READ) ); - sheet = workbook.getSheetAt( 0 ); - evaluator = new XSSFFormulaEvaluator(workbook); - - List<Arguments> data = new ArrayList<>(); - - processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, null); - processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, null); - // example for debugging individual functions/operators: - // processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, "ConcatEval"); - // processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, "Text"); - - return data.stream(); - } - - /** - * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * @param testFocusFunctionName name of a single function/operator to test alone. - * Typically pass <code>null</code> to test all functions - */ - private static void processFunctionGroup(List<Arguments> data, int startRowIndex, String testFocusFunctionName) { - for (int rowIndex = startRowIndex; true; rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION) { - Row r = sheet.getRow(rowIndex); - - // only evaluate non empty row - if(r == null) continue; - - String targetFunctionName = getTargetFunctionName(r); - assertNotNull(targetFunctionName, "Test spreadsheet cell empty on row (" - + (rowIndex+1) + "). Expected function name or '" - + SS.FUNCTION_NAMES_END_SENTINEL + "'"); - - if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { - // found end of functions list - break; - } - if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - - // expected results are on the row below - Row expectedValuesRow = sheet.getRow(rowIndex + 1); - // +1 for 1-based, +1 for next row - assertNotNull(expectedValuesRow, "Missing expected values row for function '" - + targetFunctionName + " (row " + rowIndex + 2 + ")"); - - data.add(Arguments.of(targetFunctionName, rowIndex, rowIndex + 1)); - } - } - } - - - @ParameterizedTest - @MethodSource("data") - void processFunctionRow(String targetFunctionName, int formulasRowIdx, int expectedValuesRowIdx) { - Row formulasRow = sheet.getRow(formulasRowIdx); - Row expectedValuesRow = sheet.getRow(expectedValuesRowIdx); - - short endcolnum = formulasRow.getLastCellNum(); - - // iterate across the row for all the evaluation cases - for (short colnum=SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++) { - Cell c = formulasRow.getCell(colnum); - assumeTrue(c != null); - assumeTrue(c.getCellType() == CellType.FORMULA); - ignoredFormulaTestCase(c.getCellFormula()); - - CellValue actValue = evaluator.evaluate(c); - Cell expValue = (expectedValuesRow == null) ? null : expectedValuesRow.getCell(colnum); - - String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" - , targetFunctionName, c.getCellFormula(), formulasRow.getRowNum(), colnum); - - assertNotNull(expValue, msg + " - Bad setup data expected value is null"); - assertNotNull(actValue, msg + " - actual value was null"); - - final CellType expectedCellType = expValue.getCellType(); - switch (expectedCellType) { - case BLANK: - assertEquals(CellType.BLANK, actValue.getCellType(), msg); - break; - case BOOLEAN: - assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); - assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); - break; - case ERROR: - assertEquals(CellType.ERROR, actValue.getCellType(), msg); -// if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values -// assertEquals(msg, expValue.getErrorCellValue(), actValue.getErrorValue()); -// } - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - fail("Cannot expect formula as result of formula evaluation: " + msg); - case NUMERIC: - assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); - BaseTestNumeric.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); -// double delta = Math.abs(expValue.getNumericCellValue()-actValue.getNumberValue()); -// double pctExpValue = Math.abs(0.00001*expValue.getNumericCellValue()); -// assertTrue(msg, delta <= pctExpValue); - break; - case STRING: - assertEquals(CellType.STRING, actValue.getCellType(), msg); - assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); - break; - default: - fail("Unexpected cell type: " + expectedCellType); - } - } - } - - /* - * TODO - these are all formulas which currently (Apr-2008) break on ooxml - */ - private static void ignoredFormulaTestCase(String cellFormula) { - // full row ranges are not parsed properly yet. - // These cases currently work in svn trunk because of another bug which causes the - // formula to get rendered as COLUMN($A$1:$IV$2) or ROW($A$2:$IV$3) - assumeFalse("COLUMN(1:2)".equals(cellFormula)); - assumeFalse("ROW(2:3)".equals(cellFormula)); - - // currently throws NPE because unknown function "currentcell" causes name lookup - // Name lookup requires some equivalent object of the Workbook within xSSFWorkbook. - assumeFalse("ISREF(currentcell())".equals(cellFormula)); - } - - /** - * @return <code>null</code> if cell is missing, empty or blank - */ - private static String getTargetFunctionName(Row r) { - if(r == null) { - LOG.atWarn().log("Given null row, can't figure out function name"); - return null; - } - Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME); - if(cell == null) { - LOG.atWarn().log("Row {} has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name", box(r.getRowNum())); - return null; - } - if(cell.getCellType() == CellType.BLANK) { - return null; - } - if(cell.getCellType() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - - fail("Bad cell type for 'function name' column: ("+cell.getColumnIndex()+") row ("+(r.getRowNum()+1)+")"); - return null; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMatrixFormulasFromXMLSpreadsheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMatrixFormulasFromXMLSpreadsheet.java deleted file mode 100644 index b7f32acd67..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMatrixFormulasFromXMLSpreadsheet.java +++ /dev/null @@ -1,228 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.logging.log4j.util.Unbox.box; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.stream.Stream; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.functions.BaseTestNumeric; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -public final class TestMatrixFormulasFromXMLSpreadsheet { - - private static final Logger LOG = LogManager.getLogger(TestMatrixFormulasFromXMLSpreadsheet.class); - - private static XSSFWorkbook workbook; - private static Sheet sheet; - private static FormulaEvaluator evaluator; - private static Locale userLocale; - - /* - * Unlike TestFormulaFromSpreadsheet which this class is modified from, there is no - * differentiation between operators and functions, if more functionality is implemented with - * array formulas then it might be worth it to separate operators from functions - * - * Also, output matrices are statically 3x3, if larger matrices wanted to be tested - * then adding matrix size parameter would be useful and parsing would be based off that. - */ - - private interface Navigator { - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - String FILENAME = "MatrixFormulaEvalTestData.xlsx"; - /** - * Row (zero-based) in the spreadsheet where operations start - */ - int START_OPERATORS_ROW_INDEX = 1; - /** - * Column (zero-based) in the spreadsheet where operations start - */ - int START_OPERATORS_COL_INDEX = 0; - /** - * Column (zero-based) in the spreadsheet where evaluations start - */ - int START_RESULT_COL_INDEX = 7; - /** - * Column separation in the spreadsheet between evaluations and expected results - */ - int COL_OFF_EXPECTED_RESULT = 3; - /** - * Row separation in the spreadsheet between operations - */ - int ROW_OFF_NEXT_OP = 4; - /** - * Used to indicate when there are no more operations left - */ - String END_OF_TESTS = "<END>"; - - } - - - @AfterAll - public static void closeResource() throws Exception { - LocaleUtil.setUserLocale(userLocale); - workbook.close(); - } - - /* generating parameter instances */ - public static Stream<Arguments> data() throws Exception { - // Function "Text" uses custom-formats which are locale specific - // can't set the locale on a per-testrun execution, as some settings have been - // already set, when we would try to change the locale by then - userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.ROOT); - - workbook = XSSFTestDataSamples.openSampleWorkbook(Navigator.FILENAME); - sheet = workbook.getSheetAt(0); - evaluator = new XSSFFormulaEvaluator(workbook); - - List<Arguments> data = new ArrayList<>(); - - processFunctionGroup(data, Navigator.START_OPERATORS_ROW_INDEX, null); - - return data.stream(); - } - - /** - * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * @param testFocusFunctionName name of a single function/operator to test alone. - * Typically pass <code>null</code> to test all functions - */ - private static void processFunctionGroup(List<Arguments> data, int startRowIndex, String testFocusFunctionName) { - for (int rowIndex = startRowIndex; true; rowIndex += Navigator.ROW_OFF_NEXT_OP) { - Row r = sheet.getRow(rowIndex); - String targetFunctionName = getTargetFunctionName(r); - assertNotNull(targetFunctionName, - "Test spreadsheet cell empty on row (" - + (rowIndex) + "). Expected function name or '" - + Navigator.END_OF_TESTS + "'"); - if(targetFunctionName.equals(Navigator.END_OF_TESTS)) { - // found end of functions list - break; - } - if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - data.add(Arguments.of(targetFunctionName, rowIndex)); - } - } - } - - @ParameterizedTest - @MethodSource("data") - void processFunctionRow(String targetFunctionName, int formulasRowIdx) { - - int endColNum = Navigator.START_RESULT_COL_INDEX + Navigator.COL_OFF_EXPECTED_RESULT; - - for (int rowNum = formulasRowIdx; rowNum < formulasRowIdx + Navigator.ROW_OFF_NEXT_OP - 1; rowNum++) { - for (int colNum = Navigator.START_RESULT_COL_INDEX; colNum < endColNum; colNum++) { - Row r = sheet.getRow(rowNum); - - /* mainly to escape row failures on MDETERM which only returns a scalar */ - if (r == null) { - continue; - } - - Cell c = sheet.getRow(rowNum).getCell(colNum); - - if (c == null || c.getCellType() != CellType.FORMULA) { - continue; - } - - CellValue actValue = evaluator.evaluate(c); - Cell expValue = sheet.getRow(rowNum).getCell(colNum + Navigator.COL_OFF_EXPECTED_RESULT); - - String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" - , targetFunctionName, c.getCellFormula(), rowNum, colNum); - - assertNotNull(expValue, msg + " - Bad setup data expected value is null"); - assertNotNull(actValue, msg + " - actual value was null"); - - final CellType cellType = expValue.getCellType(); - switch (cellType) { - case BLANK: - assertEquals(CellType.BLANK, actValue.getCellType(), msg); - break; - case BOOLEAN: - assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); - assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); - break; - case ERROR: - assertEquals(CellType.ERROR, actValue.getCellType(), msg); - assertEquals(ErrorEval.getText(expValue.getErrorCellValue()), ErrorEval.getText(actValue.getErrorValue()), msg); - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - fail("Cannot expect formula as result of formula evaluation: " + msg); - case NUMERIC: - assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); - BaseTestNumeric.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); - break; - case STRING: - assertEquals(CellType.STRING, actValue.getCellType(), msg); - assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); - break; - default: - fail("Unexpected cell type: " + cellType); - } - } - } - } - - /** - * @return <code>null</code> if cell is missing, empty or blank - */ - private static String getTargetFunctionName(Row r) { - if(r == null) { - LOG.atWarn().log("Given null row, can't figure out function name"); - return null; - } - Cell cell = r.getCell(Navigator.START_OPERATORS_COL_INDEX); - LOG.atDebug().log( box(Navigator.START_OPERATORS_COL_INDEX)); - if(cell == null) { - LOG.atWarn().log("Row {} has no cell " + Navigator.START_OPERATORS_COL_INDEX + ", can't figure out function name", box(r.getRowNum())); - return null; - } - - CellType ct = cell.getCellType(); - assertTrue(ct == CellType.BLANK || ct == CellType.STRING, - "Bad cell type for 'function name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - - return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java deleted file mode 100644 index bac2e49688..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java +++ /dev/null @@ -1,44 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.formula.BaseTestMissingWorkbook; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.BeforeEach; - -/** - * XSSF Specific version of the Missing Workbooks test - */ -public final class TestMissingWorkbookOnXSSF extends BaseTestMissingWorkbook { - public TestMissingWorkbookOnXSSF() { - super("52575_main.xlsx", "source_dummy.xlsx", "52575_source.xls"); - } - - @Override - @BeforeEach - protected void setUp() { - mainWorkbook = XSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME); - sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME); - - assertNotNull(mainWorkbook); - assertNotNull(sourceWorkbook); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java deleted file mode 100644 index 4c458ea42b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java +++ /dev/null @@ -1,252 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.logging.log4j.util.Unbox.box; -import static org.apache.poi.xssf.usermodel.TestMultiSheetFormulaEvaluatorOnXSSF.SS.COLUMN_INDEX_FUNCTION_NAME; -import static org.apache.poi.xssf.usermodel.TestMultiSheetFormulaEvaluatorOnXSSF.SS.COLUMN_INDEX_TEST_NAME; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.stream.Stream; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.ss.formula.functions.BaseTestNumeric; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Tests formulas for multi sheet reference (i.e. SUM(Sheet1:Sheet5!A1)) - */ -public final class TestMultiSheetFormulaEvaluatorOnXSSF { - private static final Logger LOG = LogManager.getLogger(TestMultiSheetFormulaEvaluatorOnXSSF.class); - - private static XSSFWorkbook workbook; - private static Sheet sheet; - private static FormulaEvaluator evaluator; - - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - interface SS { - - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - String FILENAME = "FormulaSheetRange.xlsx"; - /** - * Row (zero-based) in the test spreadsheet where the function examples start. - */ - int START_FUNCTIONS_ROW_INDEX = 10; // Row '11' - /** - * Index of the column that contains the function names - */ - int COLUMN_INDEX_FUNCTION_NAME = 0; // Column 'A' - /** - * Index of the column that contains the test names - */ - int COLUMN_INDEX_TEST_NAME = 1; // Column 'B' - /** - * Used to indicate when there are no more functions left - */ - String FUNCTION_NAMES_END_SENTINEL = "<END>"; - - /** - * Index of the column where the test expected value is present - */ - short COLUMN_INDEX_EXPECTED_VALUE = 2; // Column 'C' - /** - * Index of the column where the test actual value is present - */ - short COLUMN_INDEX_ACTUAL_VALUE = 3; // Column 'D' - /** - * Test sheet name (sheet with all test formulae) - */ - String TEST_SHEET_NAME = "test"; - } - - - @AfterAll - public static void closeResource() throws Exception { - workbook.close(); - } - - public static Stream<Arguments> data() throws Exception { - workbook = new XSSFWorkbook( OPCPackage.open(HSSFTestDataSamples.getSampleFile(SS.FILENAME), PackageAccess.READ) ); - sheet = workbook.getSheet( SS.TEST_SHEET_NAME ); - evaluator = new XSSFFormulaEvaluator(workbook); - - List<Arguments> data = new ArrayList<>(); - - processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, null); - - return data.stream(); - } - - /** - * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * @param testFocusFunctionName name of a single function/operator to test alone. - * Typically pass <code>null</code> to test all functions - */ - private static void processFunctionGroup(List<Arguments> data, int startRowIndex, String testFocusFunctionName) { - for (int rowIndex = startRowIndex; true; rowIndex++) { - Row r = sheet.getRow(rowIndex); - - // only evaluate non empty row - if(r == null) continue; - - String targetFunctionName = getTargetFunctionName(r); - assertNotNull(targetFunctionName, - "Test spreadsheet cell empty on row (" - + (rowIndex+1) + "). Expected function name or '" - + SS.FUNCTION_NAMES_END_SENTINEL + "'"); - - if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { - // found end of functions list - break; - } - - String targetTestName = getTargetTestName(r); - if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - - // expected results are on the row below - Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); - assertNotNull(expectedValueCell, - "Missing expected values cell for function '" - + targetFunctionName + ", test" + targetTestName + " (row " + - rowIndex + 1 + ")"); - - data.add(Arguments.of(targetTestName, targetFunctionName, rowIndex)); - } - } - } - - @ParameterizedTest - @MethodSource("data") - void processFunctionRow(String targetTestName, String targetFunctionName, int formulasRowIdx) { - Row r = sheet.getRow(formulasRowIdx); - - Cell expValue = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); - assertNotNull(expValue, - "Missing expected values cell for function '" - + targetFunctionName + ", test" + targetTestName + " (row " + - formulasRowIdx + 1 + ")"); - - Cell c = r.getCell(SS.COLUMN_INDEX_ACTUAL_VALUE); - assumeTrue(c != null); - assumeTrue(c.getCellType() == CellType.FORMULA); - - CellValue actValue = evaluator.evaluate(c); - - String msg = String.format(Locale.ROOT, "Function '%s': Test: '%s': Formula: %s @ %d:%d", - targetFunctionName, targetTestName, c.getCellFormula(), formulasRowIdx, SS.COLUMN_INDEX_ACTUAL_VALUE); - - assertNotNull(actValue, msg + " - actual value was null"); - - final CellType expectedCellType = expValue.getCellType(); - switch (expectedCellType) { - case BLANK: - assertEquals(CellType.BLANK, actValue.getCellType(), msg); - break; - case BOOLEAN: - assertEquals(CellType.BOOLEAN, actValue.getCellType(), msg); - assertEquals(expValue.getBooleanCellValue(), actValue.getBooleanValue(), msg); - break; - case ERROR: - assertEquals(CellType.ERROR, actValue.getCellType(), msg); -// if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values -// assertEquals(msg, expected.getErrorCellValue(), actual.getErrorValue()); -// } - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - fail("Cannot expect formula as result of formula evaluation: " + msg); - case NUMERIC: - assertEquals(CellType.NUMERIC, actValue.getCellType(), msg); - BaseTestNumeric.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), BaseTestNumeric.POS_ZERO, BaseTestNumeric.DIFF_TOLERANCE_FACTOR); -// double delta = Math.abs(expected.getNumericCellValue()-actual.getNumberValue()); -// double pctExpected = Math.abs(0.00001*expected.getNumericCellValue()); -// assertTrue(msg, delta <= pctExpected); - break; - case STRING: - assertEquals(CellType.STRING, actValue.getCellType(), msg); - assertEquals(expValue.getRichStringCellValue().getString(), actValue.getStringValue(), msg); - break; - default: - fail("Unexpected cell type: " + expectedCellType); - } - } - - /** - * @return <code>null</code> if cell is missing, empty or blank - */ - private static String getTargetFunctionName(Row r) { - if(r == null) { - LOG.atWarn().log("Given null row, can't figure out function name"); - return null; - } - Cell cell = r.getCell(COLUMN_INDEX_FUNCTION_NAME); - if(cell == null) { - LOG.atWarn().log("Row {} has no cell " + COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name", box(r.getRowNum())); - return null; - } - - CellType ct = cell.getCellType(); - assertTrue(ct == CellType.BLANK || ct == CellType.STRING, - "Bad cell type for 'function name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - - return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null; - } - - /** - * @return <code>null</code> if cell is missing, empty or blank - */ - private static String getTargetTestName(Row r) { - if(r == null) { - LOG.atWarn().log("Given null row, can't figure out test name"); - return null; - } - Cell cell = r.getCell(COLUMN_INDEX_TEST_NAME); - if(cell == null) { - LOG.atWarn().log("Row {} has no cell " + COLUMN_INDEX_TEST_NAME + ", can't figure out test name", box(r.getRowNum())); - return null; - } - CellType ct = cell.getCellType(); - assertTrue(ct == CellType.BLANK || ct == CellType.STRING, - "Bad cell type for 'test name' column: (" + cell.getCellType() + ") row (" + (r.getRowNum() +1) + ")"); - - return (ct == CellType.STRING) ? cell.getRichStringCellValue().getString() : null; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFBugs.java deleted file mode 100644 index aeea648a29..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFBugs.java +++ /dev/null @@ -1,248 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.FileOutputStream; -import java.io.IOException; -import java.util.Date; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.PrintSetup; -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.util.CellRangeAddress; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.streaming.SXSSFCell; -import org.apache.poi.xssf.streaming.SXSSFRow; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType; - -public final class TestSXSSFBugs extends BaseTestBugzillaIssues { - public TestSXSSFBugs() { - super(SXSSFITestDataProvider.instance); - } - - // override some tests which do not work for SXSSF - @Override @Disabled("cloneSheet() not implemented") - protected void bug18800() { /* cloneSheet() not implemented */ } - @Override @Disabled("cloneSheet() not implemented") - protected void bug22720() { /* cloneSheet() not implemented */ } - @Override @Disabled("Evaluation is not fully supported") - protected void bug47815() { /* Evaluation is not supported */ } - @Override @Disabled("Evaluation is not fully supported") - protected void bug46729_testMaxFunctionArguments() { /* Evaluation is not supported */ } - @Override @Disabled("Reading data is not supported") - protected void bug57798() { /* Reading data is not supported */ } - - /** - * Setting repeating rows and columns shouldn't break - * any print settings that were there before - */ - @Test - void bug49253() throws Exception { - Workbook wb1 = new SXSSFWorkbook(); - Workbook wb2 = new SXSSFWorkbook(); - CellRangeAddress cra = CellRangeAddress.valueOf("C2:D3"); - - // No print settings before repeating - Sheet s1 = wb1.createSheet(); - s1.setRepeatingColumns(cra); - s1.setRepeatingRows(cra); - - PrintSetup ps1 = s1.getPrintSetup(); - assertFalse(ps1.getValidSettings()); - assertFalse(ps1.getLandscape()); - - - // Had valid print settings before repeating - Sheet s2 = wb2.createSheet(); - PrintSetup ps2 = s2.getPrintSetup(); - - ps2.setLandscape(false); - assertTrue(ps2.getValidSettings()); - assertFalse(ps2.getLandscape()); - s2.setRepeatingColumns(cra); - s2.setRepeatingRows(cra); - - ps2 = s2.getPrintSetup(); - assertTrue(ps2.getValidSettings()); - assertFalse(ps2.getLandscape()); - - wb1.close(); - wb2.close(); - } - - @Test - void bug61648() throws Exception { - // works as expected - writeWorkbook(new XSSFWorkbook(), XSSFITestDataProvider.instance); - - // does not work - try (SXSSFWorkbook wb = new SXSSFWorkbook()) { - assertThrows(RuntimeException.class, () -> writeWorkbook(wb, SXSSFITestDataProvider.instance), - "this is not implemented yet"); - } - } - - void writeWorkbook(Workbook wb, ITestDataProvider testDataProvider) throws IOException { - Sheet sheet = wb.createSheet("array formula test"); - - int rowIndex = 0; - int colIndex = 0; - Row row = sheet.createRow(rowIndex++); - - Cell cell = row.createCell(colIndex++); - cell.setCellValue("multiple"); - cell = row.createCell(colIndex); - cell.setCellValue("unique"); - - writeRow(sheet, rowIndex++, 80d, "INDEX(A2:A7, MATCH(FALSE, ISBLANK(A2:A7), 0))"); - writeRow(sheet, rowIndex++, 30d, "IFERROR(INDEX(A2:A7, MATCH(1, (COUNTIF(B2:B2, A2:A7) = 0) * (NOT(ISBLANK(A2:A7))), 0)), \"\")"); - writeRow(sheet, rowIndex++, 30d, "IFERROR(INDEX(A2:A7, MATCH(1, (COUNTIF(B2:B3, A2:A7) = 0) * (NOT(ISBLANK(A2:A7))), 0)), \"\")"); - writeRow(sheet, rowIndex++, 2d, "IFERROR(INDEX(A2:A7, MATCH(1, (COUNTIF(B2:B4, A2:A7) = 0) * (NOT(ISBLANK(A2:A7))), 0)), \"\")"); - writeRow(sheet, rowIndex++, 30d, "IFERROR(INDEX(A2:A7, MATCH(1, (COUNTIF(B2:B5, A2:A7) = 0) * (NOT(ISBLANK(A2:A7))), 0)), \"\")"); - writeRow(sheet, rowIndex, 2d, "IFERROR(INDEX(A2:A7, MATCH(1, (COUNTIF(B2:B6, A2:A7) = 0) * (NOT(ISBLANK(A2:A7))), 0)), \"\")"); - - /*FileOutputStream fileOut = new FileOutputStream(filename); - wb.write(fileOut); - fileOut.close();*/ - - Workbook wbBack = testDataProvider.writeOutAndReadBack(wb); - assertNotNull(wbBack); - wbBack.close(); - - wb.close(); - } - - void writeRow(Sheet sheet, int rowIndex, Double col0Value, String col1Value) { - int colIndex = 0; - Row row = sheet.createRow(rowIndex); - - // numeric value cell - Cell cell = row.createCell(colIndex++); - cell.setCellValue(col0Value); - - // formula value cell - CellRangeAddress range = new CellRangeAddress(rowIndex, rowIndex, colIndex, colIndex); - sheet.setArrayFormula(col1Value, range); - } - - @Disabled("takes too long for the normal test run") - void test62872() throws Exception { - final int COLUMN_COUNT = 300; - final int ROW_COUNT = 600000; - final int TEN_MINUTES = 1000*60*10; - - SXSSFWorkbook workbook = new SXSSFWorkbook(100); - workbook.setCompressTempFiles(true); - SXSSFSheet sheet = workbook.createSheet("RawData"); - - SXSSFRow row = sheet.createRow(0); - SXSSFCell cell; - - for (int i = 1; i <= COLUMN_COUNT; i++) { - cell = row.createCell(i - 1); - cell.setCellValue("Column " + i); - } - - for (int i = 1; i < ROW_COUNT; i++) { - row = sheet.createRow(i); - for (int j = 1; j <= COLUMN_COUNT; j++) { - cell = row.createCell(j - 1); - - //make some noise - cell.setCellValue(new Date(i*TEN_MINUTES+(j*TEN_MINUTES)/COLUMN_COUNT)); - } - i++; - } - - try (FileOutputStream out = new FileOutputStream(File.createTempFile("test62872", ".xlsx"))) { - workbook.write(out); - workbook.dispose(); - workbook.close(); - out.flush(); - } - } - - @Test - void test63960() throws Exception { - try (Workbook workbook = new SXSSFWorkbook(100)) { - Sheet sheet = workbook.createSheet("RawData"); - - Row row = sheet.createRow(0); - Cell cell; - - cell = row.createCell(0); - cell.setCellValue(123); - cell = row.createCell(1); - cell.setCellValue(""); - cell.setCellFormula("=TEXT(A1,\"#\")"); - - /*try (FileOutputStream out = new FileOutputStream(File.createTempFile("test63960", ".xlsx"))) { - workbook.write(out); - }*/ - - try (Workbook wbBack = SXSSFITestDataProvider.instance.writeOutAndReadBack(workbook)) { - assertNotNull(wbBack); - Cell rawData = wbBack.getSheet("RawData").getRow(0).getCell(1); - - assertEquals(STCellType.STR, ((XSSFCell) rawData).getCTCell().getT()); - } - } - } - - @Test - void test64595() throws Exception { - try (Workbook workbook = new SXSSFWorkbook(100)) { - Sheet sheet = workbook.createSheet("RawData"); - Row row = sheet.createRow(0); - Cell cell; - - cell = row.createCell(0); - cell.setCellValue("Ernie & Bert"); - - cell = row.createCell(1); - // Set a precalculated formula value containing a special character. - cell.setCellValue("Ernie & Bert are cool!"); - cell.setCellFormula("A1 & \" are cool!\""); - - // While unfixed reading the workbook would throw a POIXMLException - // since the file was corrupt due to missing quotation. - try (Workbook wbBack = SXSSFITestDataProvider.instance.writeOutAndReadBack(workbook)) { - assertNotNull(wbBack); - cell = wbBack.getSheetAt(0).getRow(0).getCell(1); - assertEquals("Ernie & Bert are cool!", cell.getStringCellValue()); - assertEquals("A1 & \" are cool!\"", cell.getCellFormula()); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFSheetAutosizeColumn.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFSheetAutosizeColumn.java deleted file mode 100644 index 38ff1fc352..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFSheetAutosizeColumn.java +++ /dev/null @@ -1,39 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.BaseTestSheetAutosizeColumn; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.streaming.SXSSFSheet; - -/** - * @author Yegor Kozlov - */ -public final class TestSXSSFSheetAutosizeColumn extends BaseTestSheetAutosizeColumn { - - public TestSXSSFSheetAutosizeColumn(){ - super(SXSSFITestDataProvider.instance); - } - - @Override - protected void trackColumnsForAutoSizingIfSXSSF(Sheet sheet) { - ((SXSSFSheet)sheet).trackAllColumnsForAutoSizing(); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSheetHiding.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSheetHiding.java deleted file mode 100644 index f6b4e632b4..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSheetHiding.java +++ /dev/null @@ -1,28 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestSheetHiding; - -public final class TestSheetHiding extends BaseTestSheetHiding { - public TestSheetHiding() { - super(XSSFITestDataProvider.instance, - "TwoSheetsOneHidden.xlsx", "TwoSheetsNoneHidden.xlsx"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestTableStyles.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestTableStyles.java deleted file mode 100644 index e83cb1cd83..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestTableStyles.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.assertTrue; - -import org.apache.poi.ss.usermodel.DifferentialStyleProvider; -import org.apache.poi.ss.usermodel.FontFormatting; -import org.apache.poi.ss.usermodel.PatternFormatting; -import org.apache.poi.ss.usermodel.Table; -import org.apache.poi.ss.usermodel.TableStyle; -import org.apache.poi.ss.usermodel.TableStyleInfo; -import org.apache.poi.ss.usermodel.TableStyleType; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * Test built-in table styles - */ -class TestTableStyles { - - /** - * Test that a built-in style is initialized properly - */ - @Test - void testBuiltinStyleInit() { - TableStyle style = XSSFBuiltinTableStyle.TableStyleMedium2.getStyle(); - assertNotNull(style, "no style found for Medium2"); - assertNull(style.getStyle(TableStyleType.blankRow), "Should not have style info for blankRow"); - DifferentialStyleProvider headerRow = style.getStyle(TableStyleType.headerRow); - assertNotNull(headerRow, "no header row style"); - FontFormatting font = headerRow.getFontFormatting(); - assertNotNull(font, "No header row font formatting"); - assertTrue(font.isBold(), "header row not bold"); - PatternFormatting fill = headerRow.getPatternFormatting(); - assertNotNull(fill, "No header fill"); - assertEquals(4, ((XSSFColor) fill.getFillBackgroundColorColor()).getTheme(), "wrong header fill"); - } - - @Test - void testCustomStyle() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("tableStyle.xlsx")) { - Table table = wb.getTable("Table1"); - assertNotNull(table, "missing table"); - - TableStyleInfo style = table.getStyle(); - assertNotNull(style, "Missing table style info"); - assertNotNull(style.getStyle(), "Missing table style"); - assertEquals("TestTableStyle", style.getName(), "Wrong name"); - assertEquals("TestTableStyle", style.getStyle().getName(), "Wrong name"); - - DifferentialStyleProvider firstColumn = style.getStyle().getStyle(TableStyleType.firstColumn); - assertNotNull(firstColumn, "no first column style"); - FontFormatting font = firstColumn.getFontFormatting(); - assertNotNull(font, "no first col font"); - assertTrue(font.isBold(), "wrong first col bold"); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java deleted file mode 100644 index 4c9baa3a04..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java +++ /dev/null @@ -1,406 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -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.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Calendar; -import java.util.Date; -import java.util.Hashtable; - -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; -import org.apache.poi.ss.formula.udf.DefaultUDFFinder; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.RichTextString; -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.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellUtil; -import org.apache.poi.ss.util.RegionUtil; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; - -/** - * @author centic - * - * This testcase contains tests for bugs that are yet to be fixed. Therefore, - * the standard ant test target does not run these tests. Run this testcase with - * the single-test target. The names of the tests usually correspond to the - * Bugzilla id's PLEASE MOVE tests from this class to TestBugs once the bugs are - * fixed, so that they are then run automatically. - */ -public final class TestUnfixedBugs { - @Test - void test54071() throws Exception { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("54071.xlsx"); - Sheet sheet = workbook.getSheetAt(0); - int rows = sheet.getPhysicalNumberOfRows(); - Row title = sheet.getRow(0); - - Date prev = null; - for (int row = 1; row < rows; row++) { - Row rowObj = sheet.getRow(row); - for (int col = 0; col < 1; col++) { - String titleName = title.getCell(col).toString(); - Cell cell = rowObj.getCell(col); - if (titleName.startsWith("time")) { - // here the output will produce ...59 or ...58 for the rows, probably POI is - // doing some different rounding or some other small difference... - //System.out.println("==Time:"+cell.getDateCellValue()); - if(prev != null) { - assertEquals(prev, cell.getDateCellValue()); - } - - prev = cell.getDateCellValue(); - } - } - } - - workbook.close(); - } - - @Test - void test54071Simple() { - double value1 = 41224.999988425923; - double value2 = 41224.999988368058; - - int wholeDays1 = (int)Math.floor(value1); - int millisecondsInDay1 = (int)((value1 - wholeDays1) * DateUtil.DAY_MILLISECONDS + 0.5); - - int wholeDays2 = (int)Math.floor(value2); - int millisecondsInDay2 = (int)((value2 - wholeDays2) * DateUtil.DAY_MILLISECONDS + 0.5); - - assertEquals(wholeDays1, wholeDays2); - // here we see that the time-value is 5 milliseconds apart, one is 86399000 and the other is 86398995, - // thus one is one second higher than the other - assertEquals(millisecondsInDay1, millisecondsInDay2, "The time-values are 5 milliseconds apart"); - - // when we do the calendar-stuff, there is a boolean which determines if - // the milliseconds are rounded or not, having this at "false" causes the - // second to be different here! - int startYear = 1900; - int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't - Calendar calendar1 = LocaleUtil.getLocaleCalendar(startYear,0, wholeDays1 + dayAdjust); - calendar1.set(Calendar.MILLISECOND, millisecondsInDay1); - // this is the rounding part: - calendar1.add(Calendar.MILLISECOND, 500); - calendar1.clear(Calendar.MILLISECOND); - - Calendar calendar2 = LocaleUtil.getLocaleCalendar(startYear,0, wholeDays2 + dayAdjust); - calendar2.set(Calendar.MILLISECOND, millisecondsInDay2); - // this is the rounding part: - calendar2.add(Calendar.MILLISECOND, 500); - calendar2.clear(Calendar.MILLISECOND); - - // now the calendars are equal - assertEquals(calendar1, calendar2); - - assertEquals(DateUtil.getJavaDate(value1, false), DateUtil.getJavaDate(value2, false)); - } - - // When this is fixed, the test case should go to BaseTestXCell with - // adjustments to use _testDataProvider to also verify this for XSSF - @Test - void testBug57294() throws IOException { - Workbook wb = SXSSFITestDataProvider.instance.createWorkbook(); - - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - RichTextString str = new XSSFRichTextString("Test rich text string"); - str.applyFont(2, 4, (short)0); - assertEquals(3, str.numFormattingRuns()); - cell.setCellValue(str); - - Workbook wbBack = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - wb.close(); - - // re-read after serializing and reading back - Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(0); - assertNotNull(cellBack); - RichTextString strBack = cellBack.getRichStringCellValue(); - assertNotNull(strBack); - assertEquals(3, strBack.numFormattingRuns()); - assertEquals(0, strBack.getIndexOfFormattingRun(0)); - assertEquals(2, strBack.getIndexOfFormattingRun(1)); - assertEquals(4, strBack.getIndexOfFormattingRun(2)); - - wbBack.close(); - } - - // This test will run green, but the resulting file is formatted incorrectly, - // see the bug at https://bz.apache.org/bugzilla/show_bug.cgi?id=55752 - @Test - void testBug55752() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - Sheet sheet = wb.createSheet("test"); - - for (int i = 0; i < 4; i++) { - Row row = sheet.createRow(i); - for (int j = 0; j < 2; j++) { - Cell cell = row.createCell(j); - cell.setCellStyle(wb.createCellStyle()); - } - } - - // set content - Row row1 = sheet.getRow(0); - row1.getCell(0).setCellValue("AAA"); - Row row2 = sheet.getRow(1); - row2.getCell(0).setCellValue("BBB"); - Row row3 = sheet.getRow(2); - row3.getCell(0).setCellValue("CCC"); - Row row4 = sheet.getRow(3); - row4.getCell(0).setCellValue("DDD"); - - // merge cells - CellRangeAddress range1 = new CellRangeAddress(0, 0, 0, 1); - assertEquals(0, sheet.addMergedRegion(range1)); - CellRangeAddress range2 = new CellRangeAddress(1, 1, 0, 1); - assertEquals(1, sheet.addMergedRegion(range2)); - CellRangeAddress range3 = new CellRangeAddress(2, 2, 0, 1); - assertEquals(2, sheet.addMergedRegion(range3)); - assertEquals(0, range3.getFirstColumn()); - assertEquals(1, range3.getLastColumn()); - assertEquals(2, range3.getLastRow()); - CellRangeAddress range4 = new CellRangeAddress(3, 3, 0, 1); - assertEquals(3, sheet.addMergedRegion(range4)); - - // set border - RegionUtil.setBorderBottom(BorderStyle.THIN, range1, sheet); - - row2.getCell(0).getCellStyle().setBorderBottom(BorderStyle.THIN); - row2.getCell(1).getCellStyle().setBorderBottom(BorderStyle.THIN); - - Cell cell0 = CellUtil.getCell(row3, 0); - CellUtil.setCellStyleProperty(cell0, CellUtil.BORDER_BOTTOM, BorderStyle.THIN); - Cell cell1 = CellUtil.getCell(row3, 1); - CellUtil.setCellStyleProperty(cell1, CellUtil.BORDER_BOTTOM, BorderStyle.THIN); - - RegionUtil.setBorderBottom(BorderStyle.THIN, range4, sheet); - - // write to file for manual inspection - XSSFTestDataSamples.writeOut(wb, "bug 55752 for review"); - } - - fail("Test runs ok, but the resulting file is incorrectly formatted"); - } - - @Test - void test57423() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57423.xlsx"); - - Sheet testSheet = wb.getSheetAt(0); - - // row shift (negative or positive) causes corrupted output xlsx file when the shift value is bigger - // than the number of rows being shifted - // Excel 2010 on opening the output file says: - // "Excel found unreadable content" and offers recovering the file by removing the unreadable content - // This can be observed in cases like the following: - // negative shift of 1 row by less than -1 - // negative shift of 2 rows by less than -2 - // positive shift of 1 row by 2 or more - // positive shift of 2 rows by 3 or more - - //testSheet.shiftRows(4, 5, -3); - testSheet.shiftRows(10, 10, 2); - - checkRows57423(testSheet); - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - /* XSSFTestDataSamples.writeOut(wb, "bug 57423 for manual review"); */ - - wb.close(); - - checkRows57423(wbBack.getSheetAt(0)); - - wbBack.close(); - - fail("Excel reports that the workbook is corrupt"); - } - - private void checkRows57423(Sheet testSheet) throws IOException { - checkRow57423(testSheet, 0, "0"); - checkRow57423(testSheet, 1, "1"); - checkRow57423(testSheet, 2, "2"); - checkRow57423(testSheet, 3, "3"); - checkRow57423(testSheet, 4, "4"); - checkRow57423(testSheet, 5, "5"); - checkRow57423(testSheet, 6, "6"); - checkRow57423(testSheet, 7, "7"); - checkRow57423(testSheet, 8, "8"); - checkRow57423(testSheet, 9, "9"); - - assertNull(testSheet.getRow(10), "Row number 10 should be gone after the shift"); - - checkRow57423(testSheet, 11, "11"); - checkRow57423(testSheet, 12, "10"); - checkRow57423(testSheet, 13, "13"); - checkRow57423(testSheet, 14, "14"); - checkRow57423(testSheet, 15, "15"); - checkRow57423(testSheet, 16, "16"); - checkRow57423(testSheet, 17, "17"); - checkRow57423(testSheet, 18, "18"); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - try { - ((XSSFSheet)testSheet).write(stream); - } finally { - stream.close(); - } - - // verify that the resulting XML has the rows in correct order as required by Excel - String xml = new String(stream.toByteArray(), StandardCharsets.UTF_8); - int posR12 = xml.indexOf("<row r=\"12\""); - int posR13 = xml.indexOf("<row r=\"13\""); - - // both need to be found - assertTrue(posR12 != -1); - assertTrue(posR13 != -1); - - assertTrue(posR12 < posR13, "Need to find row 12 before row 13 after the shifting, but had row 12 at " + posR12 + " and row 13 at " + posR13); - } - - private void checkRow57423(Sheet testSheet, int rowNum, String contents) { - Row row = testSheet.getRow(rowNum); - assertNotNull(row, "Expecting row at rownum " + rowNum); - - CTRow ctRow = ((XSSFRow)row).getCTRow(); - assertEquals(rowNum+1, ctRow.getR()); - - Cell cell = row.getCell(0); - assertNotNull(cell, "Expecting cell at rownum " + rowNum); - assertEquals( contents + ".0", cell.toString(), "Did not have expected contents at rownum " + rowNum ); - } - - @Test - void bug57423_shiftRowsByLargeOffset() throws IOException { - try ( - XSSFWorkbook wb = new XSSFWorkbook() - //OutputStream out = new FileOutputStream("/tmp/57423." + wb.getClass().getName() + ".xlsx")); - ) { - Sheet sh = wb.createSheet(); - sh.createRow(0).createCell(0).setCellValue("a"); - sh.createRow(1).createCell(0).setCellValue("b"); - sh.createRow(2).createCell(0).setCellValue("c"); - sh.shiftRows(0, 1, 3); - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - - assertThatRowsInAscendingOrder(wb); - assertThatRowsInAscendingOrder(wbBack); - - //wbBack.write(out); - // Excel reports that the workbook is corrupt because the rows are not in ascending order - // LibreOffice doesn't complain when rows are not in ascending order - - wbBack.close(); - - fail("Excel reports that the workbook is corrupt, LibreOffice can read it"); - } - } - - private void assertThatRowsInAscendingOrder(final XSSFWorkbook wb) { - // Check that CTRows are stored in ascending order of row index - long maxSeenRowNum = 0; //1-based - for (final CTRow ctRow : wb.getSheetAt(0).getCTWorksheet().getSheetData().getRowList()) { - final long rowNum = ctRow.getR(); //1-based - assertTrue(rowNum > maxSeenRowNum, "Row " + rowNum + " (1-based) is not in ascending order; previously saw " + maxSeenRowNum); - maxSeenRowNum = rowNum; - } - } - - @Test - void testBug60355() throws IOException { - try (Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("HsGetVal.xlsx")){ - - Sheet sheet = workbook.getSheetAt(workbook.getActiveSheetIndex()); - System.out.println("cell_4_1 formula:" + sheet.getRow(4).getCell(1).getCellFormula()); - System.out.println("cell_4_2 formula:" + sheet.getRow(4).getCell(2).getCellFormula()); - - // hard code HsGetValue test values for formulas on the sheet - Hashtable<CellAddress, String> cellToValueTable = new Hashtable<>(); - CellAddress cell4_1 = new CellAddress(4, 1); - cellToValueTable.put(cell4_1, "678.0"); - CellAddress cell4_2 = new CellAddress(4, 2); - cellToValueTable.put(cell4_2, "123.0"); - - String[] functionNames = {HsGetValue.name}; - FreeRefFunction[] functionImpls = {new HsGetValue(cellToValueTable)}; - UDFFinder udfs = new DefaultUDFFinder(functionNames, functionImpls); - UDFFinder udfToolpack = new AggregatingUDFFinder(udfs); - workbook.addToolPack(udfToolpack); - - FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator(); - formulaEvaluator.setIgnoreMissingWorkbooks(true); - assertDoesNotThrow(formulaEvaluator::evaluateAll); - } - } - - public static class HsGetValue implements FreeRefFunction { - public static final String name = "HsGetValue"; - - private final Hashtable<CellAddress, String> cellValues; - - public HsGetValue(Hashtable<CellAddress, String> cellValues) { - super(); - this.cellValues = cellValues; - } - - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext evaluationContext) { - int row = evaluationContext.getRowIndex(); - int column = evaluationContext.getColumnIndex(); - CellAddress cell = new CellAddress(row, column); - - String value = cellValues.get(cell); - return new NumberEval( Double.parseDouble(value) ); - } - - } - - @Test - void testBug64759() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64759.xlsx")) { - Sheet cloned = wb.cloneSheet(0); - assertNotNull(cloned); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java deleted file mode 100644 index 562fa9f246..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java +++ /dev/null @@ -1,3642 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static java.time.Duration.between; -import static java.time.Instant.now; -import static org.apache.logging.log4j.util.Unbox.box; -import static org.apache.poi.extractor.ExtractorFactory.OOXML_PACKAGE; -import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive; -import static org.junit.jupiter.api.Assertions.*; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Arrays; -import java.util.Calendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; -import java.util.TreeMap; - -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipFile; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.POIDataSamples; -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ooxml.POIXMLDocumentPart; -import org.apache.poi.ooxml.POIXMLDocumentPart.RelationPart; -import org.apache.poi.ooxml.POIXMLException; -import org.apache.poi.ooxml.POIXMLProperties; -import org.apache.poi.ooxml.util.DocumentHelper; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.util.ZipSecureFile; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.sl.usermodel.ObjectShape; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.ConditionalFormattingEvaluator; -import org.apache.poi.ss.formula.EvaluationConditionalFormatRule; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaRenderer; -import org.apache.poi.ss.formula.FormulaShifter; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.WorkbookEvaluatorProvider; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.Function; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.ss.util.CellUtil; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.NullOutputStream; -import org.apache.poi.util.TempFile; -import org.apache.poi.util.XMLHelper; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.XLSBUnsupportedException; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.CalculationChain; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill; -import org.apache.xmlbeans.XmlException; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.EnumSource; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedNames; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMergeCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMergeCells; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTFontImpl; -import org.xml.sax.InputSource; -import org.xml.sax.SAXParseException; -import org.xml.sax.XMLReader; - -public final class TestXSSFBugs extends BaseTestBugzillaIssues { - private static final Logger LOG = LogManager.getLogger(TestXSSFBugs.class); - - public TestXSSFBugs() { - super(XSSFITestDataProvider.instance); - } - - /** - * Named ranges had the right reference, but - * the wrong sheet name - */ - @Test - void bug45430() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx")) { - assertFalse(wb.isMacroEnabled()); - assertEquals(3, wb.getNumberOfNames()); - - assertEquals(0, wb.getName("SheetAA1").getCTName().getLocalSheetId()); - assertFalse(wb.getName("SheetAA1").getCTName().isSetLocalSheetId()); - assertEquals("SheetA!$A$1", wb.getName("SheetAA1").getRefersToFormula()); - assertEquals("SheetA", wb.getName("SheetAA1").getSheetName()); - - assertEquals(0, wb.getName("SheetBA1").getCTName().getLocalSheetId()); - assertFalse(wb.getName("SheetBA1").getCTName().isSetLocalSheetId()); - assertEquals("SheetB!$A$1", wb.getName("SheetBA1").getRefersToFormula()); - assertEquals("SheetB", wb.getName("SheetBA1").getSheetName()); - - assertEquals(0, wb.getName("SheetCA1").getCTName().getLocalSheetId()); - assertFalse(wb.getName("SheetCA1").getCTName().isSetLocalSheetId()); - assertEquals("SheetC!$A$1", wb.getName("SheetCA1").getRefersToFormula()); - assertEquals("SheetC", wb.getName("SheetCA1").getSheetName()); - - // Save and re-load, still there - try (XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb)) { - assertEquals(3, nwb.getNumberOfNames()); - assertEquals("SheetA!$A$1", nwb.getName("SheetAA1").getRefersToFormula()); - } - } - } - - /** - * We should carry vba macros over after save - */ - @Test - void bug45431() throws IOException, InvalidFormatException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("45431.xlsm"); - OPCPackage pkg1 = wb1.getPackage(); - assertTrue(wb1.isMacroEnabled()); - - // Check the various macro related bits can be found - PackagePart vba = pkg1.getPart( - PackagingURIHelper.createPartName("/xl/vbaProject.bin") - ); - assertNotNull(vba); - // And the drawing bit - PackagePart drw = pkg1.getPart( - PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") - ); - assertNotNull(drw); - - - // Save and re-open, both still there - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - pkg1.close(); - wb1.close(); - - OPCPackage pkg2 = wb2.getPackage(); - assertTrue(wb2.isMacroEnabled()); - - vba = pkg2.getPart( - PackagingURIHelper.createPartName("/xl/vbaProject.bin") - ); - assertNotNull(vba); - drw = pkg2.getPart( - PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") - ); - assertNotNull(drw); - - // And again, just to be sure - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - pkg2.close(); - wb2.close(); - OPCPackage pkg3 = wb3.getPackage(); - assertTrue(wb3.isMacroEnabled()); - - vba = pkg3.getPart( - PackagingURIHelper.createPartName("/xl/vbaProject.bin") - ); - assertNotNull(vba); - drw = pkg3.getPart( - PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") - ); - assertNotNull(drw); - - pkg3.close(); - wb3.close(); - } - - @Test - void bug47504() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47504.xlsx"); - assertEquals(1, wb1.getNumberOfSheets()); - XSSFSheet sh = wb1.getSheetAt(0); - XSSFDrawing drawing = sh.createDrawingPatriarch(); - List<RelationPart> rels = drawing.getRelationParts(); - assertEquals(1, rels.size()); - assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment()); - - // And again, just to be sure - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - assertEquals(1, wb2.getNumberOfSheets()); - sh = wb2.getSheetAt(0); - drawing = sh.createDrawingPatriarch(); - rels = drawing.getRelationParts(); - assertEquals(1, rels.size()); - assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment()); - wb2.close(); - } - - /** - * Excel will sometimes write a button with a textbox - * containing >br< (not closed!). - * Clearly Excel shouldn't do this, but test that we can - * read the file despite the naughtiness - */ - @Test - void bug49020() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx")) { - assertNotNull(wb); - } - } - - /** - * ensure that CTPhoneticPr is loaded by the ooxml test suite so that it is included in poi-ooxml-lite - */ - @Test - void bug49325() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx")) { - CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet(); - assertNotNull(sh.getPhoneticPr()); - } - } - - /** - * Names which are defined with a Sheet - * should return that sheet index properly - */ - @Test - void bug48923() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx")) { - assertEquals(4, wb.getNumberOfNames()); - - Name b1 = wb.getName("NameB1"); - Name b2 = wb.getName("NameB2"); - Name sheet2 = wb.getName("NameSheet2"); - Name test = wb.getName("Test"); - - assertNotNull(b1); - assertEquals("NameB1", b1.getNameName()); - assertEquals("Sheet1", b1.getSheetName()); - assertEquals(-1, b1.getSheetIndex()); - assertFalse(b1.isDeleted()); - assertFalse(b1.isHidden()); - - assertNotNull(b2); - assertEquals("NameB2", b2.getNameName()); - assertEquals("Sheet1", b2.getSheetName()); - assertEquals(-1, b2.getSheetIndex()); - assertFalse(b2.isDeleted()); - assertFalse(b2.isHidden()); - - assertNotNull(sheet2); - assertEquals("NameSheet2", sheet2.getNameName()); - assertEquals("Sheet2", sheet2.getSheetName()); - assertEquals(-1, sheet2.getSheetIndex()); - - assertNotNull(test); - assertEquals("Test", test.getNameName()); - assertEquals("Sheet1", test.getSheetName()); - assertEquals(-1, test.getSheetIndex()); - } - } - - /** - * Problem with evaluation formulas due to - * NameXPtgs. - * Blows up on: - * IF(B6= (ROUNDUP(B6,0) + ROUNDDOWN(B6,0))/2, MROUND(B6,2),ROUND(B6,0)) - * <p> - * TODO: delete this test case when MROUND and VAR are implemented - */ - @Test - void bug48539() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48539.xlsx")) { - assertEquals(3, wb.getNumberOfSheets()); - assertEquals(0, wb.getNumberOfNames()); - - // Try each cell individually - XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb); - for (int i = 0; i < wb.getNumberOfSheets(); i++) { - Sheet s = wb.getSheetAt(i); - for (Row r : s) { - for (Cell c : r) { - if (c.getCellType() == CellType.FORMULA) { - CellValue cv = eval.evaluate(c); - - if (cv.getCellType() == CellType.NUMERIC) { - // assert that the calculated value agrees with - // the cached formula result calculated by Excel - String formula = c.getCellFormula(); - double cachedFormulaResult = c.getNumericCellValue(); - double evaluatedFormulaResult = cv.getNumberValue(); - assertEquals(cachedFormulaResult, evaluatedFormulaResult, 1E-7, formula); - } - } - } - } - } - - // Now all of them - XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - } - } - - /** - * Foreground colours should be found even if - * a theme is used - */ - @Test - void bug48779() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) { - XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0); - XSSFCellStyle cs = cell.getCellStyle(); - - assertNotNull(cs); - assertEquals(1, cs.getIndex()); - - // Look at the low level xml elements - assertEquals(2, cs.getCoreXf().getFillId()); - assertEquals(0, cs.getCoreXf().getXfId()); - assertTrue(cs.getCoreXf().getApplyFill()); - - XSSFCellFill fg = wb.getStylesSource().getFillAt(2); - assertNotNull(fg.getFillForegroundColor()); - assertEquals(0, fg.getFillForegroundColor().getIndexed()); - assertEquals(0.0, fg.getFillForegroundColor().getTint(), 0); - assertEquals("FFFF0000", fg.getFillForegroundColor().getARGBHex()); - assertNotNull(fg.getFillBackgroundColor()); - assertEquals(64, fg.getFillBackgroundColor().getIndexed()); - - // Now look higher up - assertNotNull(cs.getFillForegroundXSSFColor()); - assertEquals(0, cs.getFillForegroundColor()); - assertEquals("FFFF0000", cs.getFillForegroundXSSFColor().getARGBHex()); - assertEquals("FFFF0000", cs.getFillForegroundColorColor().getARGBHex()); - - assertEquals(64, cs.getFillBackgroundColor()); - assertNull(cs.getFillBackgroundXSSFColor().getARGBHex()); - assertNull(cs.getFillBackgroundColorColor().getARGBHex()); - } - } - - /** - * Ensure General and @ format are working properly - * for integers - */ - @Test - void bug47490() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GeneralFormatTests.xlsx")) { - Sheet s = wb.getSheetAt(1); - Row r; - DataFormatter df = new DataFormatter(); - - r = s.getRow(1); - assertEquals(1.0, r.getCell(2).getNumericCellValue(), 0); - assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString()); - assertEquals("1", df.formatCellValue(r.getCell(2))); - assertEquals("1", df.formatRawCellContents(1.0, -1, "@")); - assertEquals("1", df.formatRawCellContents(1.0, -1, "General")); - - r = s.getRow(2); - assertEquals(12.0, r.getCell(2).getNumericCellValue(), 0); - assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString()); - assertEquals("12", df.formatCellValue(r.getCell(2))); - assertEquals("12", df.formatRawCellContents(12.0, -1, "@")); - assertEquals("12", df.formatRawCellContents(12.0, -1, "General")); - - r = s.getRow(3); - assertEquals(123.0, r.getCell(2).getNumericCellValue(), 0); - assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString()); - assertEquals("123", df.formatCellValue(r.getCell(2))); - assertEquals("123", df.formatRawCellContents(123.0, -1, "@")); - assertEquals("123", df.formatRawCellContents(123.0, -1, "General")); - } - } - - /** - * A problem file from a non-standard source (a scientific instrument that saves its - * output as an .xlsx file) that have two issues: - * 1. The Content Type part name is lower-case: [content_types].xml - * 2. The file appears to use backslashes as path separators - * <p> - * The OPC spec tolerates both of these peculiarities, so does POI - */ - @Test - void bug49609() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49609.xlsx")) { - assertEquals("FAM", wb.getSheetName(0)); - assertEquals("Cycle", wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue()); - } - - } - - @Test - void bug49783() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49783.xlsx")) { - Sheet sheet = wb.getSheetAt(0); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell; - - cell = sheet.getRow(0).getCell(0); - assertEquals("#REF!*#REF!", cell.getCellFormula()); - assertEquals(CellType.ERROR, evaluator.evaluateInCell(cell).getCellType()); - assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString()); - - Name nm1 = wb.getName("sale_1"); - assertNotNull(nm1, "name sale_1 should be present"); - assertEquals("Sheet1!#REF!", nm1.getRefersToFormula()); - Name nm2 = wb.getName("sale_2"); - assertNotNull(nm2, "name sale_2 should be present"); - assertEquals("Sheet1!#REF!", nm2.getRefersToFormula()); - - cell = sheet.getRow(1).getCell(0); - assertEquals("sale_1*sale_2", cell.getCellFormula()); - assertEquals(CellType.ERROR, evaluator.evaluateInCell(cell).getCellType()); - assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString()); - } - } - - /** - * Creating a rich string of "hello world" and applying - * a font to characters 1-5 means we have two strings, - * "hello" and " world". As such, we need to apply - * preserve spaces to the 2nd bit, lest we end up - * with something like "helloworld" ! - */ - @Test - void bug49941() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet s = wb1.createSheet(); - XSSFRow r = s.createRow(0); - XSSFCell c = r.createCell(0); - - // First without fonts - c.setCellValue( - new XSSFRichTextString(" with spaces ") - ); - assertEquals(" with spaces ", c.getRichStringCellValue().toString()); - assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray()); - assertTrue(c.getRichStringCellValue().getCTRst().isSetT()); - // Should have the preserve set - assertEquals( - 1, - c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength() - ); - assertEquals( - "preserve", - c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().item(0).getNodeValue() - ); - - // Save and check - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - assertEquals(" with spaces ", c.getRichStringCellValue().toString()); - assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray()); - assertTrue(c.getRichStringCellValue().getCTRst().isSetT()); - - // Change the string - c.setCellValue( - new XSSFRichTextString("hello world") - ); - assertEquals("hello world", c.getRichStringCellValue().toString()); - // Won't have preserve - assertEquals( - 0, - c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength() - ); - - // Apply a font - XSSFFont f = wb2.createFont(); - f.setBold(true); - c.getRichStringCellValue().applyFont(0, 5, f); - assertEquals("hello world", c.getRichStringCellValue().toString()); - // Does need preserving on the 2nd part - assertEquals(2, c.getRichStringCellValue().getCTRst().sizeOfRArray()); - assertEquals( - 0, - c.getRichStringCellValue().getCTRst().getRArray(0).xgetT().getDomNode().getAttributes().getLength() - ); - assertEquals( - 1, - c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().getLength() - ); - assertEquals( - "preserve", - c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().item(0).getNodeValue() - ); - - // Save and check - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - - s = wb3.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - assertEquals("hello world", c.getRichStringCellValue().toString()); - wb3.close(); - } - - /** - * Repeatedly writing the same file which has styles - */ - @Test - void bug49940() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx")) { - assertEquals(3, wb.getNumberOfSheets()); - assertEquals(10, wb.getStylesSource().getNumCellStyles()); - - ByteArrayOutputStream b1 = new ByteArrayOutputStream(); - ByteArrayOutputStream b2 = new ByteArrayOutputStream(); - ByteArrayOutputStream b3 = new ByteArrayOutputStream(); - wb.write(b1); - wb.write(b2); - wb.write(b3); - - for (byte[] data : new byte[][]{ - b1.toByteArray(), b2.toByteArray(), b3.toByteArray() - }) { - ByteArrayInputStream bais = new ByteArrayInputStream(data); - XSSFWorkbook wb2 = new XSSFWorkbook(bais); - assertEquals(3, wb2.getNumberOfSheets()); - assertEquals(10, wb2.getStylesSource().getNumCellStyles()); - wb2.close(); - } - } - } - - /** - * Various ways of removing a cell formula should all zap the calcChain - * entry. - */ - @Test - void bug49966() throws IOException { - try (XSSFWorkbook wb1 = XSSFTestDataSamples - .openSampleWorkbook("shared_formulas.xlsx")) { - XSSFSheet sheet = wb1.getSheetAt(0); - - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - // CalcChain has lots of entries - CalculationChain cc = wb1.getCalculationChain(); - assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR()); - assertEquals("A3", cc.getCTCalcChain().getCArray(1).getR()); - assertEquals("A4", cc.getCTCalcChain().getCArray(2).getR()); - assertEquals("A5", cc.getCTCalcChain().getCArray(3).getR()); - assertEquals("A6", cc.getCTCalcChain().getCArray(4).getR()); - assertEquals("A7", cc.getCTCalcChain().getCArray(5).getR()); - assertEquals("A8", cc.getCTCalcChain().getCArray(6).getR()); - assertEquals(40, cc.getCTCalcChain().sizeOfCArray()); - - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - // Try various ways of changing the formulas - // If it stays a formula, chain entry should remain - // Otherwise should go - sheet.getRow(1).getCell(0).setCellFormula("A1"); // stay - sheet.getRow(2).getCell(0).setCellFormula(null); // go - sheet.getRow(3).getCell(0).setCellFormula("14"); // stay - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - sheet.getRow(4).getCell(0).setBlank(); // go - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - validateCells(sheet); - sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go - validateCells(sheet); - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - sheet.getRow(6).getCell(0).setBlank(); // go - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - sheet.getRow(7).getCell(0).setCellValue((String) null); // go - - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - // Save and check - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { - wb1.close(); - assertEquals(35, cc.getCTCalcChain().sizeOfCArray()); - - cc = wb2.getCalculationChain(); - assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR()); - assertEquals("A4", cc.getCTCalcChain().getCArray(1).getR()); - assertEquals("A9", cc.getCTCalcChain().getCArray(2).getR()); - } - } - } - - @Test - void bug49966Row() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("shared_formulas.xlsx")) { - XSSFSheet sheet = wb.getSheetAt(0); - - validateCells(sheet); - sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go - validateCells(sheet); - } - } - - private void validateCells(XSSFSheet sheet) { - for (Row row : sheet) { - // trigger handling - ((XSSFRow) row).onDocumentWrite(); - } - } - - @Test - void bug49156() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49156.xlsx")) { - FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sheet = wb.getSheetAt(0); - for (Row row : sheet) { - for (Cell cell : row) { - if (cell.getCellType() == CellType.FORMULA) { - // caused NPE on some cells - assertDoesNotThrow(() -> formulaEvaluator.evaluateInCell(cell)); - } - } - } - } - } - - /** - * Newlines are valid characters in a formula - */ - @Test - void bug50440And51875() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("NewlineInFormulas.xlsx")) { - Sheet s = wb.getSheetAt(0); - Cell c = s.getRow(0).getCell(0); - - assertEquals("SUM(\n1,2\n)", c.getCellFormula()); - assertEquals(3.0, c.getNumericCellValue(), 0); - - FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - formulaEvaluator.evaluateFormulaCell(c); - - assertEquals("SUM(\n1,2\n)", c.getCellFormula()); - assertEquals(3.0, c.getNumericCellValue(), 0); - - // For 51875 - Cell b3 = s.getRow(2).getCell(1); - formulaEvaluator.evaluateFormulaCell(b3); - assertEquals("B1+B2", b3.getCellFormula()); // The newline is lost for shared formulas - assertEquals(3.0, b3.getNumericCellValue(), 0); - } - } - - /** - * Moving a cell comment from one cell to another - */ - @Test - void bug50795() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("50795.xlsx"); - XSSFSheet sheet = wb1.getSheetAt(0); - XSSFRow row = sheet.getRow(0); - - XSSFCell cellWith = row.getCell(0); - XSSFCell cellWithoutComment = row.getCell(1); - - assertNotNull(cellWith.getCellComment()); - assertNull(cellWithoutComment.getCellComment()); - - String exp = "\u0410\u0432\u0442\u043e\u0440:\ncomment"; - XSSFComment comment = cellWith.getCellComment(); - assertEquals(exp, comment.getString().getString()); - - - // Check we can write it out and read it back as-is - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - row = sheet.getRow(0); - cellWith = row.getCell(0); - cellWithoutComment = row.getCell(1); - - // Double check things are as expected - assertNotNull(cellWith.getCellComment()); - assertNull(cellWithoutComment.getCellComment()); - comment = cellWith.getCellComment(); - assertEquals(exp, comment.getString().getString()); - - - // Move the comment - cellWithoutComment.setCellComment(comment); - - - // Write out and re-check - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - - sheet = wb3.getSheetAt(0); - row = sheet.getRow(0); - - // Ensure it swapped over - cellWith = row.getCell(0); - cellWithoutComment = row.getCell(1); - assertNull(cellWith.getCellComment()); - assertNotNull(cellWithoutComment.getCellComment()); - - comment = cellWithoutComment.getCellComment(); - assertEquals(exp, comment.getString().getString()); - - wb3.close(); - } - - /** - * When the cell background colour is set with one of the first - * two columns of the theme colour palette, the colours are - * shades of white or black. - * For those cases, ensure we don't break on reading the colour - */ - @Test - void bug50299() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx")) { - - // Check all the colours - for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) { - Sheet s = wb.getSheetAt(sn); - for (Row r : s) { - for (Cell c : r) { - CellStyle cs = c.getCellStyle(); - if (cs != null) { - cs.getFillForegroundColor(); - } - } - } - } - - // Check one bit in detail - // Check that we get back foreground=0 for the theme colours, - // and background=64 for the auto colouring - Sheet s = wb.getSheetAt(0); - assertEquals(0, s.getRow(0).getCell(8).getCellStyle().getFillForegroundColor()); - assertEquals(64, s.getRow(0).getCell(8).getCellStyle().getFillBackgroundColor()); - assertEquals(0, s.getRow(1).getCell(8).getCellStyle().getFillForegroundColor()); - assertEquals(64, s.getRow(1).getCell(8).getCellStyle().getFillBackgroundColor()); - } - } - - /** - * Excel .xls style indexed colours in a .xlsx file - */ - @Test - void bug50786() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50786-indexed_colours.xlsx")) { - XSSFSheet s = wb.getSheetAt(0); - XSSFRow r = s.getRow(2); - - // Check we have the right cell - XSSFCell c = r.getCell(1); - assertEquals("test\u00a0", c.getRichStringCellValue().getString()); - - // It should be light green - XSSFCellStyle cs = c.getCellStyle(); - assertEquals(42, cs.getFillForegroundColor()); - assertEquals(42, cs.getFillForegroundColorColor().getIndexed()); - assertNotNull(cs.getFillForegroundColorColor().getRGB()); - assertEquals("FFCCFFCC", cs.getFillForegroundColorColor().getARGBHex()); - } - } - - /** - * If the border colours are set with themes, then we - * should still be able to get colours - */ - @Test - void bug50846() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50846-border_colours.xlsx")) { - - XSSFSheet sheet = wb.getSheetAt(0); - XSSFRow row = sheet.getRow(0); - - // Border from a theme, brown - XSSFCell cellT = row.getCell(0); - XSSFCellStyle styleT = cellT.getCellStyle(); - XSSFColor colorT = styleT.getBottomBorderXSSFColor(); - - assertEquals(5, colorT.getTheme()); - assertEquals("FFC0504D", colorT.getARGBHex()); - - // Border from a style direct, red - XSSFCell cellS = row.getCell(1); - XSSFCellStyle styleS = cellS.getCellStyle(); - XSSFColor colorS = styleS.getBottomBorderXSSFColor(); - - assertEquals(0, colorS.getTheme()); - assertEquals("FFFF0000", colorS.getARGBHex()); - } - } - - /** - * Fonts where their colours come from the theme rather - * then being set explicitly still should allow the - * fetching of the RGB. - */ - @Test - void bug50784() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50784-font_theme_colours.xlsx")) { - XSSFSheet s = wb.getSheetAt(0); - XSSFRow r = s.getRow(0); - - // Column 1 has a font with regular colours - XSSFCell cr = r.getCell(1); - XSSFFont fr = wb.getFontAt(cr.getCellStyle().getFontIndex()); - XSSFColor colr = fr.getXSSFColor(); - // No theme, has colours - assertEquals(0, colr.getTheme()); - assertNotNull(colr.getRGB()); - - // Column 0 has a font with colours from a theme - XSSFCell ct = r.getCell(0); - XSSFFont ft = wb.getFontAt(ct.getCellStyle().getFontIndex()); - XSSFColor colt = ft.getXSSFColor(); - // Has a theme, which has the colours on it - assertEquals(9, colt.getTheme()); - XSSFColor themeC = wb.getTheme().getThemeColor(colt.getTheme()); - assertNotNull(themeC.getRGB()); - assertNotNull(colt.getRGB()); - assertEquals(themeC.getARGBHex(), colt.getARGBHex()); // The same colour - } - } - - /** - * New lines were being eaten when setting a font on - * a rich text string - */ - @Test - void bug48877() throws IOException { - String text = "Use \n with word wrap on to create a new line.\n" + - "This line finishes with two trailing spaces. "; - - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - - Font font1 = wb1.createFont(); - font1.setColor((short) 20); - Font font2 = wb1.createFont(); - font2.setColor(Font.COLOR_RED); - Font font3 = wb1.getFontAt(0); - - XSSFRow row = sheet.createRow(2); - XSSFCell cell = row.createCell(2); - - XSSFRichTextString richTextString = - wb1.getCreationHelper().createRichTextString(text); - - // Check the text has the newline - assertEquals(text, richTextString.getString()); - - // Apply the font - richTextString.applyFont(font3); - richTextString.applyFont(0, 3, font1); - cell.setCellValue(richTextString); - - // To enable newlines you need set a cell styles with wrap=true - CellStyle cs = wb1.createCellStyle(); - cs.setWrapText(true); - cell.setCellStyle(cs); - - // Check the text has the - assertEquals(text, cell.getStringCellValue()); - - // Save the file and re-read it - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - row = sheet.getRow(2); - cell = row.getCell(2); - assertEquals(text, cell.getStringCellValue()); - - // Now add a 2nd, and check again - int fontAt = text.indexOf('\n', 6); - cell.getRichStringCellValue().applyFont(10, fontAt + 1, font2); - assertEquals(text, cell.getStringCellValue()); - - assertEquals(4, cell.getRichStringCellValue().numFormattingRuns()); - assertEquals("Use", cell.getRichStringCellValue().getCTRst().getRArray(0).getT()); - - String r3 = cell.getRichStringCellValue().getCTRst().getRArray(2).getT(); - assertEquals("line.\n", r3.substring(r3.length() - 6)); - - // Save and re-check - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - - sheet = wb3.getSheetAt(0); - row = sheet.getRow(2); - cell = row.getCell(2); - assertEquals(text, cell.getStringCellValue()); - wb3.close(); - - // FileOutputStream out = new FileOutputStream("/tmp/test48877.xlsx"); - // wb.write(out); - // out.close(); - } - - /** - * Adding sheets when one has a table, then re-ordering - */ - @Test - void bug50867() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("50867_with_table.xlsx"); - assertEquals(3, wb1.getNumberOfSheets()); - - XSSFSheet s1 = wb1.getSheetAt(0); - XSSFSheet s2 = wb1.getSheetAt(1); - XSSFSheet s3 = wb1.getSheetAt(2); - assertEquals(1, s1.getTables().size()); - assertEquals(0, s2.getTables().size()); - assertEquals(0, s3.getTables().size()); - - XSSFTable t = s1.getTables().get(0); - assertEquals("Tabella1", t.getName()); - assertEquals("Tabella1", t.getDisplayName()); - assertEquals("A1:C3", t.getCTTable().getRef()); - - // Add a sheet and re-order - XSSFSheet s4 = wb1.createSheet("NewSheet"); - wb1.setSheetOrder(s4.getSheetName(), 0); - - // Check on tables - assertEquals(1, s1.getTables().size()); - assertEquals(0, s2.getTables().size()); - assertEquals(0, s3.getTables().size()); - assertEquals(0, s4.getTables().size()); - - // Refetch to get the new order - s1 = wb1.getSheetAt(0); - s2 = wb1.getSheetAt(1); - s3 = wb1.getSheetAt(2); - s4 = wb1.getSheetAt(3); - assertEquals(0, s1.getTables().size()); - assertEquals(1, s2.getTables().size()); - assertEquals(0, s3.getTables().size()); - assertEquals(0, s4.getTables().size()); - - // Save and re-load - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - s1 = wb2.getSheetAt(0); - s2 = wb2.getSheetAt(1); - s3 = wb2.getSheetAt(2); - s4 = wb2.getSheetAt(3); - assertEquals(0, s1.getTables().size()); - assertEquals(1, s2.getTables().size()); - assertEquals(0, s3.getTables().size()); - assertEquals(0, s4.getTables().size()); - - t = s2.getTables().get(0); - assertEquals("Tabella1", t.getName()); - assertEquals("Tabella1", t.getDisplayName()); - assertEquals("A1:C3", t.getCTTable().getRef()); - - - // Add some more tables, and check - t = s2.createTable(null); - t.setName("New 2"); - t.setDisplayName("New 2"); - t = s3.createTable(null); - t.setName("New 3"); - t.setDisplayName("New 3"); - - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - s1 = wb3.getSheetAt(0); - s2 = wb3.getSheetAt(1); - s3 = wb3.getSheetAt(2); - s4 = wb3.getSheetAt(3); - assertEquals(0, s1.getTables().size()); - assertEquals(2, s2.getTables().size()); - assertEquals(1, s3.getTables().size()); - assertEquals(0, s4.getTables().size()); - - t = s2.getTables().get(0); - assertEquals("Tabella1", t.getName()); - assertEquals("Tabella1", t.getDisplayName()); - assertEquals("A1:C3", t.getCTTable().getRef()); - - t = s2.getTables().get(1); - assertEquals("New 2", t.getName()); - assertEquals("New 2", t.getDisplayName()); - - t = s3.getTables().get(0); - assertEquals("New 3", t.getName()); - assertEquals("New 3", t.getDisplayName()); - - // Check the relationships - assertEquals(0, s1.getRelations().size()); - assertEquals(3, s2.getRelations().size()); - assertEquals(1, s3.getRelations().size()); - assertEquals(0, s4.getRelations().size()); - - assertEquals( - XSSFRelation.PRINTER_SETTINGS.getContentType(), - s2.getRelations().get(0).getPackagePart().getContentType() - ); - assertEquals( - XSSFRelation.TABLE.getContentType(), - s2.getRelations().get(1).getPackagePart().getContentType() - ); - assertEquals( - XSSFRelation.TABLE.getContentType(), - s2.getRelations().get(2).getPackagePart().getContentType() - ); - assertEquals( - XSSFRelation.TABLE.getContentType(), - s3.getRelations().get(0).getPackagePart().getContentType() - ); - assertEquals( - "/xl/tables/table3.xml", - s3.getRelations().get(0).getPackagePart().getPartName().toString() - ); - wb3.close(); - } - - /** - * Setting repeating rows and columns shouldn't break - * any print settings that were there before - */ - @Test - void bug49253() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFWorkbook wb2 = new XSSFWorkbook(); - CellRangeAddress cra = CellRangeAddress.valueOf("C2:D3"); - - // No print settings before repeating - XSSFSheet s1 = wb1.createSheet(); - assertFalse(s1.getCTWorksheet().isSetPageSetup()); - assertTrue(s1.getCTWorksheet().isSetPageMargins()); - s1.setRepeatingColumns(cra); - s1.setRepeatingRows(cra); - - assertTrue(s1.getCTWorksheet().isSetPageSetup()); - assertTrue(s1.getCTWorksheet().isSetPageMargins()); - - PrintSetup ps1 = s1.getPrintSetup(); - assertFalse(ps1.getValidSettings()); - assertFalse(ps1.getLandscape()); - - - // Had valid print settings before repeating - XSSFSheet s2 = wb2.createSheet(); - PrintSetup ps2 = s2.getPrintSetup(); - assertTrue(s2.getCTWorksheet().isSetPageSetup()); - assertTrue(s2.getCTWorksheet().isSetPageMargins()); - - ps2.setLandscape(false); - assertTrue(ps2.getValidSettings()); - assertFalse(ps2.getLandscape()); - s2.setRepeatingColumns(cra); - s2.setRepeatingRows(cra); - - ps2 = s2.getPrintSetup(); - assertTrue(s2.getCTWorksheet().isSetPageSetup()); - assertTrue(s2.getCTWorksheet().isSetPageMargins()); - assertTrue(ps2.getValidSettings()); - assertFalse(ps2.getLandscape()); - - wb1.close(); - wb2.close(); - } - - /** - * Default Column style - */ - @Test - void bug51037() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet s = wb.createSheet(); - - CellStyle defaultStyle = wb.getCellStyleAt((short) 0); - assertEquals(0, defaultStyle.getIndex()); - - CellStyle blueStyle = wb.createCellStyle(); - blueStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex()); - blueStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - assertEquals(1, blueStyle.getIndex()); - - CellStyle pinkStyle = wb.createCellStyle(); - pinkStyle.setFillForegroundColor(IndexedColors.PINK.getIndex()); - pinkStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - assertEquals(2, pinkStyle.getIndex()); - - // Starts empty - assertEquals(1, s.getCTWorksheet().sizeOfColsArray()); - CTCols cols = s.getCTWorksheet().getColsArray(0); - assertEquals(0, cols.sizeOfColArray()); - - // Add some rows and columns - XSSFRow r1 = s.createRow(0); - XSSFRow r2 = s.createRow(1); - r1.createCell(0); - r1.createCell(2); - r2.createCell(0); - r2.createCell(3); - - // Check no style is there - assertEquals(1, s.getCTWorksheet().sizeOfColsArray()); - assertEquals(0, cols.sizeOfColArray()); - - assertEquals(defaultStyle, s.getColumnStyle(0)); - assertEquals(defaultStyle, s.getColumnStyle(2)); - assertEquals(defaultStyle, s.getColumnStyle(3)); - - - // Apply the styles - s.setDefaultColumnStyle(0, pinkStyle); - s.setDefaultColumnStyle(3, blueStyle); - - // Check - assertEquals(pinkStyle, s.getColumnStyle(0)); - assertEquals(defaultStyle, s.getColumnStyle(2)); - assertEquals(blueStyle, s.getColumnStyle(3)); - - assertEquals(1, s.getCTWorksheet().sizeOfColsArray()); - assertEquals(2, cols.sizeOfColArray()); - - assertEquals(1, cols.getColArray(0).getMin()); - assertEquals(1, cols.getColArray(0).getMax()); - assertEquals(pinkStyle.getIndex(), cols.getColArray(0).getStyle()); - - assertEquals(4, cols.getColArray(1).getMin()); - assertEquals(4, cols.getColArray(1).getMax()); - assertEquals(blueStyle.getIndex(), cols.getColArray(1).getStyle()); - - - // Save, re-load and re-check - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - s = wbBack.getSheetAt(0); - defaultStyle = wbBack.getCellStyleAt(defaultStyle.getIndex()); - blueStyle = wbBack.getCellStyleAt(blueStyle.getIndex()); - pinkStyle = wbBack.getCellStyleAt(pinkStyle.getIndex()); - - assertEquals(pinkStyle, s.getColumnStyle(0)); - assertEquals(defaultStyle, s.getColumnStyle(2)); - assertEquals(blueStyle, s.getColumnStyle(3)); - wbBack.close(); - } - - /** - * Repeatedly writing a file. - * Something with the SharedStringsTable currently breaks... - */ - @Test - void bug46662() throws IOException { - for (int i=0; i<2; i++) { - try (XSSFWorkbook wb1 = (i == 0) ? new XSSFWorkbook() : XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) { - for (int j=0; j<3; j++) { - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { - assertEquals(wb1.getNumberOfSheets(), wb2.getNumberOfSheets()); - } - } - } - } - - // TODO: Complex file - } - - /** - * Colours and styles when the list has gaps in it - */ - @Test - void bug51222() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51222.xlsx")) { - XSSFSheet s = wb.getSheetAt(0); - - XSSFCell cA4_EEECE1 = s.getRow(3).getCell(0); - XSSFCell cA5_1F497D = s.getRow(4).getCell(0); - - // Check the text - assertEquals("A4", cA4_EEECE1.getRichStringCellValue().getString()); - assertEquals("A5", cA5_1F497D.getRichStringCellValue().getString()); - - // Check the styles assigned to them - assertEquals(4, cA4_EEECE1.getCTCell().getS()); - assertEquals(5, cA5_1F497D.getCTCell().getS()); - - // Check we look up the correct style - assertEquals(4, cA4_EEECE1.getCellStyle().getIndex()); - assertEquals(5, cA5_1F497D.getCellStyle().getIndex()); - - // Check the fills on them at the low level - assertEquals(5, cA4_EEECE1.getCellStyle().getCoreXf().getFillId()); - assertEquals(6, cA5_1F497D.getCellStyle().getCoreXf().getFillId()); - - // These should reference themes 2 and 3 - assertEquals(2, wb.getStylesSource().getFillAt(5).getCTFill().getPatternFill().getFgColor().getTheme()); - assertEquals(3, wb.getStylesSource().getFillAt(6).getCTFill().getPatternFill().getFgColor().getTheme()); - - // Ensure we get the right colours for these themes - // TODO fix - // assertEquals("FFEEECE1", wb.getTheme().getThemeColor(2).getARGBHex()); - // assertEquals("FF1F497D", wb.getTheme().getThemeColor(3).getARGBHex()); - - // Finally check the colours on the styles - // TODO fix - // assertEquals("FFEEECE1", cA4_EEECE1.getCellStyle().getFillForegroundXSSFColor().getARGBHex()); - // assertEquals("FF1F497D", cA5_1F497D.getCellStyle().getFillForegroundXSSFColor().getARGBHex()); - } - } - - @Test - void bug51470() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51470.xlsx")) { - XSSFSheet sh0 = wb.getSheetAt(0); - XSSFSheet sh1 = wb.cloneSheet(0); - List<RelationPart> rels0 = sh0.getRelationParts(); - List<RelationPart> rels1 = sh1.getRelationParts(); - assertEquals(1, rels0.size()); - assertEquals(1, rels1.size()); - - PackageRelationship pr0 = rels0.get(0).getRelationship(); - PackageRelationship pr1 = rels1.get(0).getRelationship(); - - assertEquals(pr0.getTargetMode(), pr1.getTargetMode()); - assertEquals(pr0.getTargetURI(), pr1.getTargetURI()); - POIXMLDocumentPart doc0 = rels0.get(0).getDocumentPart(); - POIXMLDocumentPart doc1 = rels1.get(0).getDocumentPart(); - - assertEquals(doc0, doc1); - } - } - - /** - * Add comments to Sheet 1, when Sheet 2 already has - * comments (so /xl/comments1.xml is taken) - */ - @Test - void bug51850() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("51850.xlsx"); - XSSFSheet sh1 = wb1.getSheetAt(0); - XSSFSheet sh2 = wb1.getSheetAt(1); - - // Sheet 2 has comments - assertNotNull(sh2.getCommentsTable(false)); - assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments()); - - // Sheet 1 doesn't (yet) - assertNull(sh1.getCommentsTable(false)); - - // Try to add comments to Sheet 1 - CreationHelper factory = wb1.getCreationHelper(); - Drawing<?> drawing = sh1.createDrawingPatriarch(); - - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(0); - anchor.setCol2(4); - anchor.setRow1(0); - anchor.setRow2(1); - - Comment comment1 = drawing.createCellComment(anchor); - comment1.setString( - factory.createRichTextString("I like this cell. It's my favourite.")); - comment1.setAuthor("Bob T. Fish"); - - anchor = factory.createClientAnchor(); - anchor.setCol1(0); - anchor.setCol2(4); - anchor.setRow1(1); - anchor.setRow2(1); - Comment comment2 = drawing.createCellComment(anchor); - comment2.setString( - factory.createRichTextString("This is much less fun...")); - comment2.setAuthor("Bob T. Fish"); - - Cell c1 = sh1.getRow(0).createCell(4); - c1.setCellValue(2.3); - c1.setCellComment(comment1); - - Cell c2 = sh1.getRow(0).createCell(5); - c2.setCellValue(2.1); - c2.setCellComment(comment2); - - - // Save and re-load - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh1 = wb2.getSheetAt(0); - sh2 = wb2.getSheetAt(1); - - // Check the comments - assertNotNull(sh2.getCommentsTable(false)); - assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments()); - - assertNotNull(sh1.getCommentsTable(false)); - assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments()); - wb2.close(); - } - - /** - * Sheet names with a , in them - */ - @Test - void bug51963() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx")) { - Sheet sheet = wb.getSheetAt(0); - assertEquals("Abc,1", sheet.getSheetName()); - - Name name = wb.getName("Intekon.ProdCodes"); - assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula()); - - AreaReference ref = wb.getCreationHelper().createAreaReference(name.getRefersToFormula()); - assertEquals(0, ref.getFirstCell().getRow()); - assertEquals(0, ref.getFirstCell().getCol()); - assertEquals(1, ref.getLastCell().getRow()); - assertEquals(0, ref.getLastCell().getCol()); - } - } - - /** - * Sum across multiple workbooks - * eg =SUM($Sheet1.C1:$Sheet4.C1) - */ - @Test - void bug48703() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx")) { - XSSFSheet sheet = wb.getSheetAt(0); - - // Contains two forms, one with a range and one a list - XSSFRow r1 = sheet.getRow(0); - XSSFRow r2 = sheet.getRow(1); - XSSFCell c1 = r1.getCell(1); - XSSFCell c2 = r2.getCell(1); - - assertEquals(20.0, c1.getNumericCellValue(), 0); - assertEquals("SUM(Sheet1!C1,Sheet2!C1,Sheet3!C1,Sheet4!C1)", c1.getCellFormula()); - - assertEquals(20.0, c2.getNumericCellValue(), 0); - assertEquals("SUM(Sheet1:Sheet4!C1)", c2.getCellFormula()); - - // Try evaluating both - XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb); - eval.evaluateFormulaCell(c1); - eval.evaluateFormulaCell(c2); - - assertEquals(20.0, c1.getNumericCellValue(), 0); - assertEquals(20.0, c2.getNumericCellValue(), 0); - } - } - - /** - * Bugzilla 51710: problems reading shared formuals from .xlsx - */ - @Test - void bug51710() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx")) { - - final String[] columns = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"}; - final int rowMax = 500; // bug triggers on row index 59 - - Sheet sheet = wb.getSheetAt(0); - - - // go through all formula cells - for (int rInd = 2; rInd <= rowMax; rInd++) { - Row row = sheet.getRow(rInd); - - for (int cInd = 1; cInd <= 12; cInd++) { - Cell cell = row.getCell(cInd); - String formula = cell.getCellFormula(); - CellReference ref = new CellReference(cell); - - //simulate correct answer - String correct = "$A" + (rInd + 1) + "*" + columns[cInd] + "$2"; - - assertEquals(correct, formula, "Incorrect formula in " + ref.formatAsString()); - } - - } - } - } - - /** - * Bug 53101: - */ - @Test - void bug5301() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx")) { - FormulaEvaluator evaluator = - wb.getCreationHelper().createFormulaEvaluator(); - // A1: SUM(B1: IZ1) - double a1Value = - evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(0)).getNumberValue(); - - // Assert - assertEquals(259.0, a1Value, 0.0); - - // KY: SUM(B1: IZ1) - /*double ky1Value =*/ - assertEquals(259.0, evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(310)).getNumberValue(), 0.0001); - - // Assert - assertEquals(259.0, a1Value, 0.0); - } - } - - @Test - void bug54436() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx")) { - if (!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")) { - Function func = (args, srcRowIndex, srcColumnIndex) -> ErrorEval.NA; - - WorkbookEvaluator.registerFunction("GETPIVOTDATA", func); - } - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - assertDoesNotThrow(fe::evaluateAll); - } - } - - /** - * Password Protected .xlsx files are now (as of 4.0.0) tested for the default password - * when opened via WorkbookFactory, so there's no EncryptedDocumentException thrown anymore - */ - @Test - void bug55692_poifs() throws IOException { - // Via a POIFSFileSystem - try (POIFSFileSystem fsP = new POIFSFileSystem( - POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); - Workbook wb = WorkbookFactory.create(fsP)) { - assertNotNull(wb); - assertEquals(3, wb.getNumberOfSheets()); - } - } - - @Test - void bug55692_stream() throws IOException { - // Directly on a Stream, will go via POIFS and spot it's - // actually a .xlsx file encrypted with the default password, and open - try (Workbook wb = WorkbookFactory.create( - POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"))) { - assertNotNull(wb); - assertEquals(3, wb.getNumberOfSheets()); - } - } - - @Test - void bug55692_poifs2() throws IOException { - // Via a POIFSFileSystem, will spot it's actually a .xlsx file - // encrypted with the default password, and open - try (POIFSFileSystem fsNP = new POIFSFileSystem( - POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"))) { - Workbook wb = WorkbookFactory.create(fsNP); - assertNotNull(wb); - assertEquals(3, wb.getNumberOfSheets()); - wb.close(); - } - } - - @Test - void bug53282() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx")) { - Cell c = wb.getSheetAt(0).getRow(1).getCell(0); - assertEquals("#@_#", c.getStringCellValue()); - assertEquals("http://invalid.uri", c.getHyperlink().getAddress()); - } - } - - /** - * Was giving NullPointerException - * at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead - * due to a lack of Styles Table - */ - @Test - void bug56278() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx")) { - assertEquals(0, wb.getSheetIndex("Market Rates")); - - // Save and re-check - Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(0, nwb.getSheetIndex("Market Rates")); - nwb.close(); - } - } - - @Test - void bug56315() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx")) { - Cell c = wb.getSheetAt(0).getRow(1).getCell(0); - CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c); - double rounded = cv.getNumberValue(); - assertEquals(0.1, rounded, 0.0); - } - } - - @Test - void bug56468() throws IOException, InterruptedException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellValue("Hi"); - sheet.setRepeatingRows(new CellRangeAddress(0, 0, 0, 0)); - - // small hack to try to make this test stable, previously it failed whenever the two written ZIP files had - // different file-creation dates stored. We try to do a loop until the current second changes in order to - // avoid problems with some date information that is written to the ZIP and thus causes differences - long start = System.currentTimeMillis() / 1000; - while (System.currentTimeMillis() / 1000 == start) { - Thread.sleep(10); - } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(8096); - wb.write(bos); - byte[] firstSave = bos.toByteArray(); - bos.reset(); - wb.write(bos); - byte[] secondSave = bos.toByteArray(); - - assertArrayEquals(firstSave, secondSave, - "Had: \n" + Arrays.toString(firstSave) + " and \n" + Arrays.toString(secondSave)); - } - } - - /** - * ISO-8601 style cell formats with a T in them, eg - * cell format of "yyyy-MM-ddTHH:mm:ss" - */ - @Test - void bug54034() throws IOException { - TimeZone tz = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - try { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx")) { - Sheet sheet = wb.getSheet("Sheet1"); - Row row = sheet.getRow(1); - Cell cell = row.getCell(2); - assertTrue(DateUtil.isCellDateFormatted(cell)); - - DataFormatter fmt = new DataFormatter(); - assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString()); - assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell)); - } - } finally { - LocaleUtil.setUserTimeZone(tz); - } - } - - - @Test - void testBug53798XLSX() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) { - File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); - bug53798Work(wb, xlsOutput); - } - } - - @Disabled("Shifting rows is not yet implemented in SXSSFSheet") - @Test - void testBug53798XLSXStream() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) { - File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); - SXSSFWorkbook wb2 = new SXSSFWorkbook(wb); - bug53798Work(wb2, xlsOutput); - wb2.close(); - } - } - - @Test - void testBug53798XLS() throws IOException { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls"); - File xlsOutput = TempFile.createTempFile("testBug53798", ".xls"); - bug53798Work(wb, xlsOutput); - wb.close(); - } - - /** - * SUMIF was throwing a NPE on some formulas - */ - @Test - void testBug56420SumIfNPE() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx")) { - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sheet = wb.getSheetAt(0); - Row r = sheet.getRow(2); - Cell c = r.getCell(2); - assertEquals("SUMIF($A$1:$A$4,A3,$B$1:$B$4)", c.getCellFormula()); - Cell eval = evaluator.evaluateInCell(c); - assertEquals(0.0, eval.getNumericCellValue(), 0.0001); - } - } - - private void bug53798Work(Workbook wb, File xlsOutput) throws IOException { - Sheet testSheet = wb.getSheetAt(0); - - testSheet.shiftRows(2, 2, 1); - - saveAndReloadReport(wb, xlsOutput); - - // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about - // when shifted by less than -1 negative amount (try -2) - testSheet.shiftRows(3, 3, -1); - - saveAndReloadReport(wb, xlsOutput); - - testSheet.shiftRows(2, 2, 1); - - saveAndReloadReport(wb, xlsOutput); - - // 2) attempt to create a new row IN PLACE of a removed row by a negative shift causes corrupted - // xlsx file with unreadable data in the negative shifted row. - // NOTE it's ok to create any other row. - Row newRow = testSheet.createRow(3); - - saveAndReloadReport(wb, xlsOutput); - - Cell newCell = newRow.createCell(0); - - saveAndReloadReport(wb, xlsOutput); - - newCell.setCellValue("new Cell in row " + newRow.getRowNum()); - - saveAndReloadReport(wb, xlsOutput); - - // 3) once a negative shift has been made any attempt to shift another group of rows - // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception: - // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException. - // NOTE: another negative shift on another group of rows is successful, provided no new rows in - // place of previously shifted rows were attempted to be created as explained above. - testSheet.shiftRows(6, 7, 1); // -- CHANGE the shift to positive once the behaviour of - // the above has been tested - - saveAndReloadReport(wb, xlsOutput); - } - - /** - * XSSFCell.typeMismatch on certain blank cells when formatting - * with DataFormatter - */ - @Test - void bug56702() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx")) { - - Sheet sheet = wb.getSheetAt(0); - - // Get wrong cell by row 8 & column 7 - Cell cell = sheet.getRow(8).getCell(7); - assertEquals(CellType.NUMERIC, cell.getCellType()); - - // Check the value - will be zero as it is <c><v/></c> - assertEquals(0.0, cell.getNumericCellValue(), 0.001); - - // Try to format - DataFormatter formatter = new DataFormatter(); - formatter.formatCellValue(cell); - - // Check the formatting - assertEquals("0", formatter.formatCellValue(cell)); - } - } - - /** - * Formulas which reference named ranges, either in other - * sheets, or workbook scoped but in other workbooks. - * Used to fail with with errors like - * org.apache.poi.ss.formula.FormulaParseException: Cell reference expected after sheet name at index 9 - * org.apache.poi.ss.formula.FormulaParseException: Parse error near char 0 '[' in specified formula '[0]!NR_Global_B2'. Expected number, string, or defined name - */ - @Test - void bug56737() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx")) { - - // Check the named range definitions - Name nSheetScope = wb.getName("NR_To_A1"); - Name nWBScope = wb.getName("NR_Global_B2"); - - assertNotNull(nSheetScope); - assertNotNull(nWBScope); - - assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula()); - assertEquals("Defines!$B$2", nWBScope.getRefersToFormula()); - - // Check the different kinds of formulas - Sheet s = wb.getSheetAt(0); - Cell cRefSName = s.getRow(1).getCell(3); - Cell cRefWName = s.getRow(2).getCell(3); - - assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula()); - // Note the formula, as stored in the file, has the external name index not filename - // TODO Provide a way to get the one with the filename - assertEquals("[0]!NR_Global_B2", cRefWName.getCellFormula()); - - // Try to evaluate them - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue()); - assertEquals(142, (int) eval.evaluate(cRefWName).getNumberValue()); - - // Try to evaluate everything - eval.evaluateAll(); - } - } - - private void saveAndReloadReport(Workbook wb, File outFile) throws IOException { - // run some method on the font to verify if it is "disconnected" already - //for(short i = 0;i < 256;i++) - { - Font font = wb.getFontAt(0); - if (font instanceof XSSFFont) { - XSSFFont xfont = (XSSFFont) wb.getFontAt(0); - CTFontImpl ctFont = (CTFontImpl) xfont.getCTFont(); - assertEquals(0, ctFont.sizeOfBArray()); - } - } - - try (FileOutputStream fileOutStream = new FileOutputStream(outFile)) { - wb.write(fileOutStream); - } - - try (FileInputStream is = new FileInputStream(outFile)) { - Workbook newWB = null; - try { - if (wb instanceof XSSFWorkbook) { - newWB = new XSSFWorkbook(is); - } else if (wb instanceof HSSFWorkbook) { - newWB = new HSSFWorkbook(is); - } else if (wb instanceof SXSSFWorkbook) { - newWB = new SXSSFWorkbook(new XSSFWorkbook(is)); - } else { - throw new IllegalStateException("Unknown workbook: " + wb); - } - assertNotNull(newWB.getSheet("test")); - } finally { - if (newWB != null) { - newWB.close(); - } - } - } - } - - @Test - void testBug56688_1() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_1.xlsx"); - checkValue(excel, "-1.0"); /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */ - excel.close(); - } - - @Test - void testBug56688_2() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_2.xlsx"); - checkValue(excel, "#VALUE!"); - excel.close(); - } - - @Test - void testBug56688_3() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_3.xlsx"); - checkValue(excel, "#VALUE!"); - excel.close(); - } - - @Test - void testBug56688_4() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_4.xlsx"); - - Calendar calendar = LocaleUtil.getLocaleCalendar(); - calendar.add(Calendar.MONTH, 2); - double excelDate = DateUtil.getExcelDate(calendar.getTime()); - NumberEval eval = new NumberEval(Math.floor(excelDate)); - checkValue(excel, eval.getStringValue() + ".0"); - - excel.close(); - } - - /** - * New hyperlink with no initial cell reference, still need - * to be able to change it - */ - @Test - void testBug56527() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFCreationHelper creationHelper = wb.getCreationHelper(); - XSSFHyperlink hyperlink; - - // Try with a cell reference - hyperlink = creationHelper.createHyperlink(HyperlinkType.URL); - sheet.addHyperlink(hyperlink); - hyperlink.setAddress("http://myurl"); - hyperlink.setCellReference("B4"); - assertEquals(3, hyperlink.getFirstRow()); - assertEquals(1, hyperlink.getFirstColumn()); - assertEquals(3, hyperlink.getLastRow()); - assertEquals(1, hyperlink.getLastColumn()); - - // Try with explicit rows / columns - hyperlink = creationHelper.createHyperlink(HyperlinkType.URL); - sheet.addHyperlink(hyperlink); - hyperlink.setAddress("http://myurl"); - hyperlink.setFirstRow(5); - hyperlink.setFirstColumn(3); - - assertEquals(5, hyperlink.getFirstRow()); - assertEquals(3, hyperlink.getFirstColumn()); - assertEquals(5, hyperlink.getLastRow()); - assertEquals(3, hyperlink.getLastColumn()); - wb.close(); - } - - /** - * Shifting rows with a formula that references a - * function in another file - */ - @Test - void bug56502() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56502.xlsx")) { - Sheet sheet = wb.getSheetAt(0); - - Cell cFunc = sheet.getRow(3).getCell(0); - assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula()); - Cell cRef = sheet.getRow(3).createCell(1); - cRef.setCellFormula("A3"); - - // Shift it down one row - sheet.shiftRows(1, sheet.getLastRowNum(), 1); - - // Check the new formulas: Function won't change, Reference will - cFunc = sheet.getRow(4).getCell(0); - assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula()); - cRef = sheet.getRow(4).getCell(1); - assertEquals("A4", cRef.getCellFormula()); - } - } - - @Test - void bug54764() throws IOException, OpenXML4JException, XmlException { - try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("54764.xlsx")) { - // Check the core properties - will be found but empty, due - // to the expansion being too much to be considered valid - POIXMLProperties props = new POIXMLProperties(pkg); - assertNull(props.getCoreProperties().getTitle()); - assertNull(props.getCoreProperties().getSubject()); - assertNull(props.getCoreProperties().getDescription()); - - // Now check the spreadsheet itself - assertThrows(POIXMLException.class, () -> new XSSFWorkbook(pkg), "Should fail as too much expansion occurs"); - } - - // Try with one with the entities in the Content Types - assertThrows(Exception.class, () -> XSSFTestDataSamples.openSamplePackage("54764-2.xlsx"), - "Should fail as too much expansion occurs"); - - // Check we can still parse valid files after all that - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) { - assertEquals(3, wb.getNumberOfSheets()); - } - } - - @Test - void test54764WithSAXHelper() throws Exception { - File testFile = XSSFTestDataSamples.getSampleFile("54764.xlsx"); - try (ZipFile zip = new ZipFile(testFile)) { - ZipArchiveEntry ze = zip.getEntry("xl/sharedStrings.xml"); - XMLReader reader = XMLHelper.newXMLReader(); - SAXParseException e = assertThrows(SAXParseException.class, - () -> reader.parse(new InputSource(zip.getInputStream(ze)))); - assertNotNull(e.getMessage()); - assertTrue(e.getMessage().contains("more than \"1\" entity")); - } - } - - @Test - void test54764WithDocumentHelper() throws Exception { - File testFile = XSSFTestDataSamples.getSampleFile("54764.xlsx"); - try (ZipFile zip = new ZipFile(testFile)) { - ZipArchiveEntry ze = zip.getEntry("xl/sharedStrings.xml"); - SAXParseException e = assertThrows(SAXParseException.class, - () -> DocumentHelper.readDocument(zip.getInputStream(ze))); - assertNotNull(e.getMessage()); - assertNotEquals(isOldXercesActive(), e.getMessage().contains("DOCTYPE is disallowed when the feature")); - } - } - - /** - * CTDefinedNamesImpl should be included in the smaller - * poi-ooxml-lite jar - */ - @Test - void bug57176() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57176.xlsx")) { - CTDefinedNames definedNames = wb.getCTWorkbook().getDefinedNames(); - List<CTDefinedName> definedNameList = definedNames.getDefinedNameList(); - for (CTDefinedName defName : definedNameList) { - assertNotNull(defName.getName()); - assertNotNull(defName.getStringValue()); - } - assertEquals("TestDefinedName", definedNameList.get(0).getName()); - } - } - - /** - * .xlsb files are not supported, but we should generate a helpful - * error message if given one - */ - @Test - void bug56800_xlsb() throws IOException { - // Can be opened at the OPC level - try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("Simple.xlsb")) { - // XSSF Workbook gives helpful error - assertThrows(XLSBUnsupportedException.class, () -> new XSSFWorkbook(pkg), ".xlsb files not supported"); - - // Workbook Factory gives helpful error on package - assertThrows(XLSBUnsupportedException.class, () -> XSSFWorkbookFactory.createWorkbook(pkg), ".xlsb files not supported"); - } - - // Workbook Factory gives helpful error on file - File xlsbFile = HSSFTestDataSamples.getSampleFile("Simple.xlsb"); - assertThrows(XLSBUnsupportedException.class, () -> WorkbookFactory.create(xlsbFile), ".xlsb files not supported"); - } - - private void checkValue(XSSFWorkbook excel, String expect) { - XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel); - evaluator.evaluateAll(); - - XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1); - CellValue value = evaluator.evaluate(cell); - - assertEquals(expect, value.formatAsString()); - } - - @Test - void testBug57196() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57196.xlsx")) { - Sheet sheet = wb.getSheet("Feuil1"); - Row mod = sheet.getRow(1); - mod.getCell(1).setCellValue(3); - mod = sheet.getRow(2); - mod.createCell(0).setCellValue(10); - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - assertEquals(256, mod.getCell(2).getNumericCellValue()); - } - } - - @Test - void test57196_Detail() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("Sheet1"); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)"); - XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb); - CellValue cv = fe.evaluate(cell); - - assertNotNull(cv); - wb.close(); - } - - @Test - void test57196_Detail2() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("Sheet1"); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellFormula("DEC2HEX(O2+D2)"); - XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb); - CellValue cv = fe.evaluate(cell); - - assertNotNull(cv); - wb.close(); - } - - @ParameterizedTest - @CsvSource({ - // simple formula worked - "DEC2HEX(O2+D2), org.apache.poi.ss.formula.eval.StringEval [0]", - // this already failed! Hex2Dec did not correctly handle RefEval - "HEX2DEC(O8), org.apache.poi.ss.formula.eval.NumberEval [0]", - // slightly more complex one failed - "HEX2DEC(O8)-O2+D2, org.apache.poi.ss.formula.eval.NumberEval [0]", - // more complicated failed - "DEC2HEX(HEX2DEC(O8)-O2+D2), org.apache.poi.ss.formula.eval.StringEval [0]", - // what other similar functions - "DEC2BIN(O8)-O2+D2, org.apache.poi.ss.formula.eval.ErrorEval [#VALUE!]", - // what other similar functions - "DEC2BIN(A1), org.apache.poi.ss.formula.eval.StringEval [0]" - }) - void test57196_WorkbookEvaluator(String formula, String expValue) throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet("Sheet1"); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellValue("0"); - cell = row.createCell(1); - cell.setCellValue(0); - cell = row.createCell(2); - cell.setCellValue(0); - - cell.setCellFormula(formula); - - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null); - workbookEvaluator.setDebugEvaluationOutputForNextEval(true); - ValueEval ve = workbookEvaluator.evaluate(new XSSFEvaluationCell(cell)); - - assertEquals(expValue, ve.toString()); - } - } - - /** - * A .xlsx file with no Shared Strings table should open fine - * in read-only mode - */ - @ParameterizedTest - @EnumSource(value = PackageAccess.class, names = {"READ_WRITE", "READ"}) - void bug57482(PackageAccess access) throws IOException, InvalidFormatException { - File file = HSSFTestDataSamples.getSampleFile("57482-OnlyNumeric.xlsx"); - try (OPCPackage pkg = OPCPackage.open(file, access); - XSSFWorkbook wb1 = new XSSFWorkbook(pkg)) { - // Try to open it and read the contents - - assertNotNull(wb1.getSharedStringSource()); - assertEquals(0, wb1.getSharedStringSource().getCount()); - - DataFormatter fmt = new DataFormatter(); - XSSFSheet s = wb1.getSheetAt(0); - assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0))); - assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1))); - assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0))); - - // Add a text cell - s.getRow(0).createCell(3).setCellValue("Testing"); - assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3))); - - // Try to write-out and read again, should only work - // in read-write mode, not read-only mode - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { - if (access == PackageAccess.READ) { - fail("Shouln't be able to write from read-only mode"); - } - - // Check again - s = wb2.getSheetAt(0); - assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0))); - assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1))); - assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0))); - assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3))); - - wb2.getPackage().revert(); - } catch (InvalidOperationException e) { - if (access == PackageAccess.READ_WRITE) { - // Shouldn't occur in write-mode - throw e; - } - } - - pkg.revert(); - } - } - - /** - * "Unknown error type: -60" fetching formula error value - */ - @Test - void bug57535() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57535.xlsx")) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - evaluator.clearAllCachedResultValues(); - - Sheet sheet = wb.getSheet("Sheet1"); - Cell cell = sheet.getRow(5).getCell(4); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("E4+E5", cell.getCellFormula()); - - CellValue value = evaluator.evaluate(cell); - assertEquals(CellType.ERROR, value.getCellType()); - assertEquals(-60, value.getErrorValue()); - assertEquals("~CIRCULAR~REF~", FormulaError.forInt(value.getErrorValue()).getString()); - assertEquals("CIRCULAR_REF", FormulaError.forInt(value.getErrorValue()).toString()); - } - } - - - @Test - void test57165() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx")) { - removeAllSheetsBut(3, wb); - // Throws exception here - assertDoesNotThrow(() -> wb.cloneSheet(0)); - wb.setSheetName(1, "New Sheet"); - - try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { - assertNotNull(wbBack.getSheet("New Sheet")); - } - } - } - - @Test - void test57165_create() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx")) { - removeAllSheetsBut(3, wb); - // Throws exception here - assertDoesNotThrow(() -> wb.createSheet("newsheet")); - wb.setSheetName(1, "New Sheet"); - - try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { - assertNotNull(wbBack.getSheet("New Sheet")); - } - } - } - - private static void removeAllSheetsBut(@SuppressWarnings("SameParameterValue") int sheetIndex, Workbook wb) { - int sheetNb = wb.getNumberOfSheets(); - // Move this sheet at the first position - wb.setSheetOrder(wb.getSheetName(sheetIndex), 0); - for (int sn = sheetNb - 1; sn > 0; sn--) { - wb.removeSheetAt(sn); - } - } - - /** - * Sums 2 plus the cell at the left, indirectly to avoid reference - * problems when deleting columns, conditionally to stop recursion - */ - private static final String FORMULA1 = - "IF( INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) = 0, 0, " - + "INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) ) + 2"; - - /** - * Sums 2 plus the upper cell, indirectly to avoid reference - * problems when deleting rows, conditionally to stop recursion - */ - private static final String FORMULA2 = - "IF( INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) = 0, 0, " - + "INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) ) + 2"; - - /** - * Expected: - * <p> - * [ 0][ 2][ 4] - */ - @Test - void testBug56820_Formula1() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet sh = wb.createSheet(); - - sh.createRow(0).createCell(0).setCellValue(0.0d); - Cell formulaCell1 = sh.getRow(0).createCell(1); - Cell formulaCell2 = sh.getRow(0).createCell(2); - formulaCell1.setCellFormula(FORMULA1); - formulaCell2.setCellFormula(FORMULA1); - - double A1 = evaluator.evaluate(formulaCell1).getNumberValue(); - double A2 = evaluator.evaluate(formulaCell2).getNumberValue(); - - assertEquals(2, A1, 0); - assertEquals(4, A2, 0); //<-- FAILS EXPECTATIONS - } - } - - /** - * Expected: - * <p> - * [ 0] <- number - * [ 2] <- formula - * [ 4] <- formula - */ - @Test - void testBug56820_Formula2() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet sh = wb.createSheet(); - - sh.createRow(0).createCell(0).setCellValue(0.0d); - Cell formulaCell1 = sh.createRow(1).createCell(0); - Cell formulaCell2 = sh.createRow(2).createCell(0); - formulaCell1.setCellFormula(FORMULA2); - formulaCell2.setCellFormula(FORMULA2); - - double A1 = evaluator.evaluate(formulaCell1).getNumberValue(); - double A2 = evaluator.evaluate(formulaCell2).getNumberValue(); //<-- FAILS EVALUATION - - assertEquals(2, A1, 0); - assertEquals(4, A2, 0); - } - } - - @Test - void test56467() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("picture.xlsx")) { - Sheet orig = wb.getSheetAt(0); - assertNotNull(orig); - - Sheet sheet = wb.cloneSheet(0); - Drawing<?> drawing = sheet.createDrawingPatriarch(); - for (XSSFShape shape : ((XSSFDrawing) drawing).getShapes()) { - if (shape instanceof XSSFPicture) { - XSSFPictureData pictureData = ((XSSFPicture) shape).getPictureData(); - assertNotNull(pictureData); - } - } - - } - } - - /** - * OOXML-Strict files - * Not currently working - namespace mis-match from XMLBeans - */ - @Test - @Disabled("XMLBeans namespace mis-match on ooxml-strict files") - void test57699() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.strict.xlsx")) { - assertEquals(3, wb.getNumberOfSheets()); - // TODO Check sheet contents - // TODO Check formula evaluation - - try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { - assertEquals(3, wbBack.getNumberOfSheets()); - // TODO Re-check sheet contents - // TODO Re-check formula evaluation - } - } - } - - @Test - void testBug56295_MergeXlslsWithStyles() throws IOException { - XSSFWorkbook xlsToAppendWorkbook = XSSFTestDataSamples.openSampleWorkbook("56295.xlsx"); - XSSFSheet sheet = xlsToAppendWorkbook.getSheetAt(0); - XSSFRow srcRow = sheet.getRow(0); - XSSFCell oldCell = srcRow.getCell(0); - XSSFCellStyle cellStyle = oldCell.getCellStyle(); - - checkStyle(cellStyle); - -// StylesTable table = xlsToAppendWorkbook.getStylesSource(); -// List<XSSFCellFill> fills = table.getFills(); -// System.out.println("Having " + fills.size() + " fills"); -// for(XSSFCellFill fill : fills) { -// System.out.println("Fill: " + fill.getFillBackgroundColor() + "/" + fill.getFillForegroundColor()); -// } - xlsToAppendWorkbook.close(); - - XSSFWorkbook targetWorkbook = new XSSFWorkbook(); - XSSFSheet newSheet = targetWorkbook.createSheet(sheet.getSheetName()); - XSSFRow destRow = newSheet.createRow(0); - XSSFCell newCell = destRow.createCell(0); - - //newCell.getCellStyle().cloneStyleFrom(cellStyle); - CellStyle newCellStyle = targetWorkbook.createCellStyle(); - newCellStyle.cloneStyleFrom(cellStyle); - newCell.setCellStyle(newCellStyle); - checkStyle(newCell.getCellStyle()); - newCell.setCellValue(oldCell.getStringCellValue()); - -// OutputStream os = new FileOutputStream("output.xlsm"); -// try { -// targetWorkbook.write(os); -// } finally { -// os.close(); -// } - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(targetWorkbook); - XSSFCellStyle styleBack = wbBack.getSheetAt(0).getRow(0).getCell(0).getCellStyle(); - checkStyle(styleBack); - - targetWorkbook.close(); - wbBack.close(); - } - - /** - * Paragraph with property BuFont but none of the properties - * BuNone, BuChar, and BuAutoNum, used to trigger a NPE - * Excel treats this as not-bulleted, so now do we - */ - @Test - void testBug57826() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57826.xlsx"); - - assertTrue(workbook.getNumberOfSheets() >= 1, "no sheets in workbook"); - XSSFSheet sheet = workbook.getSheetAt(0); - - XSSFDrawing drawing = sheet.getDrawingPatriarch(); - assertNotNull(drawing); - - List<XSSFShape> shapes = drawing.getShapes(); - assertEquals(1, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - - XSSFSimpleShape shape = (XSSFSimpleShape) shapes.get(0); - - // Used to throw a NPE - String text = shape.getText(); - - // No bulleting info included - assertEquals("test ok", text); - - workbook.close(); - } - - private void checkStyle(XSSFCellStyle cellStyle) { - assertNotNull(cellStyle); - assertEquals(0, cellStyle.getFillForegroundColor()); - assertNotNull(cellStyle.getFillForegroundXSSFColor()); - XSSFColor fgColor = cellStyle.getFillForegroundColorColor(); - assertNotNull(fgColor); - assertEquals("FF00FFFF", fgColor.getARGBHex()); - - assertEquals(0, cellStyle.getFillBackgroundColor()); - assertNotNull(cellStyle.getFillBackgroundXSSFColor()); - XSSFColor bgColor = cellStyle.getFillBackgroundColorColor(); - assertNotNull(bgColor); - assertEquals("FF00FFFF", fgColor.getARGBHex()); - } - - @Test - void bug57642() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet s = wb.createSheet("TestSheet"); - XSSFCell c = s.createRow(0).createCell(0); - c.setCellFormula("ISERROR(TestSheet!A1)"); - c = s.createRow(1).createCell(1); - c.setCellFormula("ISERROR(B2)"); - - wb.setSheetName(0, "CSN"); - c = s.getRow(0).getCell(0); - assertEquals("ISERROR(CSN!A1)", c.getCellFormula()); - c = s.getRow(1).getCell(1); - assertEquals("ISERROR(B2)", c.getCellFormula()); - - wb.close(); - } - - /** - * .xlsx supports 64000 cell styles, the style indexes after - * 32,767 must not be -32,768, then -32,767, -32,766 - */ - @Test - void bug57880() throws IOException { - int numStyles = 33000; - XSSFWorkbook wb = new XSSFWorkbook(); - for (int i = 1; i < numStyles; i++) { - // Create a style and use it - XSSFCellStyle style = wb.createCellStyle(); - assertEquals(i, style.getUIndex()); - } - assertEquals(numStyles, wb.getNumCellStyles()); - - // avoid OOM in Gump run - File file = XSSFTestDataSamples.writeOutAndClose(wb, "bug57880"); - //noinspection UnusedAssignment - wb = null; - // Garbage collection may happen here - - // avoid zip bomb detection - double ratio = ZipSecureFile.getMinInflateRatio(); - ZipSecureFile.setMinInflateRatio(0.00005); - wb = XSSFTestDataSamples.readBackAndDelete(file); - ZipSecureFile.setMinInflateRatio(ratio); - - //Assume identical cell styles aren't consolidated - //If XSSFWorkbooks ever implicitly optimize/consolidate cell styles (such as when the workbook is written to disk) - //then this unit test should be updated - assertEquals(numStyles, wb.getNumCellStyles()); - for (int i = 1; i < numStyles; i++) { - XSSFCellStyle style = wb.getCellStyleAt(i); - assertNotNull(style); - assertEquals(i, style.getUIndex()); - } - wb.close(); - } - - - @Test - void test56574() throws IOException { - runTest56574(false); - runTest56574(true); - } - - private void runTest56574(boolean createRow) throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56574.xlsx")) { - - Sheet sheet = wb.getSheet("Func"); - assertNotNull(sheet); - - Map<String, Object[]> data; - data = new TreeMap<>(); - data.put("1", new Object[]{"ID", "NAME", "LASTNAME"}); - data.put("2", new Object[]{2, "Amit", "Shukla"}); - data.put("3", new Object[]{1, "Lokesh", "Gupta"}); - data.put("4", new Object[]{4, "John", "Adwards"}); - data.put("5", new Object[]{2, "Brian", "Schultz"}); - - int rownum = 1; - for (Map.Entry<String, Object[]> me : data.entrySet()) { - final Row row; - if (createRow) { - row = sheet.createRow(rownum++); - } else { - row = sheet.getRow(rownum++); - } - assertNotNull(row); - - int cellnum = 0; - for (Object obj : me.getValue()) { - Cell cell = row.getCell(cellnum); - if (cell == null) { - cell = row.createCell(cellnum); - } else { - if (cell.getCellType() == CellType.FORMULA) { - cell.setCellFormula(null); - cell.getCellStyle().setDataFormat((short) 0); - } - } - if (obj instanceof String) { - cell.setCellValue((String) obj); - } else if (obj instanceof Integer) { - cell.setCellValue((Integer) obj); - } - cellnum++; - } - } - - XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - CalculationChain chain = wb.getCalculationChain(); - checkCellsAreGone(chain); - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - Sheet sheetBack = wbBack.getSheet("Func"); - assertNotNull(sheetBack); - - chain = wbBack.getCalculationChain(); - checkCellsAreGone(chain); - - wbBack.close(); - } - } - - private void checkCellsAreGone(CalculationChain chain) { - for (CTCalcCell calc : chain.getCTCalcChain().getCList()) { - // A2 to A6 should be gone - assertNotEquals("A2", calc.getR()); - assertNotEquals("A3", calc.getR()); - assertNotEquals("A4", calc.getR()); - assertNotEquals("A5", calc.getR()); - assertNotEquals("A6", calc.getR()); - } - } - - /** - * Excel 2007 generated Macro-Enabled .xlsm file - */ - @Test - void bug57181() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57181.xlsm")) { - assertEquals(9, wb.getNumberOfSheets()); - } - } - - @Test - void bug52111() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("Intersection-52111-xssf.xlsx")) { - Sheet s = wb.getSheetAt(0); - assertFormula(wb, s.getRow(2).getCell(0), "(C2:D3 D3:E4)", "4.0"); - assertFormula(wb, s.getRow(6).getCell(0), "Tabelle2!E:E Tabelle2!11:11", "5.0"); - assertFormula(wb, s.getRow(8).getCell(0), "Tabelle2!E:F Tabelle2!11:12", null); - } - } - - @Test - void test48962() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48962.xlsx")) { - Sheet sh = wb.getSheetAt(0); - Row row = sh.getRow(1); - Cell cell = row.getCell(0); - - CellStyle style = cell.getCellStyle(); - assertNotNull(style); - - // color index - assertEquals(64, style.getFillBackgroundColor()); - XSSFColor color = ((XSSFCellStyle) style).getFillBackgroundXSSFColor(); - assertNotNull(color); - - // indexed color - assertEquals(64, color.getIndexed()); - assertEquals(64, color.getIndex()); - - // not an RGB color - assertFalse(color.isRGB()); - assertNull(color.getRGB()); - } - } - - @Test - void test50755_workday_formula_example() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50755_workday_formula_example.xlsx")) { - Sheet sheet = wb.getSheet("Sheet1"); - for (Row aRow : sheet) { - Cell cell = aRow.getCell(1); - if (cell.getCellType() == CellType.FORMULA) { - String formula = cell.getCellFormula(); - assertNotNull(formula); - assertTrue(formula.contains("WORKDAY")); - } else { - assertNotNull(cell.toString()); - } - } - } - } - - @Test - void test51626() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51626.xlsx"); - assertNotNull(wb); - wb.close(); - - InputStream stream = HSSFTestDataSamples.openSampleFileStream("51626.xlsx"); - wb = WorkbookFactory.create(stream); - stream.close(); - wb.close(); - - wb = XSSFTestDataSamples.openSampleWorkbook("51626_contact.xlsx"); - assertNotNull(wb); - wb.close(); - - stream = HSSFTestDataSamples.openSampleFileStream("51626_contact.xlsx"); - wb = WorkbookFactory.create(stream); - stream.close(); - wb.close(); - } - - @Disabled("this test is only for manual verification, as we can't test if the cell is visible in Excel") - void test51451() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - Sheet sh = wb.createSheet(); - - Row row = sh.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(239827342); - - CellStyle style = wb.createCellStyle(); - //style.setHidden(false); - DataFormat excelFormat = wb.createDataFormat(); - style.setDataFormat(excelFormat.getFormat("#,##0")); - sh.setDefaultColumnStyle(0, style); - } - } - - @Test - void test53105() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53105.xlsx")) { - assertNotNull(wb); - - - // Act - // evaluate SUM('Skye Lookup Input'!A4:XFD4), cells in range each contain "1" - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - double numericValue = evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(0)).getNumberValue(); - - // Assert - assertEquals(16384.0, numericValue, 0.0); - } - } - - - @Test - void test58315() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58315.xlsx")) { - Cell cell = wb.getSheetAt(0).getRow(0).getCell(0); - assertNotNull(cell); - StringBuilder tmpCellContent = new StringBuilder(cell.getStringCellValue()); - XSSFRichTextString richText = (XSSFRichTextString) cell.getRichStringCellValue(); - - for (int i = richText.length() - 1; i >= 0; i--) { - Font f = richText.getFontAtIndex(i); - if (f != null && f.getStrikeout()) { - tmpCellContent.deleteCharAt(i); - } - } - String result = tmpCellContent.toString(); - assertEquals("320 350", result); - } - } - - @Test - void test55406() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55406_Conditional_formatting_sample.xlsx")) { - Sheet sheet = wb.getSheetAt(0); - Cell cellA1 = sheet.getRow(0).getCell(0); - Cell cellA2 = sheet.getRow(1).getCell(0); - - assertEquals(0, cellA1.getCellStyle().getFillForegroundColor()); - assertEquals("FFFDFDFD", ((XSSFColor) cellA1.getCellStyle().getFillForegroundColorColor()).getARGBHex()); - assertEquals(0, cellA2.getCellStyle().getFillForegroundColor()); - assertEquals("FFFDFDFD", ((XSSFColor) cellA2.getCellStyle().getFillForegroundColorColor()).getARGBHex()); - - SheetConditionalFormatting cond = sheet.getSheetConditionalFormatting(); - assertEquals(2, cond.getNumConditionalFormattings()); - - assertEquals(1, cond.getConditionalFormattingAt(0).getNumberOfRules()); - assertEquals(64, cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColor()); - assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(0).getRule(0).getFormula1()); - assertNull(((XSSFColor) cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex()); - - assertEquals(1, cond.getConditionalFormattingAt(1).getNumberOfRules()); - assertEquals(64, cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColor()); - assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(1).getRule(0).getFormula1()); - assertNull(((XSSFColor) cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex()); - } - } - - @Test - void test51998() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51998.xlsx"); - - Set<String> sheetNames = new HashSet<>(); - - for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) { - sheetNames.add(wb.getSheetName(sheetNum)); - } - - for (String sheetName : sheetNames) { - int sheetIndex = wb.getSheetIndex(sheetName); - - wb.removeSheetAt(sheetIndex); - - Sheet newSheet = wb.createSheet(); - //Sheet newSheet = wb.createSheet(sheetName); - int newSheetIndex = wb.getSheetIndex(newSheet); - wb.setSheetName(newSheetIndex, sheetName); - wb.setSheetOrder(sheetName, sheetIndex); - } - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - - assertNotNull(wbBack); - wbBack.close(); - } - - @Test - void test58731() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58731.xlsx")) { - Sheet sheet = wb.createSheet("Java Books"); - - Object[][] bookData = { - {"Head First Java", "Kathy Serria", 79}, - {"Effective Java", "Joshua Bloch", 36}, - {"Clean Code", "Robert martin", 42}, - {"Thinking in Java", "Bruce Eckel", 35}, - }; - - int rowCount = 0; - for (Object[] aBook : bookData) { - Row row = sheet.createRow(rowCount++); - - int columnCount = 0; - for (Object field : aBook) { - Cell cell = row.createCell(columnCount++); - if (field instanceof String) { - cell.setCellValue((String) field); - } else if (field instanceof Integer) { - cell.setCellValue((Integer) field); - } - } - } - - try (Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) { - sheet = wb2.getSheet("Java Books"); - assertNotNull(sheet.getRow(0)); - assertNotNull(sheet.getRow(0).getCell(0)); - assertEquals(bookData[0][0], sheet.getRow(0).getCell(0).getStringCellValue()); - } - } - } - - /** - * Regression between 3.10.1 and 3.13 - - * org.apache.poi.openxml4j.exceptions.InvalidFormatException: - * The part /xl/sharedStrings.xml does not have any content type - * ! Rule: Package require content types when retrieving a part from a package. [M.1.14] - */ - @Test - void test58760() throws IOException { - Workbook wb1 = XSSFTestDataSamples.openSampleWorkbook("58760.xlsx"); - assertEquals(1, wb1.getNumberOfSheets()); - assertEquals("Sheet1", wb1.getSheetName(0)); - Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals(1, wb2.getNumberOfSheets()); - assertEquals("Sheet1", wb2.getSheetName(0)); - wb2.close(); - wb1.close(); - } - - @Test - void test57236() throws IOException { - // Having very small numbers leads to different formatting, Excel uses the scientific notation, but POI leads to "0" - - /* - DecimalFormat format = new DecimalFormat("#.##########", new DecimalFormatSymbols(Locale.getDefault())); - double d = 3.0E-104; - assertEquals("3.0E-104", format.format(d)); - */ - - DataFormatter formatter = new DataFormatter(true); - - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57236.xlsx")) { - for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) { - Sheet sheet = wb.getSheetAt(sheetNum); - for (int rowNum = sheet.getFirstRowNum(); rowNum < sheet.getLastRowNum(); rowNum++) { - Row row = sheet.getRow(rowNum); - for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) { - Cell cell = row.getCell(cellNum); - String fmtCellValue = formatter.formatCellValue(cell); - assertNotNull(fmtCellValue); - assertNotEquals("0", fmtCellValue); - } - } - } - } - } - - /** - * helper function for {@link #test58043()} - * Side-effects: closes the provided workbook! - * - * @param workbook the workbook to save for manual checking - * @param outputFile the output file location to save the workbook to - */ - private void saveRotatedTextExample(Workbook workbook, File outputFile) throws IOException { - Sheet sheet = workbook.createSheet(); - Row row = sheet.createRow((short) 0); - - Cell cell = row.createCell(0); - - cell.setCellValue("Unsuccessful rotated text."); - - CellStyle style = workbook.createCellStyle(); - style.setRotation((short) -90); - - cell.setCellStyle(style); - - OutputStream fos = new FileOutputStream(outputFile); - workbook.write(fos); - fos.close(); - workbook.close(); - } - - @Disabled("Creates files for checking results manually, actual values are tested in Test*CellStyle") - void test58043() throws IOException { - saveRotatedTextExample(new HSSFWorkbook(), TempFile.createTempFile("rotated", ".xls")); - saveRotatedTextExample(new XSSFWorkbook(), TempFile.createTempFile("rotated", ".xlsx")); - } - - @Test - void test59132() throws IOException { - try (Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("59132.xlsx")) { - Sheet worksheet = workbook.getSheet("sheet1"); - - // B3 - Row row = worksheet.getRow(2); - Cell cell = row.getCell(1); - - cell.setCellValue((String) null); - - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - - // B3 - row = worksheet.getRow(2); - cell = row.getCell(1); - - assertEquals(CellType.BLANK, cell.getCellType()); - assertEquals(CellType._NONE, evaluator.evaluateFormulaCell(cell)); - - // A3 - row = worksheet.getRow(2); - cell = row.getCell(0); - - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("IF(ISBLANK(B3),\"\",B3)", cell.getCellFormula()); - assertEquals(CellType.STRING, evaluator.evaluateFormulaCell(cell)); - CellValue value = evaluator.evaluate(cell); - assertEquals("", value.getStringValue()); - - // A5 - row = worksheet.getRow(4); - cell = row.getCell(0); - - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("COUNTBLANK(A1:A4)", cell.getCellFormula()); - assertEquals(CellType.NUMERIC, evaluator.evaluateFormulaCell(cell)); - value = evaluator.evaluate(cell); - assertEquals(1.0, value.getNumberValue(), 0.1); - } - } - - @Disabled("bug 59442") - @Test - void testSetRGBBackgroundColor() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFCell cell = workbook.createSheet().createRow(0).createCell(0); - - XSSFColor color = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors()); - XSSFCellStyle style = workbook.createCellStyle(); - style.setFillForegroundColor(color); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cell.setCellStyle(style); - - // Everything is fine at this point, cell is red - XSSFColor actual = cell.getCellStyle().getFillBackgroundColorColor(); - assertNull(actual); - actual = cell.getCellStyle().getFillForegroundColorColor(); - assertNotNull(actual); - assertEquals(color.getARGBHex(), actual.getARGBHex()); - - Map<String, Object> properties = new HashMap<>(); - properties.put(CellUtil.BORDER_BOTTOM, BorderStyle.THIN); - CellUtil.setCellStyleProperties(cell, properties); - - // Now the cell is all black - actual = cell.getCellStyle().getFillBackgroundColorColor(); - assertNotNull(actual); - assertNull(actual.getARGBHex()); - actual = cell.getCellStyle().getFillForegroundColorColor(); - assertNotNull(actual); - assertEquals(color.getARGBHex(), actual.getARGBHex()); - - XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(workbook); - workbook.close(); - XSSFCell ncell = nwb.getSheetAt(0).getRow(0).getCell(0); - XSSFColor ncolor = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors()); - - // Now the cell is all black - XSSFColor nactual = ncell.getCellStyle().getFillBackgroundColorColor(); - assertNotNull(nactual); - assertEquals(ncolor.getARGBHex(), nactual.getARGBHex()); - - nwb.close(); - } - - @Disabled("currently fails on POI 3.15 beta 2") - @Test - void test55273() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("ExcelTables.xlsx")) { - Sheet sheet = wb.getSheet("ExcelTable"); - - Name name = wb.getName("TableAsRangeName"); - assertEquals("TableName[#All]", name.getRefersToFormula()); - // POI 3.15-beta 2 (2016-06-15): getSheetName throws IllegalArgumentException: Invalid CellReference: TableName[#All] - assertEquals("TableName", name.getSheetName()); - - XSSFSheet xsheet = (XSSFSheet) sheet; - List<XSSFTable> tables = xsheet.getTables(); - assertEquals(2, tables.size()); //FIXME: how many tables are there in this spreadsheet? - assertEquals("Table1", tables.get(0).getName()); //FIXME: what is the table name? - assertEquals("Table2", tables.get(1).getName()); //FIXME: what is the table name? - } - } - - @Test - void test57523() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57523.xlsx")) { - Sheet sheet = wb.getSheet("Attribute Master"); - Row row = sheet.getRow(15); - - int N = CellReference.convertColStringToIndex("N"); - Cell N16 = row.getCell(N); - assertEquals(500.0, N16.getNumericCellValue(), 0.00001); - - int P = CellReference.convertColStringToIndex("P"); - Cell P16 = row.getCell(P); - assertEquals(10.0, P16.getNumericCellValue(), 0.00001); - } - } - - /** - * Files produced by some scientific equipment neglect - * to include the row number on the row tags - */ - @Test - void noRowNumbers59746() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("59746_NoRowNums.xlsx")) { - Sheet sheet = wb.getSheetAt(0); - assertTrue(sheet.getLastRowNum() > 20, "Last row num: " + sheet.getLastRowNum()); - assertEquals("Checked", sheet.getRow(0).getCell(0).getStringCellValue()); - assertEquals("Checked", sheet.getRow(9).getCell(2).getStringCellValue()); - assertFalse(sheet.getRow(70).getCell(8).getBooleanCellValue()); - assertEquals(71, sheet.getPhysicalNumberOfRows()); - assertEquals(70, sheet.getLastRowNum()); - assertEquals(70, sheet.getRow(sheet.getLastRowNum()).getRowNum()); - } - } - - @Test - void testWorkdayFunction() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("59106.xlsx")) { - XSSFSheet sheet = workbook.getSheet("Test"); - Row row = sheet.getRow(1); - Cell cell = row.getCell(0); - DataFormatter form = new DataFormatter(); - FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - String result = form.formatCellValue(cell, evaluator); - - assertEquals("09 Mar 2016", result); - } - } - - // This bug is currently open. When this bug is fixed, it should not throw an AssertionError - @Test - void test55076_collapseColumnGroups() throws Exception { - try (Workbook wb = new XSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - - // this column collapsing bug only occurs when the grouped columns are different widths - sheet.setColumnWidth(1, 400); - sheet.setColumnWidth(2, 600); - sheet.setColumnWidth(3, 800); - - assertEquals(400, sheet.getColumnWidth(1)); - assertEquals(600, sheet.getColumnWidth(2)); - assertEquals(800, sheet.getColumnWidth(3)); - - sheet.groupColumn(1, 3); - sheet.setColumnGroupCollapsed(1, true); - - assertEquals(0, sheet.getColumnOutlineLevel(0)); - assertEquals(1, sheet.getColumnOutlineLevel(1)); - assertEquals(1, sheet.getColumnOutlineLevel(2)); - assertEquals(1, sheet.getColumnOutlineLevel(3)); - assertEquals(0, sheet.getColumnOutlineLevel(4)); - - // none of the columns should be hidden - // column group collapsing is a different concept - for (int c = 0; c < 5; c++) { - // if this fails for c == 1 in the future, then the implementation will be correct - // and we need to adapt this test accordingly - assertEquals(c == 1, sheet.isColumnHidden(c), "Column " + c); - } - - assertEquals(400, sheet.getColumnWidth(1)); - // 600 is the correct value! ... 2048 is just for pacifying the test (see above comment) - assertEquals(2048, sheet.getColumnWidth(2)); - assertEquals(800, sheet.getColumnWidth(3)); - - } - } - - /** - * Other things, including charts, may end up taking drawing part - * numbers. (Uses a test file hand-crafted with an extra non-drawing - * part with a part number) - */ - @Test - void drawingNumbersAlreadyTaken_60255() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("60255_extra_drawingparts.xlsx")) { - assertEquals(4, wb.getNumberOfSheets()); - - // Sheet 3 starts with a drawing - Sheet sheet = wb.getSheetAt(0); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(1); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(2); - assertNotNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(3); - assertNull(sheet.getDrawingPatriarch()); - - // Add another sheet, and give it a drawing - sheet = wb.createSheet(); - assertNull(sheet.getDrawingPatriarch()); - sheet.createDrawingPatriarch(); - assertNotNull(sheet.getDrawingPatriarch()); - - // Save and check - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(5, wbBack.getNumberOfSheets()); - - // Sheets 3 and 5 now - sheet = wbBack.getSheetAt(0); - assertNull(sheet.getDrawingPatriarch()); - sheet = wbBack.getSheetAt(1); - assertNull(sheet.getDrawingPatriarch()); - sheet = wbBack.getSheetAt(2); - assertNotNull(sheet.getDrawingPatriarch()); - sheet = wbBack.getSheetAt(3); - assertNull(sheet.getDrawingPatriarch()); - sheet = wbBack.getSheetAt(4); - assertNotNull(sheet.getDrawingPatriarch()); - } - } - - @Test - void test53611() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(1); - Cell cell = row.createCell(1); - cell.setCellValue("blabla"); - - //0 1 2 3 4 5 6 7 - //A B C D E F G H - row = sheet.createRow(4); - cell = row.createCell(7); - cell.setCellValue("blabla"); - - // we currently only populate the dimension during writing out - // to avoid having to iterate all rows/cells in each add/remove of a row or cell - wb.write(new NullOutputStream()); - - assertEquals("B2:H5", ((XSSFSheet) sheet).getCTWorksheet().getDimension().getRef()); - - wb.close(); - } - - @Test - void test61798() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(1); - Cell cell = row.createCell(1); - cell.setCellValue("blabla"); - - row = sheet.createRow(4); - // Allowable column range for EXCEL2007 is (0..16383) or ('A'..'XDF') - cell = row.createCell(16383); - cell.setCellValue("blabla"); - - // we currently only populate the dimension during writing out - // to avoid having to iterate all rows/cells in each add/remove of a row or cell - wb.write(new NullOutputStream()); - - assertEquals("B2:XFD5", ((XSSFSheet)sheet).getCTWorksheet().getDimension().getRef()); - - wb.close(); - } - - @Test - void bug61063() throws Exception { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61063.xlsx")) { - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - Sheet s = wb.getSheetAt(0); - - Row r = s.getRow(3); - Cell c = r.getCell(0); - assertEquals(CellType.FORMULA, c.getCellType()); - eval.setDebugEvaluationOutputForNextEval(true); - CellValue cv = eval.evaluate(c); - assertNotNull(cv); - assertEquals(2.0, cv.getNumberValue(), 0.00001, "Had: " + cv); - } - } - - @Test - void bug61516() throws IOException { - final String initialFormula = "A1"; - final String expectedFormula = "#REF!"; // from ms excel - - XSSFWorkbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet1"); - sheet.createRow(0).createCell(0).setCellValue(1); // A1 = 1 - - { - Cell c3 = sheet.createRow(2).createCell(2); - c3.setCellFormula(initialFormula); // C3 = =A1 - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cellValue = evaluator.evaluate(c3); - assertEquals(1, cellValue.getNumberValue(), 0.0001); - } - - { - FormulaShifter formulaShifter = FormulaShifter.createForRowCopy(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/ - , -1/*step*/, SpreadsheetVersion.EXCEL2007); // parameters 2, 2, -1 should mean : move row range [2-2] one level up - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1] - formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A] - String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A - //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla)); - assertEquals(expectedFormula, shiftedFmla, - "On copy we expect the formula to be adjusted, in this case it would point to row -1, which is an invalid REF"); - } - - { - FormulaShifter formulaShifter = FormulaShifter.createForRowShift(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/ - , -1/*step*/, SpreadsheetVersion.EXCEL2007); // parameters 2, 2, -1 should mean : move row range [2-2] one level up - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1] - formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A] - String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A - //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla)); - assertEquals(initialFormula, shiftedFmla, - "On move we expect the formula to stay the same, thus expecting the initial formula A1 here"); - } - - sheet.shiftRows(2, 2, -1); - { - Cell c2 = sheet.getRow(1).getCell(2); - assertNotNull(c2, "cell C2 needs to exist now"); - assertEquals(CellType.FORMULA, c2.getCellType()); - assertEquals(initialFormula, c2.getCellFormula()); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cellValue = evaluator.evaluate(c2); - assertEquals(1, cellValue.getNumberValue(), 0.0001); - } - - wb.close(); - } - - @Test - void test61652() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61652.xlsx")) { - Sheet sheet = wb.getSheet("IRPPCalc"); - Row row = sheet.getRow(11); - Cell cell = row.getCell(18); - WorkbookEvaluatorProvider fe = (WorkbookEvaluatorProvider) wb.getCreationHelper().createFormulaEvaluator(); - ConditionalFormattingEvaluator condfmt = new ConditionalFormattingEvaluator(wb, fe); - - assertEquals("[]", condfmt.getConditionalFormattingForCell(cell).toString(), - "Conditional formatting is not triggered for this cell"); - - // but we can read the conditional formatting itself - List<EvaluationConditionalFormatRule> rules = condfmt.getFormatRulesForSheet(sheet); - assertEquals(1, rules.size()); - assertEquals("AND($A1>=EDATE($D$6,3),$B1>0)", rules.get(0).getFormula1()); - } - } - - @Test - void test61543() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFTable table1 = sheet.createTable(null); - XSSFTable table2 = sheet.createTable(null); - XSSFTable table3 = sheet.createTable(null); - - assertDoesNotThrow(() -> sheet.removeTable(table1)); - - assertDoesNotThrow(() -> sheet.createTable(null)); - - assertDoesNotThrow(() -> sheet.removeTable(table2)); - assertDoesNotThrow(() -> sheet.removeTable(table3)); - - assertDoesNotThrow(() -> sheet.createTable(null)); - } - } - - /** - * Auto column sizing failed when there were loads of fonts with - * errors like ArrayIndexOutOfBoundsException: -32765 - */ - @Test - void test62108() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFRow row = sheet.createRow(0); - - // Create lots of fonts - XSSFDataFormat formats = wb.createDataFormat(); - XSSFFont[] fonts = new XSSFFont[50000]; - for (int i = 0; i < fonts.length; i++) { - XSSFFont font = wb.createFont(); - font.setFontHeight(i); - fonts[i] = font; - } - - // Create a moderate number of columns, which use - // fonts from the start and end of the font list - final int numCols = 125; - for (int i = 0; i < numCols; i++) { - XSSFCellStyle cs = wb.createCellStyle(); - cs.setDataFormat(formats.getFormat("'Test " + i + "' #,###")); - - XSSFFont font = fonts[i]; - if (i % 2 == 1) { - font = fonts[fonts.length - i]; - } - cs.setFont(font); - - XSSFCell c = row.createCell(i); - c.setCellValue(i); - c.setCellStyle(cs); - } - - // Do the auto-size - for (int i = 0; i < numCols; i++) { - int i2 = i; - assertDoesNotThrow(() -> sheet.autoSizeColumn(i2)); - } - } - } - - @Test - void test61905xlsx() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - checkActiveSheet(wb, XSSFITestDataProvider.instance); - } - } - - @Test - void test61905xls() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - checkActiveSheet(wb, HSSFITestDataProvider.instance); - } - } - - private void checkActiveSheet(Workbook wb, ITestDataProvider instance) throws IOException { - Sheet sheet = wb.createSheet("new sheet"); - sheet.setActiveCell(new CellAddress("E11")); - assertEquals("E11", sheet.getActiveCell().formatAsString()); - - Workbook wbBack = instance.writeOutAndReadBack(wb); - sheet = wbBack.getSheetAt(0); - assertEquals("E11", sheet.getActiveCell().formatAsString()); - wbBack.close(); - } - - @Test - void testBug54084Unicode() throws IOException { - // sample XLSX with the same text-contents as the text-file above - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("54084 - Greek - beyond BMP.xlsx")) { - - verifyBug54084Unicode(wb); - - //XSSFTestDataSamples.writeOut(wb, "bug 54084 for manual review"); - - // now write the file and read it back in - XSSFWorkbook wbWritten = XSSFTestDataSamples.writeOutAndReadBack(wb); - verifyBug54084Unicode(wbWritten); - - // finally also write it out via the streaming interface and verify that we still can read it back in - SXSSFWorkbook swb = new SXSSFWorkbook(wb); - Workbook wbStreamingWritten = SXSSFITestDataProvider.instance.writeOutAndReadBack(swb); - verifyBug54084Unicode(wbStreamingWritten); - - wbWritten.close(); - swb.close(); - wbStreamingWritten.close(); - } - } - - private void verifyBug54084Unicode(Workbook wb) { - // expected data is stored in UTF-8 in a text-file - byte[] data = HSSFTestDataSamples.getTestDataFileContent("54084 - Greek - beyond BMP.txt"); - String testData = new String(data, StandardCharsets.UTF_8).trim(); - - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - - String value = cell.getStringCellValue(); - //System.out.println(value); - - assertEquals(testData, value, "The data in the text-file should exactly match the data that we read from the workbook"); - } - - - @Test - void bug63371() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - CellRangeAddress region = new CellRangeAddress(1, 1, 1, 2); - assertEquals(0, sheet.addMergedRegion(region)); - //System.out.println(String.format("%s: index=%d", "testAddMergedRegion", index)); - - final List<CellRangeAddress> ranges = sheet.getMergedRegions(); - final int numMergedRegions = sheet.getNumMergedRegions(); - final CTWorksheet ctSheet = sheet.getCTWorksheet(); - final CTMergeCells ctMergeCells = ctSheet.getMergeCells(); - final List<CTMergeCell> ctMergeCellList = ctMergeCells.getMergeCellList(); - final long ctMergeCellCount = ctMergeCells.getCount(); - final int ctMergeCellListSize = ctMergeCellList.size(); - - /*System.out.println(String.format("\ntestMergeRegions(%s)", "After adding first region")); - System.out.println(String.format("ranges.size=%d", ranges.size())); - System.out.println(String.format("numMergedRegions=%d", numMergedRegions)); - System.out.println(String.format("ctMergeCellCount=%d", ctMergeCellCount)); - System.out.println(String.format("ctMergeCellListSize=%d", ctMergeCellListSize));*/ - - assertEquals(1, ranges.size()); - assertEquals(1, numMergedRegions); - assertEquals(1, ctMergeCellCount); - assertEquals(1, ctMergeCellListSize); - - } - } - - @Test - void bug60397() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - CellRangeAddress region = new CellRangeAddress(1, 1, 1, 2); - assertEquals(0, sheet.addMergedRegion(region)); - //System.out.println(String.format("%s: index=%d", "testAddMergedRegion", index)); - - List<CellRangeAddress> ranges = sheet.getMergedRegions(); - int numMergedRegions = sheet.getNumMergedRegions(); - CTWorksheet ctSheet = sheet.getCTWorksheet(); - CTMergeCells ctMergeCells = ctSheet.getMergeCells(); - List<CTMergeCell> ctMergeCellList = ctMergeCells.getMergeCellList(); - long ctMergeCellCount = ctMergeCells.getCount(); - int ctMergeCellListSize = ctMergeCellList.size(); - - /*System.out.println(String.format("\ntestMergeRegions(%s)", "After adding first region")); - System.out.println(String.format("ranges.size=%d", ranges.size())); - System.out.println(String.format("numMergedRegions=%d", numMergedRegions)); - System.out.println(String.format("ctMergeCellCount=%d", ctMergeCellCount)); - System.out.println(String.format("ctMergeCellListSize=%d", ctMergeCellListSize)); */ - - assertEquals(1, ranges.size()); - assertEquals(1, numMergedRegions); - assertEquals(1, ctMergeCellCount); - assertEquals(1, ctMergeCellListSize); - - CellRangeAddress region2 = new CellRangeAddress(1, 2, 4, 6); - assertEquals(1, sheet.addMergedRegion(region2)); - //System.out.println(String.format("%s: index=%d", "testAddMergedRegion", index)); - - ranges = sheet.getMergedRegions(); - numMergedRegions = sheet.getNumMergedRegions(); - ctSheet = sheet.getCTWorksheet(); - ctMergeCells = ctSheet.getMergeCells(); - ctMergeCellList = ctMergeCells.getMergeCellList(); - ctMergeCellCount = ctMergeCells.getCount(); - ctMergeCellListSize = ctMergeCellList.size(); - - /*System.out.println(String.format("\ntestMergeRegions(%s)", "After adding second region")); - System.out.println(String.format("ranges.size=%d", ranges.size())); - System.out.println(String.format("numMergedRegions=%d", numMergedRegions)); - System.out.println(String.format("ctMergeCellCount=%d", ctMergeCellCount)); - System.out.println(String.format("ctMergeCellListSize=%d", ctMergeCellListSize));*/ - - assertEquals(2, ranges.size()); - assertEquals(2, numMergedRegions); - assertEquals(2, ctMergeCellCount); - assertEquals(2, ctMergeCellListSize); - } - } - - @Test - void testBug63509() throws IOException { - try (XSSFWorkbook workbook = new XSSFWorkbook()) { - - XSSFSheet sheet = workbook.createSheet("sheet1"); - - Row row = sheet.createRow(0); - - Cell cell = row.createCell(0); - cell.setCellValue("1000"); - - // This causes the error - sheet.addIgnoredErrors(new CellReference(cell), IgnoredErrorType.NUMBER_STORED_AS_TEXT); - - // Workaround - // sheet.addIgnoredErrors(new CellReference(cell.getRowIndex(), cell.getColumnIndex(), false, false), - // IgnoredErrorType.NUMBER_STORED_AS_TEXT); - - String sqref = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0).getSqref().get(0).toString(); - assertEquals("A1", sqref); - } - } - - @Test - void test64045() { - File file = XSSFTestDataSamples.getSampleFile("xlsx-corrupted.xlsx"); - assertThrows(POIXMLException.class, () -> new XSSFWorkbook(file), "Should catch exception as the file is corrupted"); - } - - @Test - void test58896WithFile() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58896.xlsx")) { - Sheet sheet = wb.getSheetAt(0); - Instant start = now(); - - LOG.atInfo().log("Autosizing columns..."); - - for (int i = 0; i < 3; ++i) { - LOG.atInfo().log("Autosize {} - {}", box(i), between(start, now())); - sheet.autoSizeColumn(i); - } - - for (int i = 0; i < 69 - 35 + 1; ++i) - for (int j = 0; j < 8; ++j) { - int col = 3 + 2 + i * (8 + 2) + j; - LOG.atInfo().log("Autosize {} - {}", box(col), between(start, now())); - sheet.autoSizeColumn(col); - } - LOG.atInfo().log(between(start, now())); - - assertTrue(between(start, now()).getSeconds() < 25); - } - } - - @Test - void testBug63845() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - Cell cell = row.createCell(0, CellType.FORMULA); - cell.setCellFormula("SUM(B1:E1)"); - - assertNull(((XSSFCell) cell).getCTCell().getV(), - "Element 'v' should not be set for formulas unless the value was calculated"); - - try (Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { - Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(0); - assertNull(((XSSFCell) cellBack).getCTCell().getV(), - "Element 'v' should not be set for formulas unless the value was calculated"); - assertNotNull(((XSSFCell) cellBack).getCTCell().getF(), - "Formula should be set internally now"); - - wbBack.getCreationHelper().createFormulaEvaluator().evaluateInCell(cellBack); - - assertEquals("0.0", ((XSSFCell) cellBack).getCTCell().getV(), - "Element 'v' should be set now as the formula was calculated manually"); - - cellBack.setCellValue("123"); - assertEquals("123", cellBack.getStringCellValue(), - "String value should be set now"); - assertNull(((XSSFCell) cellBack).getCTCell().getF(), "No formula should be set any more"); - } - } - } - - @Test - void testBug63845_2() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - row.createCell(0).setCellValue(2); - row.createCell(1).setCellValue(5); - row.createCell(2).setCellFormula("A1+B1"); - - try (Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { - Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(2); - - assertNull(((XSSFCell) cellBack).getCTCell().getV(), - "Element 'v' should not be set for formulas unless the value was calculated"); - - wbBack.getCreationHelper().createFormulaEvaluator().evaluateInCell(cellBack); - - assertEquals("7.0", ((XSSFCell) cellBack).getCTCell().getV(), - "Element 'v' should be set now as the formula was calculated manually"); - } - } - } - - @Test - void testBug64508() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64508.xlsx")) { - int activeSheet = wb.getActiveSheetIndex(); - Sheet sheet1 = wb.getSheetAt(activeSheet); - Row row = sheet1.getRow(1); - CellReference aCellReference = new CellReference("E2"); - Cell aCell = row.getCell(aCellReference.getCol()); - assertEquals(CellType.STRING, aCell.getCellType()); - assertEquals("", aCell.getStringCellValue()); - } - } - - @Test - void testBug64667() throws IOException { - //test that an NPE isn't thrown on opening - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64667.xlsx")) { - int activeSheet = wb.getActiveSheetIndex(); - assertEquals(0, activeSheet); - assertNotNull(wb.getSheetAt(activeSheet)); - } - } - - - - @Test - void testXLSXinPPT() throws Exception { - assumeFalse(Boolean.getBoolean("scratchpad.ignore")); - - try (SlideShow<?,?> ppt = SlideShowFactory.create( - POIDataSamples.getSlideShowInstance().openResourceAsStream("testPPT_oleWorkbook.ppt"))) { - - Slide<?, ?> slide = ppt.getSlides().get(1); - ObjectShape<?,?> oleShape = (ObjectShape<?,?>)slide.getShapes().get(2); - - org.apache.poi.sl.usermodel.ObjectData data = oleShape.getObjectData(); - assertNull(data.getFileName()); - - // Will be OOXML wrapped in OLE2, not directly SpreadSheet - POIFSFileSystem fs = new POIFSFileSystem(data.getInputStream()); - assertTrue(fs.getRoot().hasEntry(OOXML_PACKAGE)); - assertFalse(fs.getRoot().hasEntry("Workbook")); - - - // Can fetch Package to get OOXML - DirectoryNode root = fs.getRoot(); - DocumentEntry docEntry = (DocumentEntry) root.getEntry(OOXML_PACKAGE); - try (DocumentInputStream dis = new DocumentInputStream(docEntry); - OPCPackage pkg = OPCPackage.open(dis); - XSSFWorkbook wb = new XSSFWorkbook(pkg)) { - assertEquals(1, wb.getNumberOfSheets()); - } - - // Via the XSSF Factory - XSSFWorkbookFactory xssfFactory = new XSSFWorkbookFactory(); - try (XSSFWorkbook wb = xssfFactory.create(fs.getRoot(), null)) { - assertEquals(1, wb.getNumberOfSheets()); - } - - - // Or can open via the normal Factory, as stream or OLE2 - try (Workbook wb = WorkbookFactory.create(fs)) { - assertEquals(1, wb.getNumberOfSheets()); - } - try (Workbook wb = WorkbookFactory.create(data.getInputStream())) { - assertEquals(1, wb.getNumberOfSheets()); - } - } - } - - @Test - void test64986() { - XSSFWorkbook w = new XSSFWorkbook(); - XSSFSheet s = w.createSheet(); - XSSFRow r = s.createRow(0); - XSSFCell c = r.createCell(0); - c.setCellFormula("MATCH(\"VAL\",B1:B11,)"); - - FormulaEvaluator evaluator = w.getCreationHelper().createFormulaEvaluator(); - CellValue value = evaluator.evaluate(c); - assertEquals(CellType.ERROR, value.getCellType()); - assertEquals(ErrorEval.NA.getErrorCode(), value.getErrorValue()); - - // put a value in place so the match should find something - Cell val = r.createCell(1); - val.setCellValue("VAL"); - - // clear and check that now we find a match - evaluator.clearAllCachedResultValues(); - value = evaluator.evaluate(c); - assertEquals(CellType.NUMERIC, value.getCellType()); - assertEquals(1, value.getNumberValue(), 0.01); - } - - @Test - void test64750() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64750.xlsx")) { - Sheet sheet = wb.getSheet("Sheet1"); - assertEquals(1, sheet.getDataValidations().size()); - } - } - - @Test - void test64450() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64450.xlsx")) { - assertNotNull(wb); - } - } - - @Test - void test64494() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - CellStyle styleRight = wb.createCellStyle(); - CellStyle styleLeft = wb.createCellStyle(); - styleRight.setAlignment(HorizontalAlignment.RIGHT); - //styleRight.setBorderBottom(BorderStyle.DASH_DOT); - styleLeft.setAlignment(HorizontalAlignment.LEFT); - //styleLeft.setBorderRight(BorderStyle.MEDIUM); - - assertEquals(HorizontalAlignment.RIGHT, styleRight.getAlignment()); - assertEquals(HorizontalAlignment.LEFT, styleLeft.getAlignment()); - - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - - Cell cellRight = row.createCell(0); - cellRight.setCellValue("R"); - cellRight.setCellStyle(styleRight); - - Cell cellLeft = row.createCell(1); - cellLeft.setCellValue("L"); - cellLeft.setCellStyle(styleLeft); - - /*try (OutputStream out = new FileOutputStream("/tmp/64494.xlsx")) { - wb.write(out); - }*/ - - assertEquals(HorizontalAlignment.RIGHT, cellRight.getCellStyle().getAlignment()); - assertEquals(HorizontalAlignment.LEFT, cellLeft.getCellStyle().getAlignment()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java deleted file mode 100644 index f677b5cc0f..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java +++ /dev/null @@ -1,769 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.assertNotEquals; -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 static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.tests.usermodel.BaseTestXCell; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellCopyPolicy; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.EnumSource; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType; - -public final class TestXSSFCell extends BaseTestXCell { - - public TestXSSFCell() { - super(XSSFITestDataProvider.instance); - } - - /** - * Bug 47026: trouble changing cell type when workbook doesn't contain - * Shared String Table - */ - @Test - void test47026_1() throws IOException { - try (Workbook wb = _testDataProvider.openSampleWorkbook("47026.xlsm")) { - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType()); - cell.setCellValue("456"); - assertEquals(CellType.STRING, cell.getCachedFormulaResultType()); - } - } - - @Test - void test47026_2() throws IOException { - try (Workbook wb = _testDataProvider.openSampleWorkbook("47026.xlsm")) { - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType()); - cell.setCellFormula(null); - IllegalStateException e = assertThrows(IllegalStateException.class, cell::getCachedFormulaResultType); - assertEquals("Only formula cells have cached results", e.getMessage()); - cell.setCellValue("456"); - assertEquals(CellType.STRING, cell.getCellType()); - } - } - - /** - * Test that we can read inline strings that are expressed directly in the cell definition - * instead of implementing the shared string table. - * - * Some programs, for example, Microsoft Excel Driver for .xlsx insert inline string - * instead of using the shared string table. See bug 47206 - */ - @Test - void testInlineString() throws IOException { - XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("xlsx-jdbc.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - XSSFRow row = sheet.getRow(1); - - XSSFCell cell_0 = row.getCell(0); - assertEquals(STCellType.INT_INLINE_STR, cell_0.getCTCell().getT().intValue()); - assertTrue(cell_0.getCTCell().isSetIs()); - assertEquals("A Very large string in column 1 AAAAAAAAAAAAAAAAAAAAA", cell_0.getStringCellValue()); - - XSSFCell cell_1 = row.getCell(1); - assertEquals(STCellType.INT_INLINE_STR, cell_1.getCTCell().getT().intValue()); - assertTrue(cell_1.getCTCell().isSetIs()); - assertEquals("foo", cell_1.getStringCellValue()); - - XSSFCell cell_2 = row.getCell(2); - assertEquals(STCellType.INT_INLINE_STR, cell_2.getCTCell().getT().intValue()); - assertTrue(cell_2.getCTCell().isSetIs()); - assertEquals("bar", row.getCell(2).getStringCellValue()); - wb.close(); - } - - /** - * Bug 47278 - xsi:nil attribute for <t> tag caused Excel 2007 to fail to open workbook - */ - @Test - void test47278() throws IOException { - XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - SharedStringsTable sst = wb.getSharedStringSource(); - assertEquals(0, sst.getCount()); - - //case 1. cell.setCellValue(new XSSFRichTextString((String)null)); - Cell cell_0 = row.createCell(0); - RichTextString str = new XSSFRichTextString((String)null); - assertNull(str.getString()); - cell_0.setCellValue(str); - assertEquals(0, sst.getCount()); - assertEquals(CellType.BLANK, cell_0.getCellType(), "Having: " + cell_0); - - //case 2. cell.setCellValue((String)null); - Cell cell_1 = row.createCell(1); - cell_1.setCellValue((String)null); - assertEquals(0, sst.getCount()); - assertEquals(CellType.BLANK, cell_1.getCellType(), "Having: " + cell_1); - - //case 3. cell.setCellValue((RichTextString)null); - Cell cell_2 = row.createCell(2); - cell_2.setCellValue((RichTextString) null); - assertEquals(0, sst.getCount()); - assertEquals(CellType.BLANK, cell_2.getCellType(), "Having: " + cell_2); - - wb.close(); - } - - @Test - void testFormulaString() throws IOException { - try (XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.createWorkbook()) { - XSSFCell cell = wb.createSheet().createRow(0).createCell(0); - CTCell ctCell = cell.getCTCell(); //low-level bean holding cell's xml - - cell.setCellFormula("A2"); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("A2", cell.getCellFormula()); - //the value is not set and cell's type='N' which means blank - assertEquals(STCellType.N, ctCell.getT()); - - //set cached formula value - cell.setCellValue("t='str'"); - //we are still of 'formula' type - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("A2", cell.getCellFormula()); - //cached formula value is set and cell's type='STR' - assertEquals(STCellType.STR, ctCell.getT()); - assertEquals("t='str'", cell.getStringCellValue()); - - //now remove the formula, the cached formula result remains - cell.setCellFormula(null); - assertEquals(CellType.STRING, cell.getCellType()); - assertEquals(STCellType.STR, ctCell.getT()); - //the line below failed prior to fix of Bug #47889 - assertEquals("t='str'", cell.getStringCellValue()); - - //revert to a blank cell - cell.setCellValue((String) null); - assertEquals(CellType.BLANK, cell.getCellType()); - assertEquals(STCellType.N, ctCell.getT()); - assertEquals("", cell.getStringCellValue()); - - // check behavior with setCellFormulaValidation - final String invalidFormula = "A", validFormula = "A2"; - - // check that default is true - assertTrue(wb.getCellFormulaValidation()); - - // check that valid formula does not throw exception - cell.setCellFormula(validFormula); - - // check that invalid formula does throw exception - assertThrows(FormulaParseException.class, () -> cell.setCellFormula(invalidFormula)); - - // set cell formula validation to false - wb.setCellFormulaValidation(false); - assertFalse(wb.getCellFormulaValidation()); - - // check that neither valid nor invalid formula throw an exception - cell.setCellFormula(validFormula); - cell.setCellFormula(invalidFormula); - } - } - - /** - * Bug 47889: problems when calling XSSFCell.getStringCellValue() on a workbook created in Gnumeric - */ - @Test - void test47889() throws IOException { - XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("47889.xlsx"); - XSSFSheet sh = wb.getSheetAt(0); - - XSSFCell cell; - - //try a string cell - cell = sh.getRow(0).getCell(0); - assertEquals(CellType.STRING, cell.getCellType()); - assertEquals("a", cell.getStringCellValue()); - assertEquals("a", cell.toString()); - //Gnumeric produces spreadsheets without styles - //make sure we return null for that instead of throwing OutOfBounds - assertNull(cell.getCellStyle()); - - //try a numeric cell - cell = sh.getRow(1).getCell(0); - assertEquals(CellType.NUMERIC, cell.getCellType()); - assertEquals(1.0, cell.getNumericCellValue(), 0); - assertEquals("1.0", cell.toString()); - //Gnumeric produces spreadsheets without styles - //make sure we return null for that instead of throwing OutOfBounds - assertNull(cell.getCellStyle()); - wb.close(); - } - - @Test - void testMissingRAttribute() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - XSSFRow row = sheet.createRow(0); - XSSFCell a1 = row.createCell(0); - a1.setCellValue("A1"); - XSSFCell a2 = row.createCell(1); - a2.setCellValue("B1"); - XSSFCell a4 = row.createCell(4); - a4.setCellValue("E1"); - XSSFCell a6 = row.createCell(5); - a6.setCellValue("F1"); - - assertCellsWithMissingR(row); - - a2.getCTCell().unsetR(); - a6.getCTCell().unsetR(); - - assertCellsWithMissingR(row); - - XSSFWorkbook wb2 = (XSSFWorkbook)_testDataProvider.writeOutAndReadBack(wb1); - row = wb2.getSheetAt(0).getRow(0); - assertCellsWithMissingR(row); - - wb2.close(); - wb1.close(); - } - - private void assertCellsWithMissingR(XSSFRow row){ - XSSFCell a1 = row.getCell(0); - assertNotNull(a1); - XSSFCell a2 = row.getCell(1); - assertNotNull(a2); - XSSFCell a5 = row.getCell(4); - assertNotNull(a5); - XSSFCell a6 = row.getCell(5); - assertNotNull(a6); - - assertEquals(6, row.getLastCellNum()); - assertEquals(4, row.getPhysicalNumberOfCells()); - - assertEquals("A1", a1.getStringCellValue()); - assertEquals("B1", a2.getStringCellValue()); - assertEquals("E1", a5.getStringCellValue()); - assertEquals("F1", a6.getStringCellValue()); - - // even if R attribute is not set, - // POI is able to re-construct it from column and row indexes - assertEquals("A1", a1.getReference()); - assertEquals("B1", a2.getReference()); - assertEquals("E1", a5.getReference()); - assertEquals("F1", a6.getReference()); - } - - @Test - void testMissingRAttributeBug54288() throws IOException { - // workbook with cells missing the R attribute - XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("54288.xlsx"); - // same workbook re-saved in Excel 2010, the R attribute is updated for every cell with the right value. - XSSFWorkbook wbRef = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("54288-ref.xlsx"); - - XSSFSheet sheet = wb.getSheetAt(0); - XSSFSheet sheetRef = wbRef.getSheetAt(0); - assertEquals(sheetRef.getPhysicalNumberOfRows(), sheet.getPhysicalNumberOfRows()); - - // Test idea: iterate over cells in the reference worksheet, they all have the R attribute set. - // For each cell from the reference sheet find the corresponding cell in the problematic file (with missing R) - // and assert that POI reads them equally: - DataFormatter formater = new DataFormatter(); - for(Row r : sheetRef){ - XSSFRow rowRef = (XSSFRow)r; - XSSFRow row = sheet.getRow(rowRef.getRowNum()); - - assertEquals(rowRef.getPhysicalNumberOfCells(), row.getPhysicalNumberOfCells(), - "number of cells in row["+row.getRowNum()+"]"); - - for(Cell c : rowRef){ - XSSFCell cellRef = (XSSFCell)c; - XSSFCell cell = row.getCell(cellRef.getColumnIndex()); - - assertEquals(cellRef.getColumnIndex(), cell.getColumnIndex()); - assertEquals(cellRef.getReference(), cell.getReference()); - - if(!cell.getCTCell().isSetR()){ - assertTrue(cellRef.getCTCell().isSetR(), "R must e set in cellRef"); - - String valRef = formater.formatCellValue(cellRef); - String val = formater.formatCellValue(cell); - assertEquals(valRef, val); - } - - } - } - wbRef.close(); - wb.close(); - } - - @Test - void test56170() throws IOException { - final Workbook wb1 = XSSFTestDataSamples.openSampleWorkbook("56170.xlsx"); - final XSSFSheet sheet = (XSSFSheet) wb1.getSheetAt(0); - - Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - Cell cell; - - // add some contents to table so that the table will need expansion - Row row = sheet.getRow(0); - Workbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - cell = row.createCell(0); - Workbook wb4 = XSSFTestDataSamples.writeOutAndReadBack(wb3); - cell.setCellValue("demo1"); - Workbook wb5 = XSSFTestDataSamples.writeOutAndReadBack(wb4); - cell = row.createCell(1); - Workbook wb6 = XSSFTestDataSamples.writeOutAndReadBack(wb5); - cell.setCellValue("demo2"); - Workbook wb7 = XSSFTestDataSamples.writeOutAndReadBack(wb6); - cell = row.createCell(2); - Workbook wb8 = XSSFTestDataSamples.writeOutAndReadBack(wb7); - cell.setCellValue("demo3"); - - Workbook wb9 = XSSFTestDataSamples.writeOutAndReadBack(wb8); - - row = sheet.getRow(1); - cell = row.createCell(0); - cell.setCellValue("demo1"); - cell = row.createCell(1); - cell.setCellValue("demo2"); - cell = row.createCell(2); - cell.setCellValue("demo3"); - - Workbook wb10 = XSSFTestDataSamples.writeOutAndReadBack(wb9); - - // expand table - XSSFTable table = sheet.getTables().get(0); - final CellReference startRef = table.getStartCellReference(); - final CellReference endRef = table.getEndCellReference(); - table.getCTTable().setRef(new CellRangeAddress(startRef.getRow(), 1, startRef.getCol(), endRef.getCol()).formatAsString()); - - Workbook wb11 = XSSFTestDataSamples.writeOutAndReadBack(wb10); - assertNotNull(wb11); - - wb11.close(); - wb10.close(); - wb9.close(); - wb8.close(); - wb7.close(); - wb6.close(); - wb5.close(); - wb4.close(); - wb3.close(); - wb2.close(); - wb1.close(); - } - - @Test - void test56170Reproduce() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - final Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - // by creating Cells out of order we trigger the handling in onDocumentWrite() - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(0); - - validateRow(row); - - validateRow(row); - - // once again with removing one cell - row.removeCell(cell1); - - validateRow(row); - - // once again with removing the same cell, this throws an exception - assertThrows(IllegalArgumentException.class, () -> row.removeCell(cell1)); - - // now check again - validateRow(row); - - // once again with removing one cell - row.removeCell(cell2); - - // now check again - validateRow(row); - } - } - - private void validateRow(Row row) { - // trigger bug with CArray handling - ((XSSFRow)row).onDocumentWrite(); - - for(Cell cell : row) { - assertNotNull(cell.toString()); - } - } - - @ParameterizedTest - @EnumSource(value = MissingCellPolicy.class) - void testBug56644ReturnNull(MissingCellPolicy policy) throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56644.xlsx")) { - wb.setMissingCellPolicy(policy); - Sheet sheet = wb.getSheet("samplelist"); - Row row = sheet.getRow(20); - switch (policy) { - case CREATE_NULL_AS_BLANK: { - Cell cell = row.getCell(2); - assertNotNull(cell); - assertEquals(CellType.STRING, cell.getCellType()); - break; - } - case RETURN_BLANK_AS_NULL: { - Cell cell = row.getCell(2); - assertNotNull(cell); - assertEquals(CellType.STRING, cell.getCellType()); - cell.setBlank(); - cell = row.getCell(2); - assertNull(cell); - break; - } - case RETURN_NULL_AND_BLANK: { - Cell cell = row.getCell(2); - assertNotNull(cell); - break; - } - } - } - } - - @Test - void testEncodingBelowAscii() throws IOException { - StringBuilder sb = new StringBuilder(); - // test all possible characters - for(int i = 0; i < Character.MAX_VALUE; i++) { - sb.append((char)i); - } - - String strAll = sb.toString(); - - // process in chunks as we have a limit on size of column now - int pos = 0; - while(pos < strAll.length()) { - String str = strAll.substring(pos, Math.min(strAll.length(), pos+SpreadsheetVersion.EXCEL2007.getMaxTextLength())); - - Workbook wb = HSSFITestDataProvider.instance.createWorkbook(); - Cell cell = wb.createSheet().createRow(0).createCell(0); - - Workbook xwb = XSSFITestDataProvider.instance.createWorkbook(); - Cell xCell = xwb.createSheet().createRow(0).createCell(0); - - Workbook swb = SXSSFITestDataProvider.instance.createWorkbook(); - Cell sCell = swb.createSheet().createRow(0).createCell(0); - - cell.setCellValue(str); - assertEquals(str, cell.getStringCellValue()); - xCell.setCellValue(str); - assertEquals(str, xCell.getStringCellValue()); - sCell.setCellValue(str); - assertEquals(str, sCell.getStringCellValue()); - - Workbook wbBack = HSSFITestDataProvider.instance.writeOutAndReadBack(wb); - Workbook xwbBack = XSSFITestDataProvider.instance.writeOutAndReadBack(xwb); - Workbook swbBack = SXSSFITestDataProvider.instance.writeOutAndReadBack(swb); - cell = wbBack.getSheetAt(0).createRow(0).createCell(0); - xCell = xwbBack.getSheetAt(0).createRow(0).createCell(0); - sCell = swbBack.getSheetAt(0).createRow(0).createCell(0); - - assertEquals(cell.getStringCellValue(), xCell.getStringCellValue()); - assertEquals(cell.getStringCellValue(), sCell.getStringCellValue()); - - pos += SpreadsheetVersion.EXCEL97.getMaxTextLength(); - - swbBack.close(); - xwbBack.close(); - wbBack.close(); - swb.close(); - xwb.close(); - wb.close(); - } - } - - private XSSFCell srcCell, destCell; //used for testCopyCellFrom_CellCopyPolicy - - @Test - public final void testCopyCellFrom_CellCopyPolicy_default() { - setUp_testCopyCellFrom_CellCopyPolicy(); - - // default copy policy - final CellCopyPolicy policy = new CellCopyPolicy(); - destCell.copyCellFrom(srcCell, policy); - - assertEquals(CellType.FORMULA, destCell.getCellType()); - assertEquals("2+3", destCell.getCellFormula()); - assertEquals(srcCell.getCellStyle(), destCell.getCellStyle()); - } - - @Test - public final void testCopyCellFrom_CellCopyPolicy_value() { - setUp_testCopyCellFrom_CellCopyPolicy(); - - // Paste values only - final CellCopyPolicy policy = new CellCopyPolicy.Builder().cellFormula(false).build(); - destCell.copyCellFrom(srcCell, policy); - assertEquals(CellType.NUMERIC, destCell.getCellType()); - } - - @Test - public final void testCopyCellFrom_CellCopyPolicy_formulaWithUnregisteredUDF() { - setUp_testCopyCellFrom_CellCopyPolicy(); - - srcCell.setCellFormula("MYFUNC2(123, $A5, Sheet1!$B7)"); - - // Copy formula verbatim (no shifting). This is okay because copyCellFrom is Internal. - // Users should use higher-level copying functions to row- or column-shift formulas. - final CellCopyPolicy policy = new CellCopyPolicy.Builder().cellFormula(true).build(); - destCell.copyCellFrom(srcCell, policy); - assertEquals("MYFUNC2(123, $A5, Sheet1!$B7)", destCell.getCellFormula()); - } - - @Test - public final void testCopyCellFrom_CellCopyPolicy_style() { - setUp_testCopyCellFrom_CellCopyPolicy(); - srcCell.setCellValue((String) null); - - // Paste styles only - final CellCopyPolicy policy = new CellCopyPolicy.Builder().cellValue(false).build(); - destCell.copyCellFrom(srcCell, policy); - assertEquals(srcCell.getCellStyle(), destCell.getCellStyle()); - - // Old cell value should not have been overwritten - assertNotEquals(CellType.BLANK, destCell.getCellType()); - assertEquals(CellType.BOOLEAN, destCell.getCellType()); - assertTrue(destCell.getBooleanCellValue()); - } - - @Test - public final void testCopyCellFrom_CellCopyPolicy_copyHyperlink() throws IOException { - setUp_testCopyCellFrom_CellCopyPolicy(); - final Workbook wb = srcCell.getSheet().getWorkbook(); - final CreationHelper createHelper = wb.getCreationHelper(); - - srcCell.setCellValue("URL LINK"); - Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL); - link.setAddress("https://poi.apache.org/"); - srcCell.setHyperlink(link); - - // Set link cell style (optional) - setLinkCellStyle(wb, srcCell); - - // Copy hyperlink - final CellCopyPolicy policy = new CellCopyPolicy.Builder().copyHyperlink(true).mergeHyperlink(false).build(); - destCell.copyCellFrom(srcCell, policy); - assertNotNull(destCell.getHyperlink()); - - assertSame(srcCell.getSheet(), destCell.getSheet(), - "unit test assumes srcCell and destCell are on the same sheet"); - - final List<XSSFHyperlink> links = srcCell.getSheet().getHyperlinkList(); - assertEquals(2, links.size(), "number of hyperlinks on sheet"); - assertEquals(new CellAddress(srcCell).formatAsString(), links.get(0).getCellRef(), "source hyperlink"); - assertEquals(new CellAddress(destCell).formatAsString(), links.get(1).getCellRef(), "destination hyperlink"); - - wb.close(); - } - - private void setLinkCellStyle(Workbook wb, XSSFCell srcCell) { - CellStyle hlinkStyle = wb.createCellStyle(); - Font hlinkFont = wb.createFont(); - hlinkFont.setUnderline(Font.U_SINGLE); - hlinkFont.setColor(IndexedColors.BLUE.getIndex()); - hlinkStyle.setFont(hlinkFont); - srcCell.setCellStyle(hlinkStyle); - } - - @Test - public final void testCopyCellFrom_CellCopyPolicy_mergeHyperlink() throws IOException { - setUp_testCopyCellFrom_CellCopyPolicy(); - final Workbook wb = srcCell.getSheet().getWorkbook(); - final CreationHelper createHelper = wb.getCreationHelper(); - - srcCell.setCellValue("URL LINK"); - Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL); - link.setAddress("https://poi.apache.org/"); - destCell.setHyperlink(link); - - // Set link cell style (optional) - setLinkCellStyle(wb, destCell); - - // Pre-condition assumptions. This test is broken if either of these fail. - assertSame(srcCell.getSheet(), destCell.getSheet(), - "unit test assumes srcCell and destCell are on the same sheet"); - assertNull(srcCell.getHyperlink()); - - // Merge hyperlink - since srcCell doesn't have a hyperlink, destCell's hyperlink is not overwritten (cleared). - final CellCopyPolicy policy = new CellCopyPolicy.Builder().mergeHyperlink(true).copyHyperlink(false).build(); - destCell.copyCellFrom(srcCell, policy); - assertNull(srcCell.getHyperlink()); - assertNotNull(destCell.getHyperlink()); - assertSame(link, destCell.getHyperlink()); - - List<XSSFHyperlink> links; - links = srcCell.getSheet().getHyperlinkList(); - assertEquals(1, links.size(), "number of hyperlinks on sheet"); - assertEquals(new CellAddress(destCell).formatAsString(), links.get(0).getCellRef(), "source hyperlink"); - - // Merge destCell's hyperlink to srcCell. Since destCell does have a hyperlink, this should copy destCell's hyperlink to srcCell. - srcCell.copyCellFrom(destCell, policy); - assertNotNull(srcCell.getHyperlink()); - assertNotNull(destCell.getHyperlink()); - - links = srcCell.getSheet().getHyperlinkList(); - assertEquals(2, links.size(), "number of hyperlinks on sheet"); - assertEquals(new CellAddress(destCell).formatAsString(), links.get(0).getCellRef(), "dest hyperlink"); - assertEquals(new CellAddress(srcCell).formatAsString(), links.get(1).getCellRef(), "source hyperlink"); - - wb.close(); - } - - private void setUp_testCopyCellFrom_CellCopyPolicy() { - @SuppressWarnings("resource") - final XSSFWorkbook wb = new XSSFWorkbook(); - final XSSFRow row = wb.createSheet("Sheet1").createRow(0); - srcCell = row.createCell(0); - destCell = row.createCell(1); - - srcCell.setCellFormula("2+3"); - - final CellStyle style = wb.createCellStyle(); - style.setBorderTop(BorderStyle.THICK); - style.setFillBackgroundColor((short) 5); - srcCell.setCellStyle(style); - - destCell.setCellValue(true); - } - - /** - * Bug 61869: updating a shared formula produces an unreadable file - */ - @Test - void test61869() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("61869.xlsx")) { - XSSFSheet sheet = wb.getSheetAt(0); - XSSFCell c2 = sheet.getRow(1).getCell(2); - assertEquals("SUM(A2,B2)", c2.getCellFormula()); - assertEquals(STCellFormulaType.SHARED, c2.getCTCell().getF().getT()); - assertEquals(0, c2.getCTCell().getF().getSi()); - XSSFCell c3 = sheet.getRow(2).getCell(2); - assertEquals(STCellFormulaType.SHARED, c3.getCTCell().getF().getT()); - assertEquals(0, c3.getCTCell().getF().getSi()); - assertEquals("SUM(A3,B3)", c3.getCellFormula()); - - assertEquals("SUM(A2,B2)", sheet.getSharedFormula(0).getStringValue()); - - c2.setCellFormula("SUM(A2:B2)"); - assertEquals(STCellFormulaType.SHARED, c2.getCTCell().getF().getT()); // c2 remains the master formula - - assertEquals("SUM(A2:B2)", sheet.getSharedFormula(0).getStringValue()); - assertEquals(STCellFormulaType.SHARED, c3.getCTCell().getF().getT()); - assertEquals(0, c3.getCTCell().getF().getSi()); - assertEquals("SUM(A3:B3)", c3.getCellFormula()); // formula in the follower cell is rebuilt - - } - - } - - @Test - void testBug58106RemoveSharedFormula() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("58106.xlsx")) { - XSSFSheet sheet = wb.getSheetAt(0); - XSSFRow row = sheet.getRow(12); - XSSFCell cell = row.getCell(1); - CTCellFormula f = cell.getCTCell().getF(); - assertEquals("B13:G13", f.getRef()); - assertEquals("SUM(B1:B3)", f.getStringValue()); - assertEquals(0, f.getSi()); - assertEquals(STCellFormulaType.SHARED, f.getT()); - for(char i = 'C'; i <= 'G'; i++){ - XSSFCell sc =row.getCell(i-'A'); - CTCellFormula sf = sc.getCTCell().getF(); - assertFalse(sf.isSetRef()); - assertEquals("", sf.getStringValue()); - assertEquals(0, sf.getSi()); - assertEquals(STCellFormulaType.SHARED, sf.getT()); - } - assertEquals("B13:G13", sheet.getSharedFormula(0).getRef()); - - cell.setCellType(CellType.NUMERIC); - - assertFalse(cell.getCTCell().isSetF()); - - XSSFCell nextFormulaMaster = row.getCell(2); - assertEquals("C13:G13", nextFormulaMaster.getCTCell().getF().getRef()); - assertEquals("SUM(C1:C3)", nextFormulaMaster.getCTCell().getF().getStringValue()); - assertEquals(0, nextFormulaMaster.getCTCell().getF().getSi()); - for(char i = 'D'; i <= 'G'; i++){ - XSSFCell sc =row.getCell(i-'A'); - CTCellFormula sf = sc.getCTCell().getF(); - assertFalse(sf.isSetRef()); - assertEquals("", sf.getStringValue()); - assertEquals(0, sf.getSi()); - assertEquals(STCellFormulaType.SHARED, sf.getT()); - } - assertEquals("C13:G13", sheet.getSharedFormula(0).getRef()); - - } - } - - @Test - void getErrorCellValue_returns0_onABlankCell() { - Cell cell = new XSSFWorkbook().createSheet().createRow(0).createCell(0); - assertThrows(IllegalStateException.class, cell::getErrorCellValue); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java deleted file mode 100644 index cefac9bb24..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java +++ /dev/null @@ -1,1098 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.ReadingOrder; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellXfs; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTStylesheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STHorizontalAlignment; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STVerticalAlignment; - -class TestXSSFCellStyle { - private StylesTable stylesTable; - private XSSFCellStyle cellStyle; - - @BeforeEach - void setUp() { - stylesTable = new StylesTable(); - - CTStylesheet ctStylesheet = stylesTable.getCTStylesheet(); - - CTBorder ctBorderA = CTBorder.Factory.newInstance(); - XSSFCellBorder borderA = new XSSFCellBorder(ctBorderA); - long borderId = stylesTable.putBorder(borderA); - assertEquals(0, borderId); - - XSSFCellBorder borderB = new XSSFCellBorder(); - assertEquals(0, stylesTable.putBorder(borderB)); - - CTFill ctFill = CTFill.Factory.newInstance(); - XSSFCellFill fill = new XSSFCellFill(ctFill, null); - long fillId = stylesTable.putFill(fill); - assertEquals(2, fillId); - - CTFont ctFont = CTFont.Factory.newInstance(); - XSSFFont font = new XSSFFont(ctFont); - long fontId = stylesTable.putFont(font); - assertEquals(1, fontId); - - CTXf cellStyleXf = ctStylesheet.addNewCellStyleXfs().addNewXf(); - cellStyleXf.setBorderId(1); - cellStyleXf.setFillId(1); - cellStyleXf.setFontId(1); - - CTCellXfs cellXfs = ctStylesheet.addNewCellXfs(); - CTXf cellXf = cellXfs.addNewXf(); - cellXf.setXfId(1); - cellXf.setBorderId(1); - cellXf.setFillId(1); - cellXf.setFontId(1); - assertEquals(2, stylesTable.putCellStyleXf(cellStyleXf)); - assertEquals(2, stylesTable.putCellXf(cellXf)); - cellStyle = new XSSFCellStyle(1, 1, stylesTable, null); - - assertNotNull(stylesTable.getFillAt(1).getCTFill().getPatternFill()); - assertEquals(STPatternType.INT_DARK_GRAY, stylesTable.getFillAt(1).getCTFill().getPatternFill().getPatternType().intValue()); - } - - @Test - void testGetSetBorderBottom() { - //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderBottom()); - - int num = stylesTable.getBorders().size(); - cellStyle.setBorderBottom(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderBottom()); - //a new border has been added - assertEquals(num + 1, stylesTable.getBorders().size()); - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getBottom().getStyle()); - - num = stylesTable.getBorders().size(); - //setting the same border multiple times should not change borderId - for (int i = 0; i < 3; i++) { - cellStyle.setBorderBottom(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderBottom()); - } - assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); - assertEquals(num, stylesTable.getBorders().size()); - assertSame(ctBorder, stylesTable.getBorderAt(borderId).getCTBorder()); - - //setting border to none removes the <bottom> element - cellStyle.setBorderBottom(BorderStyle.NONE); - assertEquals(num, stylesTable.getBorders().size()); - borderId = (int)cellStyle.getCoreXf().getBorderId(); - ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - //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); - } - - @Test - void testGetSetBorderRight() { - //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderRight()); - - int num = stylesTable.getBorders().size(); - cellStyle.setBorderRight(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderRight()); - //a new border has been added - assertEquals(num + 1, stylesTable.getBorders().size()); - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getRight().getStyle()); - - num = stylesTable.getBorders().size(); - //setting the same border multiple times should not change borderId - for (int i = 0; i < 3; i++) { - cellStyle.setBorderRight(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderRight()); - } - assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); - assertEquals(num, stylesTable.getBorders().size()); - assertSame(ctBorder, stylesTable.getBorderAt(borderId).getCTBorder()); - - //setting border to none removes the <right> element - cellStyle.setBorderRight(BorderStyle.NONE); - assertEquals(num, stylesTable.getBorders().size()); - borderId = (int)cellStyle.getCoreXf().getBorderId(); - ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - //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); - } - - @Test - void testGetSetBorderLeft() { - //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderLeft()); - - int num = stylesTable.getBorders().size(); - cellStyle.setBorderLeft(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderLeft()); - //a new border has been added - assertEquals(num + 1, stylesTable.getBorders().size()); - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getLeft().getStyle()); - - num = stylesTable.getBorders().size(); - //setting the same border multiple times should not change borderId - for (int i = 0; i < 3; i++) { - cellStyle.setBorderLeft(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderLeft()); - } - assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); - assertEquals(num, stylesTable.getBorders().size()); - assertSame(ctBorder, stylesTable.getBorderAt(borderId).getCTBorder()); - - //setting border to none removes the <left> element - cellStyle.setBorderLeft(BorderStyle.NONE); - assertEquals(num, stylesTable.getBorders().size()); - borderId = (int)cellStyle.getCoreXf().getBorderId(); - ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - //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); - } - - @Test - void testGetSetBorderTop() { - //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderTop()); - - int num = stylesTable.getBorders().size(); - cellStyle.setBorderTop(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderTop()); - //a new border has been added - assertEquals(num + 1, stylesTable.getBorders().size()); - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getTop().getStyle()); - - num = stylesTable.getBorders().size(); - //setting the same border multiple times should not change borderId - for (int i = 0; i < 3; i++) { - cellStyle.setBorderTop(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderTop()); - } - assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); - assertEquals(num, stylesTable.getBorders().size()); - assertSame(ctBorder, stylesTable.getBorderAt(borderId).getCTBorder()); - - //setting border to none removes the <top> element - cellStyle.setBorderTop(BorderStyle.NONE); - assertEquals(num, stylesTable.getBorders().size()); - borderId = (int)cellStyle.getCoreXf().getBorderId(); - ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - //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); - } - - private void testGetSetBorderXMLBean(BorderStyle border, STBorderStyle.Enum expected) { - cellStyle.setBorderTop(border); - assertEquals(border, cellStyle.getBorderTop()); - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(expected, ctBorder.getTop().getStyle()); - } - - - // Border Styles, in BorderStyle/STBorderStyle enum order - @Test - void testGetSetBorderNone() { - cellStyle.setBorderTop(BorderStyle.NONE); - assertEquals(BorderStyle.NONE, cellStyle.getBorderTop()); - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - // The default Style is already "none" - // Therefore the new style already exists as Id=0 - //assertTrue(borderId > 0); - // replacement: - assertEquals(0, borderId); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertNotNull(ctBorder.getTop()); - // no border style and STBorderStyle.NONE are equivalent - // POI prefers to unset the border style than explicitly set it STBorderStyle.NONE - } - - @Test - void testGetSetBorderThin() { - testGetSetBorderXMLBean(BorderStyle.THIN, STBorderStyle.THIN); - } - - @Test - void testGetSetBorderMedium() { - testGetSetBorderXMLBean(BorderStyle.MEDIUM, STBorderStyle.MEDIUM); - } - - @Test - void testGetSetBorderDashed() { - testGetSetBorderXMLBean(BorderStyle.DASHED, STBorderStyle.DASHED); - } - - @Test - void testGetSetBorderDotted() { - testGetSetBorderXMLBean(BorderStyle.DOTTED, STBorderStyle.DOTTED); - } - - @Test - void testGetSetBorderThick() { - testGetSetBorderXMLBean(BorderStyle.THICK, STBorderStyle.THICK); - } - - @Test - void testGetSetBorderDouble() { - testGetSetBorderXMLBean(BorderStyle.DOUBLE, STBorderStyle.DOUBLE); - } - - @Test - void testGetSetBorderHair() { - testGetSetBorderXMLBean(BorderStyle.HAIR, STBorderStyle.HAIR); - } - - @Test - void testGetSetBorderMediumDashed() { - testGetSetBorderXMLBean(BorderStyle.MEDIUM_DASHED, STBorderStyle.MEDIUM_DASHED); - } - - @Test - void testGetSetBorderDashDot() { - testGetSetBorderXMLBean(BorderStyle.DASH_DOT, STBorderStyle.DASH_DOT); - } - - @Test - void testGetSetBorderMediumDashDot() { - testGetSetBorderXMLBean(BorderStyle.MEDIUM_DASH_DOT, STBorderStyle.MEDIUM_DASH_DOT); - } - - @Test - void testGetSetBorderDashDotDot() { - testGetSetBorderXMLBean(BorderStyle.DASH_DOT_DOT, STBorderStyle.DASH_DOT_DOT); - } - - @Test - void testGetSetBorderMediumDashDotDot() { - testGetSetBorderXMLBean(BorderStyle.MEDIUM_DASH_DOT_DOT, STBorderStyle.MEDIUM_DASH_DOT_DOT); - } - - @Test - void testGetSetBorderSlantDashDot() { - testGetSetBorderXMLBean(BorderStyle.SLANTED_DASH_DOT, STBorderStyle.SLANT_DASH_DOT); - } - - @Test - void testGetSetBottomBorderColor() { - //defaults - assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getBottomBorderColor()); - assertNull(cellStyle.getBottomBorderXSSFColor()); - - int num = stylesTable.getBorders().size(); - - XSSFColor clr; - - //setting indexed color - cellStyle.setBottomBorderColor(IndexedColors.BLUE_GREY.getIndex()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getBottomBorderColor()); - clr = cellStyle.getBottomBorderXSSFColor(); - assertTrue(clr.getCTColor().isSetIndexed()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed()); - //a new border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), ctBorder.getBottom().getColor().getIndexed()); - - //setting XSSFColor - num = stylesTable.getBorders().size(); - clr = new XSSFColor(java.awt.Color.CYAN, stylesTable.getIndexedColors()); - cellStyle.setBottomBorderColor(clr); - assertEquals(clr.getCTColor().toString(), cellStyle.getBottomBorderXSSFColor().getCTColor().toString()); - byte[] rgb = cellStyle.getBottomBorderXSSFColor().getRGB(); - assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); - //another border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //passing null unsets the color - cellStyle.setBottomBorderColor(null); - assertNull(cellStyle.getBottomBorderXSSFColor()); - } - - @Test - void testGetSetTopBorderColor() { - //defaults - assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getTopBorderColor()); - assertNull(cellStyle.getTopBorderXSSFColor()); - - int num = stylesTable.getBorders().size(); - - XSSFColor clr; - - //setting indexed color - cellStyle.setTopBorderColor(IndexedColors.BLUE_GREY.getIndex()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getTopBorderColor()); - clr = cellStyle.getTopBorderXSSFColor(); - assertTrue(clr.getCTColor().isSetIndexed()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed()); - //a new border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), ctBorder.getTop().getColor().getIndexed()); - - //setting XSSFColor - num = stylesTable.getBorders().size(); - clr = new XSSFColor(java.awt.Color.CYAN, stylesTable.getIndexedColors()); - cellStyle.setTopBorderColor(clr); - assertEquals(clr.getCTColor().toString(), cellStyle.getTopBorderXSSFColor().getCTColor().toString()); - byte[] rgb = cellStyle.getTopBorderXSSFColor().getRGB(); - assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); - //another border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //passing null unsets the color - cellStyle.setTopBorderColor(null); - assertNull(cellStyle.getTopBorderXSSFColor()); - } - - @Test - void testGetSetLeftBorderColor() { - //defaults - assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getLeftBorderColor()); - assertNull(cellStyle.getLeftBorderXSSFColor()); - - int num = stylesTable.getBorders().size(); - - XSSFColor clr; - - //setting indexed color - cellStyle.setLeftBorderColor(IndexedColors.BLUE_GREY.getIndex()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getLeftBorderColor()); - clr = cellStyle.getLeftBorderXSSFColor(); - assertTrue(clr.getCTColor().isSetIndexed()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed()); - //a new border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), ctBorder.getLeft().getColor().getIndexed()); - - //setting XSSFColor - num = stylesTable.getBorders().size(); - clr = new XSSFColor(java.awt.Color.CYAN, stylesTable.getIndexedColors()); - cellStyle.setLeftBorderColor(clr); - assertEquals(clr.getCTColor().toString(), cellStyle.getLeftBorderXSSFColor().getCTColor().toString()); - byte[] rgb = cellStyle.getLeftBorderXSSFColor().getRGB(); - assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); - //another border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //passing null unsets the color - cellStyle.setLeftBorderColor(null); - assertNull(cellStyle.getLeftBorderXSSFColor()); - } - - @Test - void testGetSetRightBorderColor() { - //defaults - assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getRightBorderColor()); - assertNull(cellStyle.getRightBorderXSSFColor()); - - int num = stylesTable.getBorders().size(); - - XSSFColor clr; - - //setting indexed color - cellStyle.setRightBorderColor(IndexedColors.BLUE_GREY.getIndex()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getRightBorderColor()); - clr = cellStyle.getRightBorderXSSFColor(); - assertTrue(clr.getCTColor().isSetIndexed()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed()); - //a new border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), ctBorder.getRight().getColor().getIndexed()); - - //setting XSSFColor - num = stylesTable.getBorders().size(); - clr = new XSSFColor(java.awt.Color.CYAN, stylesTable.getIndexedColors()); - cellStyle.setRightBorderColor(clr); - assertEquals(clr.getCTColor().toString(), cellStyle.getRightBorderXSSFColor().getCTColor().toString()); - byte[] rgb = cellStyle.getRightBorderXSSFColor().getRGB(); - assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); - //another border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //passing null unsets the color - cellStyle.setRightBorderColor(null); - assertNull(cellStyle.getRightBorderXSSFColor()); - } - - @Test - void testGetSetFillBackgroundColor() { - - assertEquals(IndexedColors.AUTOMATIC.getIndex(), cellStyle.getFillBackgroundColor()); - assertNull(cellStyle.getFillBackgroundXSSFColor()); - - XSSFColor clr; - - int num = stylesTable.getFills().size(); - - //setting indexed color - cellStyle.setFillBackgroundColor(IndexedColors.RED.getIndex()); - assertEquals(IndexedColors.RED.getIndex(), cellStyle.getFillBackgroundColor()); - clr = cellStyle.getFillBackgroundXSSFColor(); - assertTrue(clr.getCTColor().isSetIndexed()); - assertEquals(IndexedColors.RED.getIndex(), clr.getIndexed()); - //a new fill was added to the styles table - assertEquals(num + 1, stylesTable.getFills().size()); - - //id of the created border - int fillId = (int)cellStyle.getCoreXf().getFillId(); - assertTrue(fillId > 0); - //check changes in the underlying xml bean - CTFill ctFill2 = stylesTable.getFillAt(fillId).getCTFill(); - assertEquals(IndexedColors.RED.getIndex(), ctFill2.getPatternFill().getBgColor().getIndexed()); - - //setting XSSFColor - num = stylesTable.getFills().size(); - clr = new XSSFColor(java.awt.Color.CYAN, stylesTable.getIndexedColors()); - cellStyle.setFillBackgroundColor(clr); - assertEquals(clr.getCTColor().toString(), cellStyle.getFillBackgroundXSSFColor().getCTColor().toString()); - byte[] rgb = cellStyle.getFillBackgroundXSSFColor().getRGB(); - assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); - //another border was added to the styles table - assertEquals(num + 1, stylesTable.getFills().size()); - - //passing null unsets the color - cellStyle.setFillBackgroundColor(null); - assertNull(cellStyle.getFillBackgroundXSSFColor()); - assertEquals(IndexedColors.AUTOMATIC.getIndex(), cellStyle.getFillBackgroundColor()); - } - - @Test - void testDefaultStyles() throws IOException { - - XSSFWorkbook wb1 = new XSSFWorkbook(); - - XSSFCellStyle style1 = wb1.createCellStyle(); - assertEquals(IndexedColors.AUTOMATIC.getIndex(), style1.getFillBackgroundColor()); - assertNull(style1.getFillBackgroundXSSFColor()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb1)); - wb1.close(); - - //compatibility with HSSF - HSSFWorkbook wb2 = new HSSFWorkbook(); - HSSFCellStyle style2 = wb2.createCellStyle(); - assertEquals(style2.getFillBackgroundColor(), style1.getFillBackgroundColor()); - assertEquals(style2.getFillForegroundColor(), style1.getFillForegroundColor()); - assertEquals(style2.getFillPattern(), style1.getFillPattern()); - assertEquals(style2.getFillPattern(), style1.getFillPattern()); - - assertEquals(style2.getLeftBorderColor(), style1.getLeftBorderColor()); - assertEquals(style2.getTopBorderColor(), style1.getTopBorderColor()); - assertEquals(style2.getRightBorderColor(), style1.getRightBorderColor()); - assertEquals(style2.getBottomBorderColor(), style1.getBottomBorderColor()); - - assertEquals(style2.getBorderBottom(), style1.getBorderBottom()); - assertEquals(style2.getBorderLeft(), style1.getBorderLeft()); - assertEquals(style2.getBorderRight(), style1.getBorderRight()); - assertEquals(style2.getBorderTop(), style1.getBorderTop()); - wb2.close(); - } - - @Test - void testGetFillForegroundColor() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - StylesTable styles = wb.getStylesSource(); - assertEquals(1, wb.getNumCellStyles()); - assertEquals(2, styles.getFills().size()); - - XSSFCellStyle defaultStyle = wb.getCellStyleAt((short)0); - assertEquals(IndexedColors.AUTOMATIC.getIndex(), defaultStyle.getFillForegroundColor()); - assertNull(defaultStyle.getFillForegroundXSSFColor()); - assertEquals(FillPatternType.NO_FILL, defaultStyle.getFillPattern()); - - XSSFCellStyle customStyle = wb.createCellStyle(); - - customStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - assertEquals(FillPatternType.SOLID_FOREGROUND, customStyle.getFillPattern()); - assertEquals(3, styles.getFills().size()); - - customStyle.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); - assertEquals(IndexedColors.BRIGHT_GREEN.getIndex(), customStyle.getFillForegroundColor()); - assertEquals(4, styles.getFills().size()); - - for (int i = 0; i < 3; i++) { - XSSFCellStyle style = wb.createCellStyle(); - - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - assertEquals(FillPatternType.SOLID_FOREGROUND, style.getFillPattern()); - assertEquals(4, styles.getFills().size()); - - style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); - assertEquals(IndexedColors.BRIGHT_GREEN.getIndex(), style.getFillForegroundColor()); - assertEquals(4, styles.getFills().size()); - } - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - wb.close(); - } - - @Test - void testGetFillPattern() { - - assertEquals(STPatternType.INT_DARK_GRAY-1, cellStyle.getFillPattern().getCode()); - - int num = stylesTable.getFills().size(); - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - assertEquals(FillPatternType.SOLID_FOREGROUND, cellStyle.getFillPattern()); - assertEquals(num + 1, stylesTable.getFills().size()); - int fillId = (int)cellStyle.getCoreXf().getFillId(); - assertTrue(fillId > 0); - //check changes in the underlying xml bean - CTFill ctFill2 = stylesTable.getFillAt(fillId).getCTFill(); - assertEquals(STPatternType.SOLID, ctFill2.getPatternFill().getPatternType()); - - //setting the same fill multiple time does not update the styles table - for (int i = 0; i < 3; i++) { - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - } - assertEquals(num + 1, stylesTable.getFills().size()); - - cellStyle.setFillPattern(FillPatternType.NO_FILL); - assertEquals(FillPatternType.NO_FILL, cellStyle.getFillPattern()); - fillId = (int)cellStyle.getCoreXf().getFillId(); - ctFill2 = stylesTable.getFillAt(fillId).getCTFill(); - assertNull(ctFill2.getPatternFill()); - } - - @Test - void testGetFont() { - assertNotNull(cellStyle.getFont()); - } - - @Test - void testGetSetHidden() { - assertFalse(cellStyle.getHidden()); - cellStyle.setHidden(true); - assertTrue(cellStyle.getHidden()); - cellStyle.setHidden(false); - assertFalse(cellStyle.getHidden()); - } - - @Test - void testGetSetLocked() { - assertTrue(cellStyle.getLocked()); - cellStyle.setLocked(true); - assertTrue(cellStyle.getLocked()); - cellStyle.setLocked(false); - assertFalse(cellStyle.getLocked()); - } - - @Test - void testGetSetIndent() { - assertEquals((short)0, cellStyle.getIndention()); - cellStyle.setIndention((short)3); - assertEquals((short)3, cellStyle.getIndention()); - cellStyle.setIndention((short) 13); - assertEquals((short)13, cellStyle.getIndention()); - } - - @Test - void testGetSetAlignment() { - assertNull(cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - assertEquals(HorizontalAlignment.GENERAL, cellStyle.getAlignment()); - - cellStyle.setAlignment(HorizontalAlignment.LEFT); - assertEquals(HorizontalAlignment.LEFT, cellStyle.getAlignment()); - assertEquals(STHorizontalAlignment.LEFT, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - - cellStyle.setAlignment(HorizontalAlignment.JUSTIFY); - assertEquals(HorizontalAlignment.JUSTIFY, cellStyle.getAlignment()); - assertEquals(STHorizontalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - - cellStyle.setAlignment(HorizontalAlignment.CENTER); - assertEquals(HorizontalAlignment.CENTER, cellStyle.getAlignment()); - assertEquals(STHorizontalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - } - - @Test - void testGetSetReadingOrder() { - assertEquals(ReadingOrder.CONTEXT, cellStyle.getReadingOrder()); - assertEquals(ReadingOrder.CONTEXT.getCode(), cellStyle.getCellAlignment().getCTCellAlignment().getReadingOrder()); - - cellStyle.setReadingOrder(ReadingOrder.LEFT_TO_RIGHT); - assertEquals(ReadingOrder.LEFT_TO_RIGHT, cellStyle.getReadingOrder()); - assertEquals(ReadingOrder.LEFT_TO_RIGHT.getCode(), cellStyle.getCellAlignment().getCTCellAlignment().getReadingOrder()); - - cellStyle.setReadingOrder(ReadingOrder.RIGHT_TO_LEFT); - assertEquals(ReadingOrder.RIGHT_TO_LEFT, cellStyle.getReadingOrder()); - assertEquals(ReadingOrder.RIGHT_TO_LEFT.getCode(), cellStyle.getCellAlignment().getCTCellAlignment().getReadingOrder()); - - cellStyle.setReadingOrder(ReadingOrder.CONTEXT); - assertEquals(ReadingOrder.CONTEXT, cellStyle.getReadingOrder()); - assertEquals(ReadingOrder.CONTEXT.getCode(), cellStyle.getCellAlignment().getCTCellAlignment().getReadingOrder()); - } - - @Test - void testGetSetVerticalAlignment() { - assertEquals(VerticalAlignment.BOTTOM, cellStyle.getVerticalAlignment()); - assertFalse(cellStyle.getCellAlignment().getCTCellAlignment().isSetVertical()); - assertEquals(STVerticalAlignment.BOTTOM, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); - - cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); - assertEquals(VerticalAlignment.CENTER, cellStyle.getVerticalAlignment()); - assertEquals(STVerticalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); - - cellStyle.setVerticalAlignment(VerticalAlignment.JUSTIFY); - assertEquals(VerticalAlignment.JUSTIFY, cellStyle.getVerticalAlignment()); - assertEquals(STVerticalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); - } - - @Test - void testGetSetWrapText() { - assertFalse(cellStyle.getWrapText()); - cellStyle.setWrapText(true); - assertTrue(cellStyle.getWrapText()); - cellStyle.setWrapText(false); - assertFalse(cellStyle.getWrapText()); - } - - /** - * Cloning one XSSFCellStyle onto Another, same XSSFWorkbook - */ - @Test - void testCloneStyleSameWB() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - assertEquals(1, wb.getNumberOfFonts()); - - XSSFFont fnt = wb.createFont(); - fnt.setFontName("TestingFont"); - assertEquals(2, wb.getNumberOfFonts()); - - XSSFCellStyle orig = wb.createCellStyle(); - orig.setAlignment(HorizontalAlignment.RIGHT); - orig.setFont(fnt); - orig.setDataFormat((short)18); - - assertEquals(HorizontalAlignment.RIGHT, orig.getAlignment()); - assertEquals(fnt, orig.getFont()); - assertEquals(18, orig.getDataFormat()); - - XSSFCellStyle clone = wb.createCellStyle(); - assertNotSame(HorizontalAlignment.RIGHT, clone.getAlignment()); - assertNotSame(fnt, clone.getFont()); - assertNotEquals(18, clone.getDataFormat()); - - clone.cloneStyleFrom(orig); - assertEquals(HorizontalAlignment.RIGHT, clone.getAlignment()); - assertEquals(fnt, clone.getFont()); - assertEquals(18, clone.getDataFormat()); - assertEquals(2, wb.getNumberOfFonts()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wb2); - wb2.close(); - - wb.close(); - } - - /** - * Cloning one XSSFCellStyle onto Another, different XSSFWorkbooks - */ - @Test - void testCloneStyleDiffWB() throws IOException { - XSSFWorkbook wbOrig = new XSSFWorkbook(); - assertEquals(1, wbOrig.getNumberOfFonts()); - assertEquals(0, wbOrig.getStylesSource().getNumberFormats().size()); - - XSSFFont fnt = wbOrig.createFont(); - fnt.setFontName("TestingFont"); - assertEquals(2, wbOrig.getNumberOfFonts()); - assertEquals(0, wbOrig.getStylesSource().getNumberFormats().size()); - - XSSFDataFormat fmt = wbOrig.createDataFormat(); - fmt.getFormat("MadeUpOne"); - fmt.getFormat("MadeUpTwo"); - - XSSFCellStyle orig = wbOrig.createCellStyle(); - orig.setAlignment(HorizontalAlignment.RIGHT); - orig.setFont(fnt); - orig.setDataFormat(fmt.getFormat("Test##")); - orig.setFillPattern(FillPatternType.SOLID_FOREGROUND); - orig.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); - - XSSFCellStyle origEmpty = wbOrig.createCellStyle(); - assertNotNull(origEmpty); - - assertSame(HorizontalAlignment.RIGHT, orig.getAlignment()); - assertSame(fnt, orig.getFont()); - assertEquals(fmt.getFormat("Test##"), orig.getDataFormat()); - - assertEquals(2, wbOrig.getNumberOfFonts()); - assertEquals(3, wbOrig.getStylesSource().getNumberFormats().size()); - - - // Now a style on another workbook - XSSFWorkbook wbClone = new XSSFWorkbook(); - assertEquals(1, wbClone.getNumberOfFonts()); - assertEquals(0, wbClone.getStylesSource().getNumberFormats().size()); - assertEquals(1, wbClone.getNumCellStyles()); - - XSSFDataFormat fmtClone = wbClone.createDataFormat(); - XSSFCellStyle clone = wbClone.createCellStyle(); - - assertEquals(1, wbClone.getNumberOfFonts()); - assertEquals(0, wbClone.getStylesSource().getNumberFormats().size()); - - assertNotSame(HorizontalAlignment.RIGHT, clone.getAlignment()); - assertNotEquals("TestingFont", clone.getFont().getFontName()); - - clone.cloneStyleFrom(orig); - - assertEquals(2, wbClone.getNumberOfFonts()); - assertEquals(2, wbClone.getNumCellStyles()); - assertEquals(1, wbClone.getStylesSource().getNumberFormats().size()); - - assertEquals(HorizontalAlignment.RIGHT, clone.getAlignment()); - 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()); - - // Save it and re-check - XSSFWorkbook wbReload = XSSFTestDataSamples.writeOutAndReadBack(wbClone); - assertEquals(2, wbReload.getNumberOfFonts()); - assertEquals(2, wbReload.getNumCellStyles()); - assertEquals(1, wbReload.getStylesSource().getNumberFormats().size()); - - XSSFCellStyle reload = wbReload.getCellStyleAt((short)1); - assertEquals(HorizontalAlignment.RIGHT, reload.getAlignment()); - 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()); - - XSSFWorkbook wbOrig2 = XSSFTestDataSamples.writeOutAndReadBack(wbOrig); - assertNotNull(wbOrig2); - wbOrig2.close(); - - XSSFWorkbook wbClone2 = XSSFTestDataSamples.writeOutAndReadBack(wbClone); - assertNotNull(wbClone2); - wbClone2.close(); - - wbReload.close(); - wbClone.close(); - wbOrig.close(); - } - - /** - * Avoid ArrayIndexOutOfBoundsException when creating cell style - * in a workbook that has an empty xf table. - */ - @Test - void testBug52348() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("52348.xlsx"); - StylesTable st = workbook.getStylesSource(); - assertEquals(0, st._getStyleXfsSize()); - - XSSFCellStyle style = workbook.createCellStyle(); // no exception at this point - assertNull(style.getStyleXf()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertNotNull(wb2); - wb2.close(); - workbook.close(); - } - - /** - * Avoid ArrayIndexOutOfBoundsException when getting cell style - * in a workbook that has an empty xf table. - */ - @Test - void testBug55650() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("52348.xlsx"); - StylesTable st = workbook.getStylesSource(); - assertEquals(0, st._getStyleXfsSize()); - - // no exception at this point - XSSFCellStyle style = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle(); - assertNull(style.getStyleXf()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertNotNull(wb2); - wb2.close(); - - workbook.close(); - } - - @Test - void testShrinkToFit() throws IOException { - // Existing file - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("ShrinkToFit.xlsx"); - Sheet s = wb1.getSheetAt(0); - Row r = s.getRow(0); - CellStyle cs = r.getCell(0).getCellStyle(); - - assertTrue(cs.getShrinkToFit()); - - // New file - XSSFWorkbook wb2 = new XSSFWorkbook(); - s = wb2.createSheet(); - r = s.createRow(0); - - cs = wb2.createCellStyle(); - cs.setShrinkToFit(false); - r.createCell(0).setCellStyle(cs); - - cs = wb2.createCellStyle(); - cs.setShrinkToFit(true); - r.createCell(1).setCellStyle(cs); - - // Write out, read, and check - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - s = wb3.getSheetAt(0); - r = s.getRow(0); - assertFalse(r.getCell(0).getCellStyle().getShrinkToFit()); - assertTrue(r.getCell(1).getCellStyle().getShrinkToFit()); - - XSSFWorkbook wb4 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - assertNotNull(wb4); - wb4.close(); - - XSSFWorkbook wb5 = XSSFTestDataSamples.writeOutAndReadBack(wb3); - assertNotNull(wb5); - wb5.close(); - - wb3.close(); - wb2.close(); - wb1.close(); - - } - - @Test - void testSetColor() throws IOException { - try(Workbook wb = new XSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - DataFormat format = wb.createDataFormat(); - Cell cell = row.createCell(1); - cell.setCellValue("somevalue"); - CellStyle cellStyle2 = wb.createCellStyle(); - - - cellStyle2.setDataFormat(format.getFormat("###0")); - - cellStyle2.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex()); - cellStyle2.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex()); - cellStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND); - - cellStyle2.setAlignment(HorizontalAlignment.RIGHT); - cellStyle2.setVerticalAlignment(VerticalAlignment.TOP); - - cell.setCellStyle(cellStyle2); - - try (Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { - Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(1); - assertNotNull(cellBack); - CellStyle styleBack = cellBack.getCellStyle(); - assertEquals(IndexedColors.DARK_BLUE.getIndex(), styleBack.getFillBackgroundColor()); - assertEquals(IndexedColors.DARK_BLUE.getIndex(), styleBack.getFillForegroundColor()); - assertEquals(HorizontalAlignment.RIGHT, styleBack.getAlignment()); - assertEquals(VerticalAlignment.TOP, styleBack.getVerticalAlignment()); - assertEquals(FillPatternType.SOLID_FOREGROUND, styleBack.getFillPattern()); - } - } - } - - public static void copyStyles(Workbook reference, Workbook target) { - final int numberOfStyles = reference.getNumCellStyles(); - // don't copy default style (style index 0) - for (int i = 1; i < numberOfStyles; i++) { - final CellStyle referenceStyle = reference.getCellStyleAt(i); - final CellStyle targetStyle = target.createCellStyle(); - targetStyle.cloneStyleFrom(referenceStyle); - } - /*System.out.println("Reference : "+reference.getNumCellStyles()); - System.out.println("Target : "+target.getNumCellStyles());*/ - } - - @Test - void test58084() throws IOException { - Workbook reference = XSSFTestDataSamples.openSampleWorkbook("template.xlsx"); - Workbook target = new XSSFWorkbook(); - copyStyles(reference, target); - - assertEquals(reference.getNumCellStyles(), target.getNumCellStyles()); - final Sheet sheet = target.createSheet(); - final Row row = sheet.createRow(0); - int col = 0; - for (short i = 1; i < target.getNumCellStyles(); i++) { - final Cell cell = row.createCell(col++); - 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); - - // previously this failed because the border-element was not copied over - copy.getCellStyleAt((short)1).getBorderBottom(); - - copy.close(); - - target.close(); - reference.close(); - } - - @Test - void test58043() { - assertEquals(0, cellStyle.getRotation()); - - cellStyle.setRotation((short)89); - assertEquals(89, cellStyle.getRotation()); - - cellStyle.setRotation((short)90); - assertEquals(90, cellStyle.getRotation()); - - cellStyle.setRotation((short)179); - assertEquals(179, cellStyle.getRotation()); - - cellStyle.setRotation((short)180); - assertEquals(180, cellStyle.getRotation()); - - // negative values are mapped to the correct values for compatibility between HSSF and XSSF - cellStyle.setRotation((short)-1); - assertEquals(91, cellStyle.getRotation()); - - cellStyle.setRotation((short)-89); - assertEquals(179, cellStyle.getRotation()); - - cellStyle.setRotation((short)-90); - assertEquals(180, cellStyle.getRotation()); - } - - @Test - void bug58996_UsedToWorkIn3_11_ButNotIn3_13() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - - XSSFCellStyle cellStyle = workbook.createCellStyle(); - cellStyle.setFillForegroundColor(null); - assertNull(cellStyle.getFillForegroundColorColor()); - - cellStyle.setFillBackgroundColor(null); - assertNull(cellStyle.getFillBackgroundColorColor()); - - cellStyle.setFillPattern(FillPatternType.NO_FILL); - assertEquals(FillPatternType.NO_FILL, cellStyle.getFillPattern()); - - cellStyle.setBottomBorderColor(null); - assertNull(cellStyle.getBottomBorderXSSFColor()); - - cellStyle.setTopBorderColor(null); - assertNull(cellStyle.getTopBorderXSSFColor()); - - cellStyle.setLeftBorderColor(null); - assertNull(cellStyle.getLeftBorderXSSFColor()); - - cellStyle.setRightBorderColor(null); - assertNull(cellStyle.getRightBorderXSSFColor()); - - workbook.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java deleted file mode 100644 index 7f6978683f..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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 java.io.IOException; - -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -public final class TestXSSFChart { - @Test - void testGetAccessors() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx")) { - XSSFSheet s1 = wb.getSheetAt(0); - XSSFSheet s2 = wb.getSheetAt(1); - XSSFSheet s3 = wb.getSheetAt(2); - - assertEquals(0, s1.getRelations().size()); - assertEquals(1, s2.getRelations().size()); - assertEquals(1, s3.getRelations().size()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } - } - - @Test - void testGetCharts() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx")) { - XSSFSheet s1 = wb.getSheetAt(0); - XSSFSheet s2 = wb.getSheetAt(1); - XSSFSheet s3 = wb.getSheetAt(2); - - assertEquals(0, s1.createDrawingPatriarch().getCharts().size()); - assertEquals(2, s2.createDrawingPatriarch().getCharts().size()); - assertEquals(1, s3.createDrawingPatriarch().getCharts().size()); - - // Check the titles - XSSFChart chart = s2.createDrawingPatriarch().getCharts().get(0); - assertNull(chart.getTitleText()); - - chart = s2.createDrawingPatriarch().getCharts().get(1); - XSSFRichTextString title = chart.getTitleText(); - assertNotNull(title); - assertEquals("Pie Chart Title Thingy", title.getString()); - - chart = s3.createDrawingPatriarch().getCharts().get(0); - title = chart.getTitleText(); - assertNotNull(title); - assertEquals("Sheet 3 Chart with Title", title.getString()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } - } - - @Test - void testAddChartsToNewWorkbook() throws Exception { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet s1 = wb.createSheet(); - XSSFDrawing d1 = s1.createDrawingPatriarch(); - XSSFClientAnchor a1 = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart c1 = d1.createChart(a1); - - assertEquals(1, d1.getCharts().size()); - - assertNotNull(c1.getGraphicFrame()); - assertNotNull(c1.getOrAddLegend()); - - XSSFClientAnchor a2 = new XSSFClientAnchor(0, 0, 0, 0, 1, 11, 10, 60); - XSSFChart c2 = d1.createChart(a2); - assertNotNull(c2); - assertEquals(2, d1.getCharts().size()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java deleted file mode 100644 index a97ca36e94..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java +++ /dev/null @@ -1,85 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTChartsheet; - -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.*; - -public final class TestXSSFChartSheet { - - @Test - void testXSSFFactory() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx")) { - assertEquals(4, wb.getNumberOfSheets()); - - //the third sheet is of type 'chartsheet' - assertEquals("Chart1", wb.getSheetName(2)); - assertTrue(wb.getSheetAt(2) instanceof XSSFChartSheet); - assertEquals("Chart1", wb.getSheetAt(2).getSheetName()); - - final CTChartsheet ctChartsheet = ((XSSFChartSheet) wb.getSheetAt(2)).getCTChartsheet(); - assertNotNull(ctChartsheet); - } - } - - @Test - void testGetAccessors() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx")) { - XSSFChartSheet sheet = (XSSFChartSheet) wb.getSheetAt(2); - - assertFalse(sheet.iterator().hasNext(), "Row iterator for charts sheets should return zero rows"); - - //access to a arbitrary row - assertNull(sheet.getRow(1)); - - //some basic get* accessors - assertEquals(0, sheet.getNumberOfComments()); - assertEquals(0, sheet.getNumHyperlinks()); - assertEquals(0, sheet.getNumMergedRegions()); - assertNull(sheet.getActiveCell()); - assertTrue(sheet.getAutobreaks()); - assertNull(sheet.getCellComment(new CellAddress(0, 0))); - assertEquals(0, sheet.getColumnBreaks().length); - assertTrue(sheet.getRowSumsBelow()); - assertNotNull(sheet.createDrawingPatriarch()); - assertNotNull(sheet.getDrawingPatriarch()); - assertNotNull(sheet.getCTChartsheet()); - } - } - - @Test - void testGetCharts() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx")) { - - XSSFSheet ns = wb.getSheetAt(0); - XSSFChartSheet cs = (XSSFChartSheet) wb.getSheetAt(2); - - assertEquals(0, ns.createDrawingPatriarch().getCharts().size()); - assertEquals(1, cs.createDrawingPatriarch().getCharts().size()); - - XSSFChart chart = cs.createDrawingPatriarch().getCharts().get(0); - assertNull(chart.getTitleText()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java deleted file mode 100644 index 227dc3627b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java +++ /dev/null @@ -1,304 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.assertTrue; - -import java.io.IOException; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; - -/** - * Test asserts the POI produces <cols> element that could be read and properly interpreted by the MS Excel. - * For specification of the "cols" element see the chapter 3.3.1.16 of the "Office Open XML Part 4 - Markup Language Reference.pdf". - * The specification can be downloaded at http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%204%20(PDF).zip. - * - * <p><em> - * The test saves xlsx file on a disk if the system property is set: - * -Dpoi.test.xssf.output.dir=${workspace_loc}/poi/build/xssf-output - * </em> - * - */ -class TestXSSFColGrouping { - - private static final Logger LOG = LogManager.getLogger(TestXSSFColGrouping.class); - - - /** - * Tests that POI doesn't produce "col" elements without "width" attribute. - * POI-52186 - */ - @Test - void testNoColsWithoutWidthWhenGrouping() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - XSSFSheet sheet = wb1.createSheet("test"); - - sheet.setColumnWidth(4, 5000); - sheet.setColumnWidth(5, 5000); - - sheet.groupColumn((short) 4, (short) 7); - sheet.groupColumn((short) 9, (short) 12); - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGrouping")) { - sheet = wb2.getSheet("test"); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - LOG.atDebug().log("test52186/cols:{}", cols); - for (CTCol col : cols.getColArray()) { - assertTrue(col.isSetWidth(), "Col width attribute is unset: " + col); - } - - } - } - } - - /** - * Tests that POI doesn't produce "col" elements without "width" attribute. - * POI-52186 - */ - @Test - void testNoColsWithoutWidthWhenGroupingAndCollapsing() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - XSSFSheet sheet = wb1.createSheet("test"); - - sheet.setColumnWidth(4, 5000); - sheet.setColumnWidth(5, 5000); - - sheet.groupColumn((short) 4, (short) 5); - - sheet.setColumnGroupCollapsed(4, true); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - LOG.atDebug().log("test52186_2/cols:{}", cols); - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGroupingAndCollapsing")) { - sheet = wb2.getSheet("test"); - - for (int i = 4; i <= 5; i++) { - assertEquals(5000, sheet.getColumnWidth(i), "Unexpected width of column " + i); - } - cols = sheet.getCTWorksheet().getColsArray(0); - for (CTCol col : cols.getColArray()) { - assertTrue(col.isSetWidth(), "Col width attribute is unset: " + col); - } - } - } - } - - /** - * Test the cols element is correct in case of NumericRanges.OVERLAPS_2_WRAPS - */ - @Test - void testMergingOverlappingCols_OVERLAPS_2_WRAPS() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - XSSFSheet sheet = wb1.createSheet("test"); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(1 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); - - sheet.groupColumn((short) 2, (short) 3); - - sheet.getCTWorksheet().getColsArray(0); - LOG.atDebug().log("testMergingOverlappingCols_OVERLAPS_2_WRAPS/cols:{}", cols); - - assertEquals(0, cols.getColArray(0).getOutlineLevel()); - assertEquals(2, cols.getColArray(0).getMin()); // 1 based - assertEquals(2, cols.getColArray(0).getMax()); // 1 based - assertTrue(cols.getColArray(0).getCustomWidth()); - - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(3, cols.getColArray(1).getMin()); // 1 based - assertEquals(4, cols.getColArray(1).getMax()); // 1 based - assertTrue(cols.getColArray(1).getCustomWidth()); - - assertEquals(0, cols.getColArray(2).getOutlineLevel()); - assertEquals(5, cols.getColArray(2).getMin()); // 1 based - assertEquals(5, cols.getColArray(2).getMax()); // 1 based - assertTrue(cols.getColArray(2).getCustomWidth()); - - assertEquals(3, cols.sizeOfColArray()); - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_WRAPS")) { - sheet = wb2.getSheet("test"); - - for (int i = 1; i <= 4; i++) { - assertEquals(20 * 256, sheet.getColumnWidth(i), "Unexpected width of column " + i); - } - - } - } - } - - /** - * Test the cols element is correct in case of NumericRanges.OVERLAPS_1_WRAPS - */ - @Test - void testMergingOverlappingCols_OVERLAPS_1_WRAPS() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - XSSFSheet sheet = wb1.createSheet("test"); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(2 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); - - sheet.groupColumn((short) 1, (short) 5); - - cols = sheet.getCTWorksheet().getColsArray(0); - LOG.atDebug().log("testMergingOverlappingCols_OVERLAPS_1_WRAPS/cols:{}", cols); - - assertEquals(1, cols.getColArray(0).getOutlineLevel()); - assertEquals(2, cols.getColArray(0).getMin()); // 1 based - assertEquals(2, cols.getColArray(0).getMax()); // 1 based - assertFalse(cols.getColArray(0).getCustomWidth()); - - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(3, cols.getColArray(1).getMin()); // 1 based - assertEquals(5, cols.getColArray(1).getMax()); // 1 based - assertTrue(cols.getColArray(1).getCustomWidth()); - - assertEquals(1, cols.getColArray(2).getOutlineLevel()); - assertEquals(6, cols.getColArray(2).getMin()); // 1 based - assertEquals(6, cols.getColArray(2).getMax()); // 1 based - assertFalse(cols.getColArray(2).getCustomWidth()); - - assertEquals(3, cols.sizeOfColArray()); - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_WRAPS")) { - sheet = wb2.getSheet("test"); - - for (int i = 2; i <= 4; i++) { - assertEquals(20 * 256, sheet.getColumnWidth(i), "Unexpected width of column " + i); - } - - } - } - } - - /** - * Test the cols element is correct in case of NumericRanges.OVERLAPS_1_MINOR - */ - @Test - void testMergingOverlappingCols_OVERLAPS_1_MINOR() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - XSSFSheet sheet = wb1.createSheet("test"); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(2 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); - - sheet.groupColumn((short) 3, (short) 5); - - cols = sheet.getCTWorksheet().getColsArray(0); - LOG.atDebug().log("testMergingOverlappingCols_OVERLAPS_1_MINOR/cols:{}", cols); - - assertEquals(0, cols.getColArray(0).getOutlineLevel()); - assertEquals(3, cols.getColArray(0).getMin()); // 1 based - assertEquals(3, cols.getColArray(0).getMax()); // 1 based - assertTrue(cols.getColArray(0).getCustomWidth()); - - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(4, cols.getColArray(1).getMin()); // 1 based - assertEquals(5, cols.getColArray(1).getMax()); // 1 based - assertTrue(cols.getColArray(1).getCustomWidth()); - - assertEquals(1, cols.getColArray(2).getOutlineLevel()); - assertEquals(6, cols.getColArray(2).getMin()); // 1 based - assertEquals(6, cols.getColArray(2).getMax()); // 1 based - assertFalse(cols.getColArray(2).getCustomWidth()); - - assertEquals(3, cols.sizeOfColArray()); - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_MINOR")) { - sheet = wb2.getSheet("test"); - - for (int i = 2; i <= 4; i++) { - assertEquals(20 * 256L, sheet.getColumnWidth(i), "Unexpected width of column " + i); - } - assertEquals(sheet.getDefaultColumnWidth() * 256L, sheet.getColumnWidth(5), "Unexpected width of column " + 5); - - } - } - } - - /** - * Test the cols element is correct in case of NumericRanges.OVERLAPS_2_MINOR - */ - @Test - void testMergingOverlappingCols_OVERLAPS_2_MINOR() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - XSSFSheet sheet = wb1.createSheet("test"); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(2 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); - - sheet.groupColumn((short) 1, (short) 3); - - cols = sheet.getCTWorksheet().getColsArray(0); - LOG.atDebug().log("testMergingOverlappingCols_OVERLAPS_2_MINOR/cols:{}", cols); - - assertEquals(1, cols.getColArray(0).getOutlineLevel()); - assertEquals(2, cols.getColArray(0).getMin()); // 1 based - assertEquals(2, cols.getColArray(0).getMax()); // 1 based - assertFalse(cols.getColArray(0).getCustomWidth()); - - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(3, cols.getColArray(1).getMin()); // 1 based - assertEquals(4, cols.getColArray(1).getMax()); // 1 based - assertTrue(cols.getColArray(1).getCustomWidth()); - - assertEquals(0, cols.getColArray(2).getOutlineLevel()); - assertEquals(5, cols.getColArray(2).getMin()); // 1 based - assertEquals(5, cols.getColArray(2).getMax()); // 1 based - assertTrue(cols.getColArray(2).getCustomWidth()); - - assertEquals(3, cols.sizeOfColArray()); - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_MINOR")) { - sheet = wb2.getSheet("test"); - - for (int i = 2; i <= 4; i++) { - assertEquals(20 * 256L, sheet.getColumnWidth(i), "Unexpected width of column " + i); - } - assertEquals(sheet.getDefaultColumnWidth() * 256L, sheet.getColumnWidth(1), "Unexpected width of column " + 1); - - } - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java deleted file mode 100644 index 88c54d7386..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java +++ /dev/null @@ -1,201 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColors; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRgbColor; - -public final class TestXSSFColor { - - @Test - void testIndexedColour() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) { - // Check the CTColor is as expected - XSSFColor indexed = wb.getCellStyleAt(1).getFillBackgroundXSSFColor(); - assertTrue(indexed.getCTColor().isSetIndexed()); - assertEquals(64, indexed.getCTColor().getIndexed()); - assertFalse(indexed.getCTColor().isSetRgb()); - assertNull(indexed.getCTColor().getRgb()); - - // Now check the XSSFColor - // Note - 64 is a special "auto" one with no rgb equiv - assertEquals(64, indexed.getIndexed()); - assertNull(indexed.getRGB()); - assertNull(indexed.getRGBWithTint()); - assertNull(indexed.getARGBHex()); - assertFalse(indexed.hasAlpha()); - assertFalse(indexed.hasTint()); - - // Now move to one with indexed rgb values - indexed.setIndexed(59); - assertTrue(indexed.getCTColor().isSetIndexed()); - assertEquals(59, indexed.getCTColor().getIndexed()); - assertFalse(indexed.getCTColor().isSetRgb()); - assertNull(indexed.getCTColor().getRgb()); - - assertEquals(59, indexed.getIndexed()); - assertEquals("FF333300", indexed.getARGBHex()); - - assertEquals(3, indexed.getRGB().length); - assertEquals(0x33, indexed.getRGB()[0]); - assertEquals(0x33, indexed.getRGB()[1]); - assertEquals(0x00, indexed.getRGB()[2]); - - assertEquals(4, indexed.getARGB().length); - assertEquals(-1, indexed.getARGB()[0]); - assertEquals(0x33, indexed.getARGB()[1]); - assertEquals(0x33, indexed.getARGB()[2]); - assertEquals(0x00, indexed.getARGB()[3]); - - // You don't get tinted indexed colours, sorry... - assertNull(indexed.getRGBWithTint()); - } - } - - @Test - void testRGBColour() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx")) { - - // Check the CTColor is as expected - XSSFColor rgb3 = wb.getCellStyleAt((short) 25).getFillForegroundXSSFColor(); - assertFalse(rgb3.getCTColor().isSetIndexed()); - assertEquals(0, rgb3.getCTColor().getIndexed()); - assertTrue(rgb3.getCTColor().isSetTint()); - assertEquals(-0.34999, rgb3.getCTColor().getTint(), 0.00001); - assertTrue(rgb3.getCTColor().isSetRgb()); - assertEquals(3, rgb3.getCTColor().getRgb().length); - - // Now check the XSSFColor - assertEquals(0, rgb3.getIndexed()); - assertEquals(-0.34999, rgb3.getTint(), 0.00001); - assertFalse(rgb3.hasAlpha()); - assertTrue(rgb3.hasTint()); - - assertEquals("FFFFFFFF", rgb3.getARGBHex()); - assertEquals(3, rgb3.getRGB().length); - assertEquals(-1, rgb3.getRGB()[0]); - assertEquals(-1, rgb3.getRGB()[1]); - assertEquals(-1, rgb3.getRGB()[2]); - - assertEquals(4, rgb3.getARGB().length); - assertEquals(-1, rgb3.getARGB()[0]); - assertEquals(-1, rgb3.getARGB()[1]); - assertEquals(-1, rgb3.getARGB()[2]); - assertEquals(-1, rgb3.getARGB()[3]); - - // Tint doesn't have the alpha - // tint = -0.34999 - // 255 * (1 + tint) = 165 truncated - // or (byte) -91 (which is 165 - 256) - assertEquals(3, rgb3.getRGBWithTint().length); - assertEquals(-91, rgb3.getRGBWithTint()[0]); - assertEquals(-91, rgb3.getRGBWithTint()[1]); - assertEquals(-91, rgb3.getRGBWithTint()[2]); - - // Set the color to black (no theme). - rgb3.setRGB(new byte[]{0, 0, 0}); - assertEquals("FF000000", rgb3.getARGBHex()); - assertEquals(0, rgb3.getCTColor().getRgb()[0]); - assertEquals(0, rgb3.getCTColor().getRgb()[1]); - assertEquals(0, rgb3.getCTColor().getRgb()[2]); - - // Set another, is fine - rgb3.setRGB(new byte[]{16, 17, 18}); - assertFalse(rgb3.hasAlpha()); - assertEquals("FF101112", rgb3.getARGBHex()); - assertEquals(0x10, rgb3.getCTColor().getRgb()[0]); - assertEquals(0x11, rgb3.getCTColor().getRgb()[1]); - assertEquals(0x12, rgb3.getCTColor().getRgb()[2]); - } - } - - @Test - void testARGBColour() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) { - - // Check the CTColor is as expected - XSSFColor rgb4 = wb.getCellStyleAt((short) 1).getFillForegroundXSSFColor(); - assertFalse(rgb4.getCTColor().isSetIndexed()); - assertEquals(0, rgb4.getCTColor().getIndexed()); - assertTrue(rgb4.getCTColor().isSetRgb()); - assertEquals(4, rgb4.getCTColor().getRgb().length); - - // Now check the XSSFColor - assertEquals(0, rgb4.getIndexed()); - assertEquals(0.0, rgb4.getTint(), 0); - assertFalse(rgb4.hasTint()); - assertTrue(rgb4.hasAlpha()); - - assertEquals("FFFF0000", rgb4.getARGBHex()); - assertEquals(3, rgb4.getRGB().length); - assertEquals(-1, rgb4.getRGB()[0]); - assertEquals(0, rgb4.getRGB()[1]); - assertEquals(0, rgb4.getRGB()[2]); - - assertEquals(4, rgb4.getARGB().length); - assertEquals(-1, rgb4.getARGB()[0]); - assertEquals(-1, rgb4.getARGB()[1]); - assertEquals(0, rgb4.getARGB()[2]); - assertEquals(0, rgb4.getARGB()[3]); - - // Tint doesn't have the alpha - assertEquals(3, rgb4.getRGBWithTint().length); - assertEquals(-1, rgb4.getRGBWithTint()[0]); - assertEquals(0, rgb4.getRGBWithTint()[1]); - assertEquals(0, rgb4.getRGBWithTint()[2]); - - - // Turn on tinting, and check it behaves - // TODO These values are suspected to be wrong... - rgb4.setTint(0.4); - assertTrue(rgb4.hasTint()); - assertEquals(0.4, rgb4.getTint(), 0); - - assertEquals(3, rgb4.getRGBWithTint().length); - assertEquals(-1, rgb4.getRGBWithTint()[0]); - assertEquals(102, rgb4.getRGBWithTint()[1]); - assertEquals(102, rgb4.getRGBWithTint()[2]); - } - } - - @Test - void testCustomIndexedColour() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("customIndexedColors.xlsx")) { - XSSFCell cell = wb.getSheetAt(1).getRow(0).getCell(0); - XSSFColor color = cell.getCellStyle().getFillForegroundColorColor(); - CTColors ctColors = wb.getStylesSource().getCTStylesheet().getColors(); - - CTRgbColor ctRgbColor = ctColors.getIndexedColors() - .getRgbColorList() - .get(color.getIndex()); - - String hexRgb = ctRgbColor.getDomNode().getAttributes().getNamedItem("rgb").getNodeValue(); - - assertEquals(hexRgb, color.getARGBHex()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java deleted file mode 100644 index aea85b4cc1..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java +++ /dev/null @@ -1,314 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; -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.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; - -import com.microsoft.schemas.vml.CTShape; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.ss.usermodel.BaseTestCellComment; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.CreationHelper; -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.util.CellAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.xmlbeans.XmlObject; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComment; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt; - -public final class TestXSSFComment extends BaseTestCellComment { - - private static final String TEST_RICHTEXTSTRING = "test richtextstring"; - - public TestXSSFComment() { - super(XSSFITestDataProvider.instance); - } - - /** - * test properties of a newly constructed comment - */ - @Test - void constructor() { - CommentsTable sheetComments = new CommentsTable(); - assertNotNull(sheetComments.getCTComments().getCommentList()); - assertNotNull(sheetComments.getCTComments().getAuthors()); - assertEquals(1, sheetComments.getCTComments().getAuthors().sizeOfAuthorArray()); - assertEquals(1, sheetComments.getNumberOfAuthors()); - - CTComment ctComment = sheetComments.newComment(CellAddress.A1); - CTShape vmlShape = CTShape.Factory.newInstance(); - - XSSFComment comment = new XSSFComment(sheetComments, ctComment, vmlShape); - assertNull(comment.getString()); - assertEquals(0, comment.getRow()); - assertEquals(0, comment.getColumn()); - assertEquals("", comment.getAuthor()); - assertFalse(comment.isVisible()); - } - - @Test - void getSetCol() { - CommentsTable sheetComments = new CommentsTable(); - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - CTComment ctComment = sheetComments.newComment(CellAddress.A1); - CTShape vmlShape = vml.newCommentShape(); - - XSSFComment comment = new XSSFComment(sheetComments, ctComment, vmlShape); - comment.setColumn(1); - assertEquals(1, comment.getColumn()); - assertEquals(1, new CellReference(ctComment.getRef()).getCol()); - assertEquals(1, vmlShape.getClientDataArray(0).getColumnArray(0).intValue()); - - comment.setColumn(5); - assertEquals(5, comment.getColumn()); - assertEquals(5, new CellReference(ctComment.getRef()).getCol()); - assertEquals(5, vmlShape.getClientDataArray(0).getColumnArray(0).intValue()); - } - - @Test - void getSetRow() { - CommentsTable sheetComments = new CommentsTable(); - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - CTComment ctComment = sheetComments.newComment(CellAddress.A1); - CTShape vmlShape = vml.newCommentShape(); - - XSSFComment comment = new XSSFComment(sheetComments, ctComment, vmlShape); - comment.setRow(1); - assertEquals(1, comment.getRow()); - assertEquals(1, new CellReference(ctComment.getRef()).getRow()); - assertEquals(1, vmlShape.getClientDataArray(0).getRowArray(0).intValue()); - - comment.setRow(5); - assertEquals(5, comment.getRow()); - assertEquals(5, new CellReference(ctComment.getRef()).getRow()); - assertEquals(5, vmlShape.getClientDataArray(0).getRowArray(0).intValue()); - } - - @Test - void setString() { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sh = wb.createSheet(); - XSSFComment comment = sh.createDrawingPatriarch().createCellComment(new XSSFClientAnchor()); - - //passing HSSFRichTextString is incorrect - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, - () -> comment.setString(new HSSFRichTextString(TEST_RICHTEXTSTRING))); - assertEquals("Only XSSFRichTextString argument is supported", e.getMessage()); - - //simple string argument - comment.setString(TEST_RICHTEXTSTRING); - assertEquals(TEST_RICHTEXTSTRING, comment.getString().getString()); - - //if the text is already set, it should be overridden, not added twice! - comment.setString(TEST_RICHTEXTSTRING); - - CTComment ctComment = comment.getCTComment(); - XmlObject[] obj = ctComment.selectPath( - "declare namespace w='"+NS_SPREADSHEETML+"' .//w:text"); - assertEquals(1, obj.length); - assertEquals(TEST_RICHTEXTSTRING, comment.getString().getString()); - - //sequential call of comment.getString() should return the same XSSFRichTextString object - assertSame(comment.getString(), comment.getString()); - - XSSFRichTextString richText = new XSSFRichTextString(TEST_RICHTEXTSTRING); - XSSFFont font1 = wb.createFont(); - font1.setFontName("Tahoma"); - font1.setFontHeight(8.5); - font1.setItalic(true); - font1.setColor(IndexedColors.BLUE_GREY.getIndex()); - richText.applyFont(0, 5, font1); - - //check the low-level stuff - comment.setString(richText); - obj = ctComment.selectPath( - "declare namespace w='"+NS_SPREADSHEETML+"' .//w:text"); - assertEquals(1, obj.length); - assertSame(comment.getString(), richText); - //check that the rich text is set in the comment - CTRPrElt rPr = richText.getCTRst().getRArray(0).getRPr(); - assertTrue(rPr.getIArray(0).getVal()); - assertEquals(8.5, rPr.getSzArray(0).getVal(), 0); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), rPr.getColorArray(0).getIndexed()); - assertEquals("Tahoma", rPr.getRFontArray(0).getVal()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } - - @Test - void author() { - CommentsTable sheetComments = new CommentsTable(); - CTComment ctComment = sheetComments.newComment(CellAddress.A1); - - assertEquals(1, sheetComments.getNumberOfAuthors()); - XSSFComment comment = new XSSFComment(sheetComments, ctComment, null); - assertEquals("", comment.getAuthor()); - comment.setAuthor("Apache POI"); - assertEquals("Apache POI", comment.getAuthor()); - assertEquals(2, sheetComments.getNumberOfAuthors()); - comment.setAuthor("Apache POI"); - assertEquals(2, sheetComments.getNumberOfAuthors()); - comment.setAuthor(""); - assertEquals("", comment.getAuthor()); - assertEquals(2, sheetComments.getNumberOfAuthors()); - } - - @Test - void testBug58175() throws IOException { - try (SXSSFWorkbook wb = new SXSSFWorkbook()) { - Sheet sheet = wb.createSheet(); - - Row row = sheet.createRow(1); - Cell cell = row.createCell(3); - - cell.setCellValue("F4"); - - CreationHelper factory = wb.getCreationHelper(); - - // When the comment box is visible, have it show in a 1x3 space - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(cell.getColumnIndex()); - anchor.setCol2(cell.getColumnIndex() + 1); - anchor.setRow1(row.getRowNum()); - anchor.setRow2(row.getRowNum() + 3); - - XSSFClientAnchor ca = (XSSFClientAnchor) anchor; - - // create comments and vmlDrawing parts if they don't exist - CommentsTable comments = wb.getXSSFWorkbook() - .getSheetAt(0).getCommentsTable(true); - XSSFVMLDrawing vml = wb.getXSSFWorkbook() - .getSheetAt(0).getVMLDrawing(true); - CTShape vmlShape1 = vml.newCommentShape(); - if (ca.isSet()) { - String position = ca.getCol1() + ", 0, " + ca.getRow1() - + ", 0, " + ca.getCol2() + ", 0, " + ca.getRow2() - + ", 0"; - vmlShape1.getClientDataArray(0).setAnchorArray(0, position); - } - - // create the comment in two different ways and verify that there is no difference - XSSFComment shape1 = new XSSFComment(comments, comments.newComment(CellAddress.A1), vmlShape1); - shape1.setColumn(ca.getCol1()); - shape1.setRow(ca.getRow1()); - - CTShape vmlShape2 = vml.newCommentShape(); - if (ca.isSet()) { - String position = ca.getCol1() + ", 0, " + ca.getRow1() - + ", 0, " + ca.getCol2() + ", 0, " + ca.getRow2() - + ", 0"; - vmlShape2.getClientDataArray(0).setAnchorArray(0, position); - } - - CellAddress ref = new CellAddress(ca.getRow1(), ca.getCol1()); - XSSFComment shape2 = new XSSFComment(comments, comments.newComment(ref), vmlShape2); - - assertEquals(shape1.getAuthor(), shape2.getAuthor()); - assertEquals(shape1.getClientAnchor(), shape2.getClientAnchor()); - assertEquals(shape1.getColumn(), shape2.getColumn()); - assertEquals(shape1.getRow(), shape2.getRow()); - assertEquals(shape1.getCTComment().toString(), shape2.getCTComment().toString()); - assertEquals(shape1.getCTComment().getRef(), shape2.getCTComment().getRef()); - - /*CommentsTable table1 = shape1.getCommentsTable(); - CommentsTable table2 = shape2.getCommentsTable(); - assertEquals(table1.getCTComments().toString(), table2.getCTComments().toString()); - assertEquals(table1.getNumberOfComments(), table2.getNumberOfComments()); - assertEquals(table1.getRelations(), table2.getRelations());*/ - - assertEquals(vmlShape1.toString().replaceAll("_x0000_s\\d+", "_x0000_s0000"), vmlShape2.toString().replaceAll("_x0000_s\\d+", "_x0000_s0000"), - "The vmlShapes should have equal content afterwards"); - } - } - - @Test - void testBug55814() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55814.xlsx")) { - - int oldsheetIndex = wb.getSheetIndex("example"); - Sheet oldsheet = wb.getSheetAt(oldsheetIndex); - - Comment comment = oldsheet.getRow(0).getCell(0).getCellComment(); - assertEquals("Comment Here\n", comment.getString().getString()); - - Sheet newsheet = wb.cloneSheet(oldsheetIndex); - - wb.removeSheetAt(oldsheetIndex); - - //wb.write(new FileOutputStream("/tmp/outnocomment.xlsx")); - - comment = newsheet.getRow(0).getCell(0).getCellComment(); - assertNotNull(comment, "Should have a comment on A1 in the new sheet"); - assertEquals("Comment Here\n", comment.getString().getString()); - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wbBack); - wbBack.close(); - } - - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55814.xlsx")) { - int oldsheetIndex = wb.getSheetIndex("example"); - Sheet newsheet = wb.getSheetAt(oldsheetIndex); - Comment comment = newsheet.getRow(0).getCell(0).getCellComment(); - assertEquals("Comment Here\n", comment.getString().getString()); - } - } - - @Test - void bug57838DeleteRowsWthCommentsBug() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57838.xlsx"); - Sheet sheet=wb.getSheetAt(0); - Comment comment1 = sheet.getCellComment(new CellAddress(2, 1)); - assertNotNull(comment1); - Comment comment2 = sheet.getCellComment(new CellAddress(2, 2)); - assertNotNull(comment2); - Row row=sheet.getRow(2); - assertNotNull(row); - - sheet.removeRow(row); // Remove row from index 2 - - row=sheet.getRow(2); - assertNull(row); // Row is null since we deleted it. - - comment1 = sheet.getCellComment(new CellAddress(2, 1)); - assertNull(comment1); // comment should be null but will fail due to bug - comment2 = sheet.getCellComment(new CellAddress(2, 2)); - assertNull(comment2); // comment should be null but will fail due to bug - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFConditionalFormatting.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFConditionalFormatting.java deleted file mode 100644 index 30d92dda2f..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFConditionalFormatting.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestConditionalFormatting; -import org.apache.poi.ss.usermodel.Color; -import org.apache.poi.ss.usermodel.ConditionalFormatting; -import org.apache.poi.ss.usermodel.ConditionalFormattingRule; -import org.apache.poi.ss.usermodel.ExtendedColor; -import org.apache.poi.ss.usermodel.FontFormatting; -import org.apache.poi.ss.usermodel.PatternFormatting; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.SheetConditionalFormatting; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.jupiter.api.Test; - -/** - * XSSF-specific Conditional Formatting tests - */ -class TestXSSFConditionalFormatting extends BaseTestConditionalFormatting { - - public TestXSSFConditionalFormatting(){ - super(XSSFITestDataProvider.instance); - } - - @Override - protected void assertColor(String hexExpected, Color actual) { - assertNotNull(actual, "Color must be given"); - XSSFColor color = (XSSFColor)actual; - if (hexExpected.length() == 8) { - assertEquals(hexExpected, color.getARGBHex()); - } else { - assertEquals(hexExpected, color.getARGBHex().substring(2)); - } - } - - @Test - void testRead() throws IOException { - testRead("WithConditionalFormatting.xlsx"); - } - - @Test - void testReadOffice2007() throws IOException { - testReadOffice2007("NewStyleConditionalFormattings.xlsx"); - } - - private static final java.awt.Color PEAK_ORANGE = new java.awt.Color(255, 239, 221); - - @Test - void testFontFormattingColor() { - XSSFWorkbook wb = XSSFITestDataProvider.instance.createWorkbook(); - final Sheet sheet = wb.createSheet(); - - final SheetConditionalFormatting formatting = sheet.getSheetConditionalFormatting(); - - // the conditional formatting is not automatically added when it is created... - assertEquals(0, formatting.getNumConditionalFormattings()); - ConditionalFormattingRule formattingRule = formatting.createConditionalFormattingRule("A1"); - assertEquals(0, formatting.getNumConditionalFormattings()); - - // adding the formatting makes it available - int idx = formatting.addConditionalFormatting(new CellRangeAddress[] {}, formattingRule); - - // verify that it can be accessed now - assertEquals(0, idx); - assertEquals(1, formatting.getNumConditionalFormattings()); - assertEquals(1, formatting.getConditionalFormattingAt(idx).getNumberOfRules()); - - // this is confusing: the rule is not connected to the sheet, changes are not applied - // so we need to use setRule() explicitly! - FontFormatting fontFmt = formattingRule.createFontFormatting(); - assertNotNull(formattingRule.getFontFormatting()); - assertEquals(1, formatting.getConditionalFormattingAt(idx).getNumberOfRules()); - formatting.getConditionalFormattingAt(idx).setRule(0, formattingRule); - assertNotNull(formatting.getConditionalFormattingAt(idx).getRule(0).getFontFormatting()); - - fontFmt.setFontStyle(true, false); - - assertEquals(-1, fontFmt.getFontColorIndex()); - - //fontFmt.setFontColorIndex((short)11); - final ExtendedColor extendedColor = new XSSFColor(PEAK_ORANGE, wb.getStylesSource().getIndexedColors()); - fontFmt.setFontColor(extendedColor); - - PatternFormatting patternFmt = formattingRule.createPatternFormatting(); - assertNotNull(patternFmt); - patternFmt.setFillBackgroundColor(extendedColor); - - assertEquals(1, formatting.getConditionalFormattingAt(0).getNumberOfRules()); - assertNotNull(formatting.getConditionalFormattingAt(0).getRule(0).getFontFormatting()); - assertNotNull(formatting.getConditionalFormattingAt(0).getRule(0).getFontFormatting().getFontColor()); - assertNotNull(formatting.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillBackgroundColorColor()); - - checkFontFormattingColorWriteOutAndReadBack(wb, extendedColor); - } - - private void checkFontFormattingColorWriteOutAndReadBack(Workbook wb, ExtendedColor extendedColor) { - Workbook wbBack = XSSFITestDataProvider.instance.writeOutAndReadBack(wb); - assertNotNull(wbBack); - - assertEquals(1, wbBack.getSheetAt(0).getSheetConditionalFormatting().getNumConditionalFormattings()); - final ConditionalFormatting formattingBack = wbBack.getSheetAt(0).getSheetConditionalFormatting().getConditionalFormattingAt(0); - assertEquals(1, wbBack.getSheetAt(0).getSheetConditionalFormatting().getConditionalFormattingAt(0).getNumberOfRules()); - final ConditionalFormattingRule ruleBack = formattingBack.getRule(0); - final FontFormatting fontFormattingBack = ruleBack.getFontFormatting(); - assertNotNull(formattingBack); - assertNotNull(fontFormattingBack.getFontColor()); - assertEquals(extendedColor, fontFormattingBack.getFontColor()); - assertEquals(extendedColor, ruleBack.getPatternFormatting().getFillBackgroundColorColor()); - } - - @Override - protected boolean applyLimitOf3() { - return false; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java deleted file mode 100644 index b9e2474309..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java +++ /dev/null @@ -1,110 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.ss.formula.ConditionalFormattingEvaluator; -import org.apache.poi.ss.formula.WorkbookEvaluatorProvider; -import org.apache.poi.ss.usermodel.BaseTestDataFormat; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * Tests for {@link XSSFDataFormat} - */ -public final class TestXSSFDataFormat extends BaseTestDataFormat { - - public TestXSSFDataFormat() { - super(XSSFITestDataProvider.instance); - } - - /** - * [Bug 58778] Built-in number formats can be overridden with XSSFDataFormat.putFormat(int id, String fmt) - */ - @Test - void test58778() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - Cell cell = wb1.createSheet("bug58778").createRow(0).createCell(0); - cell.setCellValue(5.25); - CellStyle style = wb1.createCellStyle(); - - XSSFDataFormat dataFormat = wb1.createDataFormat(); - - short poundFmtIdx = 6; - dataFormat.putFormat(poundFmtIdx, POUND_FMT); - style.setDataFormat(poundFmtIdx); - cell.setCellStyle(style); - // Cell should appear as "<poundsymbol>5" - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutCloseAndReadBack(wb1)) { - cell = wb2.getSheet("bug58778").getRow(0).getCell(0); - assertEquals(5.25, cell.getNumericCellValue(), 0); - - style = cell.getCellStyle(); - assertEquals(POUND_FMT, style.getDataFormatString()); - assertEquals(poundFmtIdx, style.getDataFormat()); - - // manually check the file to make sure the cell is rendered as "<poundsymbol>5" - // Verified with LibreOffice 4.2.8.2 on 2015-12-28 - } - } - } - - @Test - void testConditionalFormattingEvaluation() throws IOException { - try (Workbook wb = openSampleWorkbook("61060-conditional-number-formatting.xlsx")) { - - final DataFormatter formatter = new DataFormatter(); - final FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - final ConditionalFormattingEvaluator cfEvaluator = new ConditionalFormattingEvaluator(wb, (WorkbookEvaluatorProvider) evaluator); - - CellReference ref = new CellReference("A1"); - Cell cell = wb.getSheetAt(0).getRow(ref.getRow()).getCell(ref.getCol()); - assertEquals("0.10", formatter.formatCellValue(cell, evaluator, cfEvaluator)); - // verify cell format without the conditional rule applied - assertEquals("0.1", formatter.formatCellValue(cell, evaluator)); - - ref = new CellReference("A3"); - cell = wb.getSheetAt(0).getRow(ref.getRow()).getCell(ref.getCol()); - assertEquals("-2.00E+03", formatter.formatCellValue(cell, evaluator, cfEvaluator)); - // verify cell format without the conditional rule applied - assertEquals("-2000", formatter.formatCellValue(cell, evaluator)); - - ref = new CellReference("A4"); - cell = wb.getSheetAt(0).getRow(ref.getRow()).getCell(ref.getCol()); - assertEquals("100", formatter.formatCellValue(cell, evaluator, cfEvaluator)); - - ref = new CellReference("A5"); - cell = wb.getSheetAt(0).getRow(ref.getRow()).getCell(ref.getCol()); - assertEquals("$1,000", formatter.formatCellValue(cell, evaluator, cfEvaluator)); - // verify cell format without the conditional rule applied - assertEquals("1000", formatter.formatCellValue(cell, evaluator)); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java deleted file mode 100644 index 18f4d51d5d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java +++ /dev/null @@ -1,381 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -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.assertTrue; - -import java.io.IOException; -import java.math.BigDecimal; -import java.util.List; - -import org.apache.poi.ss.formula.DataValidationEvaluator; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.BaseTestDataValidation; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType; -import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -class TestXSSFDataValidation extends BaseTestDataValidation { - - public TestXSSFDataValidation(){ - super(XSSFITestDataProvider.instance); - } - - @Test - void testAddValidations() throws Exception { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("DataValidations-49244.xlsx"); - XSSFSheet sheet = wb1.getSheetAt(0); - List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); - - // For each validation type, there are two cells with the same validation. This tests - // application of a single validation definition to multiple cells. - // - // For list ( 3 validations for explicit and 3 for formula ) - // - one validation that allows blank. - // - one that does not allow blank. - // - one that does not show the drop down arrow. - // = 2 - // - // For number validations ( integer/decimal and text length ) with 8 different types of operators. - // = 50 - // - // = 52 ( Total ) - - assertEquals(52,dataValidations.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - int[] validationTypes = new int[]{ValidationType.INTEGER,ValidationType.DECIMAL,ValidationType.TEXT_LENGTH}; - - int[] singleOperandOperatorTypes = new int[]{ - OperatorType.LESS_THAN,OperatorType.LESS_OR_EQUAL, - OperatorType.GREATER_THAN,OperatorType.GREATER_OR_EQUAL, - OperatorType.EQUAL,OperatorType.NOT_EQUAL - } ; - int[] doubleOperandOperatorTypes = new int[]{ - OperatorType.BETWEEN,OperatorType.NOT_BETWEEN - }; - - BigDecimal value = new BigDecimal("10"),value2 = new BigDecimal("20"); - BigDecimal dvalue = new BigDecimal("10.001"),dvalue2 = new BigDecimal("19.999"); - final int lastRow = sheet.getLastRowNum(); - int offset = lastRow + 3; - - int lastKnownNumValidations = dataValidations.size(); - - Row row = sheet.createRow(offset++); - Cell cell = row.createCell(0); - DataValidationConstraint explicitListValidation = dataValidationHelper.createExplicitListConstraint(new String[]{"MA","MI","CA"}); - CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(cell.getRowIndex(), cell.getColumnIndex(), cell.getRowIndex(), cell.getColumnIndex()); - DataValidation dataValidation = dataValidationHelper.createValidation(explicitListValidation, cellRangeAddressList); - setOtherValidationParameters(dataValidation); - sheet.addValidationData(dataValidation); - lastKnownNumValidations++; - - row = sheet.createRow(offset++); - cell = row.createCell(0); - - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(cell.getRowIndex(), cell.getColumnIndex(), cell.getRowIndex(), cell.getColumnIndex()); - - Cell firstCell = row.createCell(1);firstCell.setCellValue("UT"); - Cell secondCell = row.createCell(2);secondCell.setCellValue("MN"); - Cell thirdCell = row.createCell(3);thirdCell.setCellValue("IL"); - - int rowNum = row.getRowNum() + 1; - String listFormula = "$B$" + rowNum + ":" + "$D$" + rowNum; - DataValidationConstraint formulaListValidation = dataValidationHelper.createFormulaListConstraint(listFormula); - - dataValidation = dataValidationHelper.createValidation(formulaListValidation, cellRangeAddressList); - setOtherValidationParameters(dataValidation); - sheet.addValidationData(dataValidation); - lastKnownNumValidations++; - - offset++; - offset++; - - for (int i = 0; i < validationTypes.length; i++) { - int validationType = validationTypes[i]; - offset = offset + 2; - final Row row0 = sheet.createRow(offset++); - Cell cell_10 = row0.createCell(0); - cell_10.setCellValue(validationType==ValidationType.DECIMAL ? "Decimal " : validationType==ValidationType.INTEGER ? "Integer" : "Text Length"); - offset++; - for (int j = 0; j < singleOperandOperatorTypes.length; j++) { - int operatorType = singleOperandOperatorTypes[j]; - final Row row1 = sheet.createRow(offset++); - - //For Integer (> and >=) we add 1 extra cell for validations whose formulae reference other cells. - final Row row2 = i==0 && j < 2 ? sheet.createRow(offset++) : null; - - cell_10 = row1.createCell(0); - cell_10.setCellValue(XSSFDataValidation.operatorTypeMappings.get(operatorType).toString()); - Cell cell_11 = row1.createCell(1); - Cell cell_21 = row1.createCell(2); - Cell cell_22 = i==0 && j < 2 ? (row2 == null ? null : row2.createCell(2)) : null; - - Cell cell_13 = row1.createCell(3); - cell_13.setCellValue(validationType==ValidationType.DECIMAL ? dvalue.doubleValue() : value.intValue()); - - - //First create value based validation; - DataValidationConstraint constraint = dataValidationHelper.createNumericConstraint(validationType,operatorType, value.toString(), null); - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_11.getRowIndex(),cell_11.getRowIndex(),cell_11.getColumnIndex(),cell_11.getColumnIndex())); - DataValidation validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters(validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); - - //Now create real formula based validation. - String formula1 = new CellReference(cell_13.getRowIndex(),cell_13.getColumnIndex()).formatAsString(); - constraint = dataValidationHelper.createNumericConstraint(validationType,operatorType, formula1, null); - if (i==0 && j==0) { - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(), cell_21.getRowIndex(), cell_21.getColumnIndex(), cell_21.getColumnIndex())); - validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters(validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); - - cellRangeAddressList = new CellRangeAddressList(); - if (cell_22 != null) { - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_22.getRowIndex(), cell_22.getRowIndex(), cell_22.getColumnIndex(), cell_22.getColumnIndex())); - } - validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters( validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); - } else if(i==0 && j==1 ){ - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(), cell_21.getRowIndex(), cell_21.getColumnIndex(), cell_21.getColumnIndex())); - if (cell_22 != null) { - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_22.getRowIndex(), cell_22.getRowIndex(), cell_22.getColumnIndex(), cell_22.getColumnIndex())); - } - validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters( validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); - } else { - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(), cell_21.getRowIndex(), cell_21.getColumnIndex(), cell_21.getColumnIndex())); - validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters(validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); - } - } - - for (int operatorType : doubleOperandOperatorTypes) { - final Row row1 = sheet.createRow(offset++); - - cell_10 = row1.createCell(0); - cell_10.setCellValue(XSSFDataValidation.operatorTypeMappings.get(operatorType).toString()); - - Cell cell_11 = row1.createCell(1); - Cell cell_21 = row1.createCell(2); - - Cell cell_13 = row1.createCell(3); - Cell cell_14 = row1.createCell(4); - - - String value1String = validationType==ValidationType.DECIMAL ? dvalue.toString() : value.toString(); - cell_13.setCellValue(validationType==ValidationType.DECIMAL ? dvalue.doubleValue() : value.intValue()); - - String value2String = validationType==ValidationType.DECIMAL ? dvalue2.toString() : value2.toString(); - cell_14.setCellValue(validationType==ValidationType.DECIMAL ? dvalue2.doubleValue() : value2.intValue()); - - - //First create value based validation; - DataValidationConstraint constraint = dataValidationHelper.createNumericConstraint(validationType,operatorType, value1String, value2String); - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_11.getRowIndex(),cell_11.getRowIndex(),cell_11.getColumnIndex(),cell_11.getColumnIndex())); - DataValidation validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters(validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); - - - //Now create real formula based validation. - String formula1 = new CellReference(cell_13.getRowIndex(),cell_13.getColumnIndex()).formatAsString(); - String formula2 = new CellReference(cell_14.getRowIndex(),cell_14.getColumnIndex()).formatAsString(); - constraint = dataValidationHelper.createNumericConstraint(validationType,operatorType, formula1, formula2); - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(),cell_21.getRowIndex(),cell_21.getColumnIndex(),cell_21.getColumnIndex())); - validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - - setOtherValidationParameters(validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, sheet.getDataValidations().size()); - } - } - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - XSSFSheet sheetAt = wb2.getSheetAt(0); - assertEquals(lastKnownNumValidations, sheetAt.getDataValidations().size()); - wb2.close(); - } - - protected void setOtherValidationParameters(DataValidation validation) { - boolean yesNo = true; - validation.setEmptyCellAllowed(yesNo); - validation.setShowErrorBox(yesNo); - validation.setShowPromptBox(yesNo); - validation.createErrorBox("Error Message Title", "Error Message"); - validation.createPromptBox("Prompt", "Enter some value"); - validation.setSuppressDropDownArrow(yesNo); - } - - @Test - void test53965() throws Exception { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - List<XSSFDataValidation> lst = sheet.getDataValidations(); //<-- works - assertEquals(0, lst.size()); - - //create the cell that will have the validation applied - sheet.createRow(0).createCell(0); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("SUM($A$1:$A$1) <= 3500"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - // this line caused XmlValueOutOfRangeException , see Bugzilla 3965 - lst = sheet.getDataValidations(); - assertEquals(1, lst.size()); - } - } - - @Test - void testDefaultErrorStyle() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - final XSSFDataValidation validation = createValidation(sheet); - sheet.addValidationData(validation); - - final List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); - assertEquals(DataValidation.ErrorStyle.STOP, dataValidations.get(0).getErrorStyle()); - } - } - - @Test - void testSetErrorStyles() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - XSSFDataValidation validation = createValidation(sheet); - sheet.addValidationData(validation); - - // extract generated validation from sheet - List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); - validation = dataValidations.get(0); - - // test INFO - validation.setErrorStyle(DataValidation.ErrorStyle.INFO); - assertEquals(DataValidation.ErrorStyle.INFO, dataValidations.get(0).getErrorStyle()); - - // test WARNING - validation.setErrorStyle(DataValidation.ErrorStyle.WARNING); - assertEquals(DataValidation.ErrorStyle.WARNING, dataValidations.get(0).getErrorStyle()); - - // test STOP - validation.setErrorStyle(DataValidation.ErrorStyle.STOP); - assertEquals(DataValidation.ErrorStyle.STOP, dataValidations.get(0).getErrorStyle()); - } - } - - @Test - void testDefaultAllowBlank() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - final XSSFDataValidation validation = createValidation(sheet); - sheet.addValidationData(validation); - - final List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); - assertTrue(dataValidations.get(0).getCtDataValidation().getAllowBlank()); - } - } - - @Test - void testSetAllowBlankToFalse() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - final XSSFDataValidation validation = createValidation(sheet); - validation.getCtDataValidation().setAllowBlank(false); - - sheet.addValidationData(validation); - - final List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); - assertFalse(dataValidations.get(0).getCtDataValidation().getAllowBlank()); - } - } - - @Test - void testSetAllowBlankToTrue() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - final XSSFDataValidation validation = createValidation(sheet); - validation.getCtDataValidation().setAllowBlank(true); - - sheet.addValidationData(validation); - - final List<XSSFDataValidation> dataValidations = sheet.getDataValidations(); - assertTrue(dataValidations.get(0).getCtDataValidation().getAllowBlank()); - } - } - - private XSSFDataValidation createValidation(XSSFSheet sheet) { - //create the cell that will have the validation applied - final Row row = sheet.createRow(0); - row.createCell(0); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - - DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("true"); - return (XSSFDataValidation) dataValidationHelper.createValidation(constraint, new CellRangeAddressList(0, 0, 0, 0)); - } - - @Test - void testTableBasedValidationList() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("dataValidationTableRange.xlsx")) { - XSSFFormulaEvaluator fEval = wb.getCreationHelper().createFormulaEvaluator(); - DataValidationEvaluator dve = new DataValidationEvaluator(wb, fEval); - List<ValueEval> values = dve.getValidationValuesForCell(new CellReference("County Ranking", 8, 6, false, false)); - assertEquals(32, values.size(), "wrong # of valid values"); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidationConstraint.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidationConstraint.java deleted file mode 100644 index 79d340ebe2..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidationConstraint.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import org.apache.poi.ss.formula.DataValidationEvaluator; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.util.stream.IntStream; - -class TestXSSFDataValidationConstraint { - static final int listType = ValidationType.LIST; - static final int ignoredType = OperatorType.IGNORED; - - // See bug 59719 - @Test - void listLiteralsQuotesAreStripped_formulaConstructor() { - // literal list, using formula constructor - String literal = "\"one, two, three\""; - String[] expected = new String[] { "one", "two", "three" }; - DataValidationConstraint constraint = new XSSFDataValidationConstraint(listType, ignoredType, literal, null); - assertArrayEquals(expected, constraint.getExplicitListValues()); - // Excel and DataValidationConstraint parser ignore (strip) whitespace; quotes should still be intact - // FIXME: whitespace wasn't stripped - assertEquals(literal, constraint.getFormula1()); - } - - @Test - void listLiteralsQuotesAreStripped_arrayConstructor() { - // literal list, using array constructor - String literal = "\"one, two, three\""; - String[] expected = new String[] { "one", "two", "three" }; - DataValidationConstraint constraint = new XSSFDataValidationConstraint(expected); - assertArrayEquals(expected, constraint.getExplicitListValues()); - // Excel and DataValidationConstraint parser ignore (strip) whitespace; quotes should still be intact - assertEquals(literal.replace(" ", ""), constraint.getFormula1()); - } - - @Test - void listLiteralsGreaterThan255CharactersThrows() { - String[] literal = IntStream.range(0, 129).mapToObj(i -> "a").toArray(String[]::new); - assertThrows(IllegalArgumentException.class, () -> new XSSFDataValidationConstraint(literal)); - } - - @Test - void dataValidationListLiteralTooLongFromFile() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("DataValidationListTooLong.xlsx")) { - XSSFFormulaEvaluator fEval = wb.getCreationHelper().createFormulaEvaluator(); - DataValidationEvaluator dvEval = new DataValidationEvaluator(wb, fEval); - assertThrows(IllegalArgumentException.class, () -> dvEval.getValidationValuesForCell(new CellReference("Sheet0!A1"))); - } - } - - @Test - void rangeReference() { - // (unnamed range) reference list - String reference = "A1:A5"; - DataValidationConstraint constraint = new XSSFDataValidationConstraint(listType, ignoredType, reference, null); - assertNull(constraint.getExplicitListValues()); - assertEquals("A1:A5", constraint.getFormula1()); - } - - @Test - void namedRangeReference() { - // named range list - String namedRange = "MyNamedRange"; - DataValidationConstraint constraint = new XSSFDataValidationConstraint(listType, ignoredType, namedRange, null); - assertNull(constraint.getExplicitListValues()); - assertEquals("MyNamedRange", constraint.getFormula1()); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java deleted file mode 100644 index f85f0411ed..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java +++ /dev/null @@ -1,205 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDialogsheet; - - -class TestXSSFDialogSheet { - - @Test - void testCreateDialogSheet() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - Sheet dialogsheet = workbook.createDialogsheet("Dialogsheet 1", CTDialogsheet.Factory.newInstance()); - assertNotNull(dialogsheet); - workbook.close(); - } - - @Test - void testGetDialog() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet dialogsheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertTrue(dialogsheet.getDialog()); - workbook.close(); - } - - @Test - void testAddRow() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - Sheet dialogsheet = workbook.createDialogsheet("Dialogsheet 1", CTDialogsheet.Factory.newInstance()); - assertNotNull(dialogsheet); - Row row = dialogsheet.createRow(0); - assertNull(row); - workbook.close(); - } - - @Test - void testGetSetAutoBreaks() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertTrue(sheet.getAutobreaks()); - sheet.setAutobreaks(false); - assertFalse(sheet.getAutobreaks()); - workbook.close(); - } - - @Test - void testIsSetFitToPage() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.getFitToPage()); - sheet.setFitToPage(true); - assertTrue(sheet.getFitToPage()); - sheet.setFitToPage(false); - assertFalse(sheet.getFitToPage()); - workbook.close(); - } - - - @Test - void testGetFooter() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertNotNull(sheet.getFooter()); - sheet.getFooter().setCenter("test center footer"); - assertEquals("test center footer", sheet.getFooter().getCenter()); - workbook.close(); - } - - @Test - void testGetAllHeadersFooters() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertNotNull(sheet); - assertNotNull(sheet.getOddFooter()); - assertNotNull(sheet.getEvenFooter()); - assertNotNull(sheet.getFirstFooter()); - assertNotNull(sheet.getOddHeader()); - assertNotNull(sheet.getEvenHeader()); - assertNotNull(sheet.getFirstHeader()); - - assertEquals("", sheet.getOddFooter().getLeft()); - sheet.getOddFooter().setLeft("odd footer left"); - assertEquals("odd footer left", sheet.getOddFooter().getLeft()); - - assertEquals("", sheet.getEvenFooter().getLeft()); - sheet.getEvenFooter().setLeft("even footer left"); - assertEquals("even footer left", sheet.getEvenFooter().getLeft()); - - assertEquals("", sheet.getFirstFooter().getLeft()); - sheet.getFirstFooter().setLeft("first footer left"); - assertEquals("first footer left", sheet.getFirstFooter().getLeft()); - - assertEquals("", sheet.getOddHeader().getLeft()); - sheet.getOddHeader().setLeft("odd header left"); - assertEquals("odd header left", sheet.getOddHeader().getLeft()); - - assertEquals("", sheet.getOddHeader().getRight()); - sheet.getOddHeader().setRight("odd header right"); - assertEquals("odd header right", sheet.getOddHeader().getRight()); - - assertEquals("", sheet.getOddHeader().getCenter()); - sheet.getOddHeader().setCenter("odd header center"); - assertEquals("odd header center", sheet.getOddHeader().getCenter()); - workbook.close(); - } - - @Test - void testGetSetHorizontallyCentered() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.getHorizontallyCenter()); - sheet.setHorizontallyCenter(true); - assertTrue(sheet.getHorizontallyCenter()); - sheet.setHorizontallyCenter(false); - assertFalse(sheet.getHorizontallyCenter()); - workbook.close(); - } - - @Test - void testGetSetVerticallyCentered() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.getVerticallyCenter()); - sheet.setVerticallyCenter(true); - assertTrue(sheet.getVerticallyCenter()); - sheet.setVerticallyCenter(false); - assertFalse(sheet.getVerticallyCenter()); - workbook.close(); - } - - @Test - void testIsSetPrintGridlines() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.isPrintGridlines()); - sheet.setPrintGridlines(true); - assertTrue(sheet.isPrintGridlines()); - workbook.close(); - } - - @Test - void testIsSetDisplayFormulas() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.isDisplayFormulas()); - sheet.setDisplayFormulas(true); - assertTrue(sheet.isDisplayFormulas()); - workbook.close(); - } - - @Test - void testIsSetDisplayGridLines() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertTrue(sheet.isDisplayGridlines()); - sheet.setDisplayGridlines(false); - assertFalse(sheet.isDisplayGridlines()); - workbook.close(); - } - - @Test - void testIsSetDisplayRowColHeadings() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertTrue(sheet.isDisplayRowColHeadings()); - sheet.setDisplayRowColHeadings(false); - assertFalse(sheet.isDisplayRowColHeadings()); - workbook.close(); - } - - @Test - void testGetScenarioProtect() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.getScenarioProtect()); - workbook.close(); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java deleted file mode 100644 index c072013404..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java +++ /dev/null @@ -1,937 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -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.assertNotSame; -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.awt.Color; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ooxml.POIXMLDocumentPart; -import org.apache.poi.ooxml.POIXMLDocumentPart.RelationPart; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.FontUnderline; -import org.apache.poi.ss.usermodel.ShapeTypes; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.Units; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTDrawing; - -class TestXSSFDrawing { - @Test - void bug54803() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("bug54803.xlsx")) { - XSSFSheet sheet = wb.getSheetAt(0); - sheet.createDrawingPatriarch(); - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) { - XSSFSheet sheet2 = wb2.getSheetAt(0); - assertNotNull(sheet2.getDrawingPatriarch()); - } - } - } - - @Test - void testRead() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - //the sheet has one relationship and it is XSSFDrawing - List<RelationPart> rels = sheet.getRelationParts(); - assertEquals(1, rels.size()); - RelationPart rp = rels.get(0); - assertTrue(rp.getDocumentPart() instanceof XSSFDrawing); - - XSSFDrawing drawing = rp.getDocumentPart(); - //sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing - assertSame(drawing, sheet.createDrawingPatriarch()); - String drawingId = rp.getRelationship().getId(); - - //there should be a relation to this drawing in the worksheet - assertTrue(sheet.getCTWorksheet().isSetDrawing()); - assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId()); - - List<XSSFShape> shapes = drawing.getShapes(); - assertEquals(6, shapes.size()); - - assertTrue(shapes.get(0) instanceof XSSFPicture); - assertTrue(shapes.get(1) instanceof XSSFPicture); - assertTrue(shapes.get(2) instanceof XSSFPicture); - assertTrue(shapes.get(3) instanceof XSSFPicture); - assertTrue(shapes.get(4) instanceof XSSFSimpleShape); - assertTrue(shapes.get(5) instanceof XSSFPicture); - - for(XSSFShape sh : shapes) assertNotNull(sh.getAnchor()); - - checkRewrite(wb); - wb.close(); - } - - @Test - void testNew() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - //multiple calls of createDrawingPatriarch should return the same instance of XSSFDrawing - XSSFDrawing dr1 = sheet.createDrawingPatriarch(); - XSSFDrawing dr2 = sheet.createDrawingPatriarch(); - assertSame(dr1, dr2); - - List<RelationPart> rels = sheet.getRelationParts(); - assertEquals(1, rels.size()); - RelationPart rp = rels.get(0); - assertTrue(rp.getDocumentPart() instanceof XSSFDrawing); - - XSSFDrawing drawing = rp.getDocumentPart(); - String drawingId = rp.getRelationship().getId(); - - //there should be a relation to this drawing in the worksheet - assertTrue(sheet.getCTWorksheet().isSetDrawing()); - assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId()); - - XSSFConnector c1= drawing.createConnector(new XSSFClientAnchor(0,0,0,0,0,0,2,2)); - c1.setLineWidth(2.5); - c1.setLineStyle(1); - - XSSFShapeGroup c2 = drawing.createGroup(new XSSFClientAnchor(0,0,0,0,0,0,5,5)); - assertNotNull(c2); - - XSSFSimpleShape c3 = drawing.createSimpleShape(new XSSFClientAnchor(0,0,0,0,2,2,3,4)); - c3.setText(new XSSFRichTextString("Test String")); - c3.setFillColor(128, 128, 128); - - XSSFTextBox c4 = drawing.createTextbox(new XSSFClientAnchor(0,0,0,0,4,4,5,6)); - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - rt.applyFont(0, 5, wb1.createFont()); - rt.applyFont(5, 6, wb1.createFont()); - c4.setText(rt); - - c4.setNoFill(true); - assertEquals(4, drawing.getCTDrawing().sizeOfTwoCellAnchorArray()); - - List<XSSFShape> shapes = drawing.getShapes(); - assertEquals(4, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFConnector); - assertTrue(shapes.get(1) instanceof XSSFShapeGroup); - assertTrue(shapes.get(2) instanceof XSSFSimpleShape); - assertTrue(shapes.get(3) instanceof XSSFSimpleShape); // - - // Save and re-load it - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - // Check - dr1 = sheet.createDrawingPatriarch(); - CTDrawing ctDrawing = dr1.getCTDrawing(); - - // Connector, shapes and text boxes are all two cell anchors - assertEquals(0, ctDrawing.sizeOfAbsoluteAnchorArray()); - assertEquals(0, ctDrawing.sizeOfOneCellAnchorArray()); - assertEquals(4, ctDrawing.sizeOfTwoCellAnchorArray()); - - shapes = dr1.getShapes(); - assertEquals(4, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFConnector); - assertTrue(shapes.get(1) instanceof XSSFShapeGroup); - assertTrue(shapes.get(2) instanceof XSSFSimpleShape); - assertTrue(shapes.get(3) instanceof XSSFSimpleShape); // - - // Ensure it got the right namespaces - String xml = ctDrawing.toString(); - assertTrue(xml.contains("xmlns:xdr=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\"")); - assertTrue(xml.contains("xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"")); - - checkRewrite(wb2); - wb2.close(); - } - - @Test - void testMultipleDrawings() throws IOException{ - XSSFWorkbook wb = new XSSFWorkbook(); - for (int i = 0; i < 3; i++) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - assertNotNull(drawing); - } - try (OPCPackage pkg = wb.getPackage()) { - assertEquals(3, pkg.getPartsByContentType(XSSFRelation.DRAWINGS.getContentType()).size()); - checkRewrite(wb); - } - wb.close(); - } - - @Test - void testClone() throws Exception{ - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx"); - XSSFSheet sheet1 = wb.getSheetAt(0); - - XSSFSheet sheet2 = wb.cloneSheet(0); - - //the source sheet has one relationship and it is XSSFDrawing - List<POIXMLDocumentPart> rels1 = sheet1.getRelations(); - assertEquals(1, rels1.size()); - assertTrue(rels1.get(0) instanceof XSSFDrawing); - - List<POIXMLDocumentPart> rels2 = sheet2.getRelations(); - assertEquals(1, rels2.size()); - assertTrue(rels2.get(0) instanceof XSSFDrawing); - - XSSFDrawing drawing1 = (XSSFDrawing)rels1.get(0); - XSSFDrawing drawing2 = (XSSFDrawing)rels2.get(0); - assertNotSame(drawing1, drawing2); // drawing2 is a clone of drawing1 - - List<XSSFShape> shapes1 = drawing1.getShapes(); - List<XSSFShape> shapes2 = drawing2.getShapes(); - assertEquals(shapes1.size(), shapes2.size()); - - for(int i = 0; i < shapes1.size(); i++){ - XSSFShape sh1 = shapes1.get(i); - XSSFShape sh2 = shapes2.get(i); - - assertSame(sh1.getClass(), sh2.getClass()); - assertEquals(sh1.getShapeProperties().toString(), sh2.getShapeProperties().toString()); - } - - checkRewrite(wb); - wb.close(); - } - - /** - * ensure that rich text attributes defined in a XSSFRichTextString - * are passed to XSSFSimpleShape. - * - * See Bugzilla 52219. - */ - @Test - void testRichText() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - - XSSFFont font = wb.createFont(); - font.setColor(new XSSFColor(new Color(0, 128, 128), wb.getStylesSource().getIndexedColors())); - font.setItalic(true); - font.setBold(true); - font.setUnderline(FontUnderline.SINGLE); - rt.applyFont(font); - - shape.setText(rt); - - CTTextParagraph pr = shape.getCTShape().getTxBody().getPArray(0); - assertEquals(1, pr.sizeOfRArray()); - - CTTextCharacterProperties rPr = pr.getRArray(0).getRPr(); - assertTrue(rPr.getB()); - assertTrue(rPr.getI()); - assertEquals(STTextUnderlineType.SNG, rPr.getU()); - assertArrayEquals( - new byte[]{0, (byte)128, (byte)128} , - rPr.getSolidFill().getSrgbClr().getVal()); - - checkRewrite(wb); - wb.close(); - } - - /** - * test that anchor is not null when reading shapes from existing drawings - */ - @Test - void testReadAnchors() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFClientAnchor anchor1 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4); - XSSFShape shape1 = drawing.createTextbox(anchor1); - assertNotNull(shape1); - - XSSFClientAnchor anchor2 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 5); - XSSFShape shape2 = drawing.createTextbox(anchor2); - assertNotNull(shape2); - - int pictureIndex= wb1.addPicture(new byte[]{}, XSSFWorkbook.PICTURE_TYPE_PNG); - XSSFClientAnchor anchor3 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 6); - XSSFShape shape3 = drawing.createPicture(anchor3, pictureIndex); - assertNotNull(shape3); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - drawing = sheet.createDrawingPatriarch(); - List<XSSFShape> shapes = drawing.getShapes(); - assertEquals(shapes.get(0).getAnchor(), anchor1); - assertEquals(shapes.get(1).getAnchor(), anchor2); - assertEquals(shapes.get(2).getAnchor(), anchor3); - - checkRewrite(wb2); - wb2.close(); - } - - /** - * ensure that font and color rich text attributes defined in a XSSFRichTextString - * are passed to XSSFSimpleShape. - * - * See Bugzilla 54969. - */ - @Test - void testRichTextFontAndColor() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - - XSSFFont font = wb.createFont(); - font.setColor(new XSSFColor(new Color(0, 128, 128), wb.getStylesSource().getIndexedColors())); - font.setFontName("Arial"); - rt.applyFont(font); - - shape.setText(rt); - - CTTextParagraph pr = shape.getCTShape().getTxBody().getPArray(0); - assertEquals(1, pr.sizeOfRArray()); - - CTTextCharacterProperties rPr = pr.getRArray(0).getRPr(); - assertEquals("Arial", rPr.getLatin().getTypeface()); - assertArrayEquals( - new byte[]{0, (byte)128, (byte)128} , - rPr.getSolidFill().getSrgbClr().getVal()); - checkRewrite(wb); - wb.close(); - } - - /** - * Test setText single paragraph to ensure backwards compatibility - */ - @Test - void testSetTextSingleParagraph() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - - XSSFFont font = wb.createFont(); - font.setColor(new XSSFColor(new Color(0, 255, 255), wb.getStylesSource().getIndexedColors())); - font.setFontName("Arial"); - rt.applyFont(font); - - shape.setText(rt); - - List<XSSFTextParagraph> paras = shape.getTextParagraphs(); - assertEquals(1, paras.size()); - assertEquals("Test String", paras.get(0).getText()); - - List<XSSFTextRun> runs = paras.get(0).getTextRuns(); - assertEquals(1, runs.size()); - assertEquals("Arial", runs.get(0).getFontFamily()); - - Color clr = runs.get(0).getFontColor(); - assertArrayEquals( - new int[] { 0, 255, 255 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - checkRewrite(wb); - wb.close(); - } - - /** - * Test addNewTextParagraph - */ - @Test - void testAddNewTextParagraph() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - - XSSFTextParagraph para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 1"); - - List<XSSFTextParagraph> paras = shape.getTextParagraphs(); - assertEquals(2, paras.size()); // this should be 2 as XSSFSimpleShape creates a default paragraph (no text), and then we add a string to that. - - List<XSSFTextRun> runs = para.getTextRuns(); - assertEquals(1, runs.size()); - assertEquals("Line 1", runs.get(0).getText()); - - checkRewrite(wb); - wb.close(); - } - - /** - * Test addNewTextParagraph using RichTextString - */ - @Test - void testAddNewTextParagraphWithRTS() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - XSSFRichTextString rt = new XSSFRichTextString("Test Rich Text String"); - - XSSFFont font = wb1.createFont(); - font.setColor(new XSSFColor(new Color(0, 255, 255), wb1.getStylesSource().getIndexedColors())); - font.setFontName("Arial"); - rt.applyFont(font); - - XSSFFont midfont = wb1.createFont(); - midfont.setColor(new XSSFColor(new Color(0, 255, 0), wb1.getStylesSource().getIndexedColors())); - rt.applyFont(5, 14, midfont); // set the text "Rich Text" to be green and the default font - - XSSFTextParagraph para = shape.addNewTextParagraph(rt); - - // Save and re-load it - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - // Check - drawing = sheet.createDrawingPatriarch(); - - List<XSSFShape> shapes = drawing.getShapes(); - assertEquals(1, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - - XSSFSimpleShape sshape = (XSSFSimpleShape) shapes.get(0); - - List<XSSFTextParagraph> paras = sshape.getTextParagraphs(); - assertEquals(2, paras.size()); // this should be 2 as XSSFSimpleShape creates a default paragraph (no text), and then we add a string to that. - - List<XSSFTextRun> runs = para.getTextRuns(); - assertEquals(3, runs.size()); - - // first run properties - assertEquals("Test ", runs.get(0).getText()); - assertEquals("Arial", runs.get(0).getFontFamily()); - - Color clr = runs.get(0).getFontColor(); - assertArrayEquals( - new int[] { 0, 255, 255 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - // second run properties - assertEquals("Rich Text", runs.get(1).getText()); - assertEquals(XSSFFont.DEFAULT_FONT_NAME, runs.get(1).getFontFamily()); - - clr = runs.get(1).getFontColor(); - assertArrayEquals( - new int[] { 0, 255, 0 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - // third run properties - assertEquals(" String", runs.get(2).getText()); - assertEquals("Arial", runs.get(2).getFontFamily()); - clr = runs.get(2).getFontColor(); - assertArrayEquals( - new int[] { 0, 255, 255 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - checkRewrite(wb2); - wb2.close(); - } - - /** - * Test add multiple paragraphs and retrieve text - */ - @Test - void testAddMultipleParagraphs() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - - XSSFTextParagraph para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 1"); - - para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 2"); - - para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 3"); - - List<XSSFTextParagraph> paras = shape.getTextParagraphs(); - assertEquals(4, paras.size()); // this should be 4 as XSSFSimpleShape creates a default paragraph (no text), and then we added 3 paragraphs - assertEquals("Line 1\nLine 2\nLine 3", shape.getText()); - - checkRewrite(wb); - wb.close(); - } - - /** - * Test setting the text, then adding multiple paragraphs and retrieve text - */ - @Test - void testSetAddMultipleParagraphs() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - - shape.setText("Line 1"); - - XSSFTextParagraph para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 2"); - - para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 3"); - - List<XSSFTextParagraph> paras = shape.getTextParagraphs(); - assertEquals(3, paras.size()); // this should be 3 as we overwrote the default paragraph with setText, then added 2 new paragraphs - assertEquals("Line 1\nLine 2\nLine 3", shape.getText()); - - checkRewrite(wb); - wb.close(); - } - - /** - * Test reading text from a textbox in an existing file - */ - @Test - void testReadTextBox() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - //the sheet has one relationship and it is XSSFDrawing - List<RelationPart> rels = sheet.getRelationParts(); - assertEquals(1, rels.size()); - RelationPart rp = rels.get(0); - assertTrue(rp.getDocumentPart() instanceof XSSFDrawing); - - XSSFDrawing drawing = rp.getDocumentPart(); - //sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing - assertSame(drawing, sheet.createDrawingPatriarch()); - String drawingId = rp.getRelationship().getId(); - - //there should be a relation to this drawing in the worksheet - assertTrue(sheet.getCTWorksheet().isSetDrawing()); - assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId()); - - List<XSSFShape> shapes = drawing.getShapes(); - assertEquals(6, shapes.size()); - - assertTrue(shapes.get(4) instanceof XSSFSimpleShape); - - XSSFSimpleShape textbox = (XSSFSimpleShape) shapes.get(4); - assertEquals("Sheet with various pictures\n(jpeg, png, wmf, emf and pict)", textbox.getText()); - - checkRewrite(wb); - wb.close(); - } - - - /** - * Test reading multiple paragraphs from a textbox in an existing file - */ - @Test - void testReadTextBoxParagraphs() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTextBox.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - //the sheet has one relationship and it is XSSFDrawing - List<RelationPart> rels = sheet.getRelationParts(); - assertEquals(1, rels.size()); - RelationPart rp = rels.get(0); - - assertTrue(rp.getDocumentPart() instanceof XSSFDrawing); - - XSSFDrawing drawing = rp.getDocumentPart(); - - //sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing - assertSame(drawing, sheet.createDrawingPatriarch()); - String drawingId = rp.getRelationship().getId(); - - //there should be a relation to this drawing in the worksheet - assertTrue(sheet.getCTWorksheet().isSetDrawing()); - assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId()); - - List<XSSFShape> shapes = drawing.getShapes(); - assertEquals(1, shapes.size()); - - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - - XSSFSimpleShape textbox = (XSSFSimpleShape) shapes.get(0); - - List<XSSFTextParagraph> paras = textbox.getTextParagraphs(); - assertEquals(3, paras.size()); - - assertEquals("Line 2", paras.get(1).getText()); // check content of second paragraph - - assertEquals("Line 1\nLine 2\nLine 3", textbox.getText()); // check content of entire textbox - - // check attributes of paragraphs - assertEquals(TextAlign.LEFT, paras.get(0).getTextAlign()); - assertEquals(TextAlign.CENTER, paras.get(1).getTextAlign()); - assertEquals(TextAlign.RIGHT, paras.get(2).getTextAlign()); - - Color clr = paras.get(0).getTextRuns().get(0).getFontColor(); - assertArrayEquals( - new int[] { 255, 0, 0 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - clr = paras.get(1).getTextRuns().get(0).getFontColor(); - assertArrayEquals( - new int[] { 0, 255, 0 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - clr = paras.get(2).getTextRuns().get(0).getFontColor(); - assertArrayEquals( - new int[] { 0, 0, 255 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - checkRewrite(wb); - wb.close(); - } - - /** - * Test adding and reading back paragraphs as bullet points - */ - @Test - void testAddBulletParagraphs() throws IOException { - - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 10, 20)); - - String paraString1 = "A normal paragraph"; - String paraString2 = "First bullet"; - String paraString3 = "Second bullet (level 1)"; - String paraString4 = "Third bullet"; - String paraString5 = "Another normal paragraph"; - String paraString6 = "First numbered bullet"; - String paraString7 = "Second bullet (level 1)"; - String paraString8 = "Third bullet (level 1)"; - String paraString9 = "Fourth bullet (level 1)"; - String paraString10 = "Fifth Bullet"; - - XSSFTextParagraph para = shape.addNewTextParagraph(paraString1); - assertNotNull(para); - para = shape.addNewTextParagraph(paraString2); - para.setBullet(true); - - para = shape.addNewTextParagraph(paraString3); - para.setBullet(true); - para.setLevel(1); - - para = shape.addNewTextParagraph(paraString4); - para.setBullet(true); - - para = shape.addNewTextParagraph(paraString5); - assertNotNull(para); - para = shape.addNewTextParagraph(paraString6); - para.setBullet(ListAutoNumber.ARABIC_PERIOD); - - para = shape.addNewTextParagraph(paraString7); - para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3); - para.setLevel(1); - - para = shape.addNewTextParagraph(paraString8); - para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3); - para.setLevel(1); - - para = shape.addNewTextParagraph(""); - para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3); - para.setLevel(1); - - para = shape.addNewTextParagraph(paraString9); - para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3); - para.setLevel(1); - - para = shape.addNewTextParagraph(paraString10); - para.setBullet(ListAutoNumber.ARABIC_PERIOD); - - // Save and re-load it - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - // Check - drawing = sheet.createDrawingPatriarch(); - - List<XSSFShape> shapes = drawing.getShapes(); - assertEquals(1, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - - XSSFSimpleShape sshape = (XSSFSimpleShape) shapes.get(0); - - List<XSSFTextParagraph> paras = sshape.getTextParagraphs(); - assertEquals(12, paras.size()); // this should be 12 as XSSFSimpleShape creates a default paragraph (no text), and then we added to that - - String builder = - paraString1 + - "\n" + - "\u2022 " + - paraString2 + - "\n" + - "\t\u2022 " + - paraString3 + - "\n" + - "\u2022 " + - paraString4 + - "\n" + - paraString5 + - "\n" + - "1. " + - paraString6 + - "\n" + - "\t3. " + - paraString7 + - "\n" + - "\t4. " + - paraString8 + - "\n" + - "\t" + // should be empty - "\n" + - "\t5. " + - paraString9 + - "\n" + - "2. " + - paraString10; - - assertEquals(builder, sshape.getText()); - - checkRewrite(wb2); - wb2.close(); - } - - /** - * Test reading bullet numbering from a textbox in an existing file - */ - @Test - void testReadTextBox2() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTextBox2.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - List<XSSFShape> shapes = drawing.getShapes(); - XSSFSimpleShape textbox = (XSSFSimpleShape) shapes.get(0); - String extracted = textbox.getText(); - String sb = - "1. content1A\n" + - "\t1. content1B\n" + - "\t2. content2B\n" + - "\t3. content3B\n" + - "2. content2A\n" + - "\t3. content2BStartAt3\n" + - "\t\n\t\n\t" + - "4. content2BStartAt3Incremented\n" + - "\t\n\t\n\t\n\t"; - - assertEquals(sb, extracted); - checkRewrite(wb); - wb.close(); - } - - @Test - void testXSSFSimpleShapeCausesNPE56514() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("56514.xlsx"); - XSSFSheet sheet = wb1.getSheetAt(0); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - List<XSSFShape> shapes = drawing.getShapes(); - assertEquals(4, shapes.size()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - drawing = sheet.createDrawingPatriarch(); - - shapes = drawing.getShapes(); - assertEquals(4, shapes.size()); - wb2.close(); - } - - @Test - void testXSSFSAddPicture() throws Exception { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - //multiple calls of createDrawingPatriarch should return the same instance of XSSFDrawing - XSSFDrawing dr1 = sheet.createDrawingPatriarch(); - XSSFDrawing dr2 = sheet.createDrawingPatriarch(); - assertSame(dr1, dr2); - - List<RelationPart> rels = sheet.getRelationParts(); - assertEquals(1, rels.size()); - RelationPart rp = rels.get(0); - assertTrue(rp.getDocumentPart() instanceof XSSFDrawing); - - assertEquals(0, rp.getDocumentPart().getRelations().size()); - - XSSFDrawing drawing = rp.getDocumentPart(); - String drawingId = rp.getRelationship().getId(); - - //there should be a relation to this drawing in the worksheet - assertTrue(sheet.getCTWorksheet().isSetDrawing()); - assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId()); - - byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("45829.png"); - - ClientAnchor anchor = wb1.getCreationHelper().createClientAnchor(); - anchor.setCol1(1); - anchor.setRow1(1); - - drawing.createPicture(anchor, wb1.addPicture(pictureData, Workbook.PICTURE_TYPE_JPEG)); - final int pictureIndex = wb1.addPicture(pictureData, Workbook.PICTURE_TYPE_JPEG); - drawing.createPicture(anchor, pictureIndex); - drawing.createPicture(anchor, pictureIndex); - - // repeated additions of same share package relationship - assertEquals(2, rp.getDocumentPart().getPackagePart().getRelationships().size()); - - List<XSSFShape> shapes = drawing.getShapes(); - assertEquals(3, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFPicture); - assertTrue(shapes.get(1) instanceof XSSFPicture); - - // Save and re-load it - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - // Check - dr1 = sheet.createDrawingPatriarch(); - CTDrawing ctDrawing = dr1.getCTDrawing(); - - // Connector, shapes and text boxes are all two cell anchors - assertEquals(0, ctDrawing.sizeOfAbsoluteAnchorArray()); - assertEquals(0, ctDrawing.sizeOfOneCellAnchorArray()); - assertEquals(3, ctDrawing.sizeOfTwoCellAnchorArray()); - - shapes = dr1.getShapes(); - assertEquals(3, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFPicture); - assertTrue(shapes.get(1) instanceof XSSFPicture); - - checkRewrite(wb2); - wb2.close(); - } - - @Test - void testBug56835CellComment() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - // first comment works - ClientAnchor anchor = new XSSFClientAnchor(1, 1, 2, 2, 3, 3, 4, 4); - XSSFComment comment = drawing.createCellComment(anchor); - assertNotNull(comment); - - // Should fail if we try to add the same comment for the same cell - assertThrows(IllegalArgumentException.class, () -> drawing.createCellComment(anchor)); - } - } - - @Test - void testGroupShape() throws Exception { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFSimpleShape s0 = drawing.createSimpleShape(drawing.createAnchor(0, 0, Units.pixelToEMU(30), Units.pixelToEMU(30), 1, 1, 10, 10)); - s0.setShapeType(ShapeTypes.RECT); - s0.setLineStyleColor(100, 0, 0); - - XSSFShapeGroup g1 = drawing.createGroup(drawing.createAnchor(0, 0, 300, 300, 1, 1, 10, 10)); - CTGroupTransform2D xfrmG1 = g1.getCTGroupShape().getGrpSpPr().getXfrm(); - - XSSFSimpleShape s1 = g1.createSimpleShape(new XSSFChildAnchor( - (int)(xfrmG1.getChExt().getCx()*0.1), - (int)(xfrmG1.getChExt().getCy()*0.1), - (int)(xfrmG1.getChExt().getCx()*0.9), - (int)(xfrmG1.getChExt().getCy()*0.9) - )); - s1.setShapeType(ShapeTypes.RECT); - s1.setLineStyleColor(0, 100, 0); - - XSSFShapeGroup g2 = g1.createGroup(new XSSFChildAnchor( - (int)(xfrmG1.getChExt().getCx()*0.2), - (int)(xfrmG1.getChExt().getCy()*0.2), - (int)(xfrmG1.getChExt().getCx()*0.8), - (int)(xfrmG1.getChExt().getCy()*0.8) - )); - CTGroupTransform2D xfrmG2 = g2.getCTGroupShape().getGrpSpPr().getXfrm(); - - XSSFSimpleShape s2 = g2.createSimpleShape(new XSSFChildAnchor( - (int)(xfrmG2.getChExt().getCx()*0.1), - (int)(xfrmG2.getChExt().getCy()*0.1), - (int)(xfrmG2.getChExt().getCx()*0.9), - (int)(xfrmG2.getChExt().getCy()*0.9) - )); - s2.setShapeType(ShapeTypes.RECT); - s2.setLineStyleColor(0, 0, 100); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - XSSFDrawing draw = wb2.getSheetAt(0).getDrawingPatriarch(); - List<XSSFShape> shapes = draw.getShapes(); - assertEquals(2, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - assertTrue(shapes.get(1) instanceof XSSFShapeGroup); - shapes = draw.getShapes((XSSFShapeGroup)shapes.get(1)); - assertEquals(2, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - assertTrue(shapes.get(1) instanceof XSSFShapeGroup); - shapes = draw.getShapes((XSSFShapeGroup)shapes.get(1)); - assertEquals(1, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - - wb2.close(); - } - - @Test - void testBug63901() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("chartTitle_withTitle.xlsx")) { - XSSFSheet sheet = workbook.getSheetAt(0); - XSSFDrawing drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getCharts().size()); - - XSSFWorkbook workbook2 = new XSSFWorkbook(); - XSSFSheet sheet2 = workbook2.createSheet(); - XSSFDrawing drawing2 = sheet2.createDrawingPatriarch(); - - drawing.getCharts().forEach(drawing2::importChart); - assertEquals(1, drawing2.getCharts().size()); - } - } - - private static void checkRewrite(XSSFWorkbook wb) throws IOException { - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wb2); - wb2.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvaluationSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvaluationSheet.java deleted file mode 100644 index 431f585b60..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvaluationSheet.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -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 java.util.AbstractMap; -import java.util.Map; - -import org.apache.poi.ss.formula.EvaluationSheet; -import org.apache.poi.ss.usermodel.BaseTestXEvaluationSheet; -import org.apache.poi.ss.usermodel.Sheet; -import org.junit.jupiter.api.Test; - -class TestXSSFEvaluationSheet extends BaseTestXEvaluationSheet { - - @Test - void test() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("test"); - XSSFRow row = sheet.createRow(0); - row.createCell(0); - XSSFEvaluationSheet evalsheet = new XSSFEvaluationSheet(sheet); - - assertNotNull(evalsheet.getCell(0, 0), "Cell 0,0 is found"); - assertNull(evalsheet.getCell(0, 1), "Cell 0,1 is not found"); - assertNull(evalsheet.getCell(1, 0), "Cell 1,0 is not found"); - - // now add Cell 0,1 - row.createCell(1); - - assertNotNull(evalsheet.getCell(0, 0), "Cell 0,0 is found"); - assertNotNull(evalsheet.getCell(0, 1), "Cell 0,1 is now also found"); - assertNull(evalsheet.getCell(1, 0), "Cell 1,0 is not found"); - - // after clearing all values it also works - row.createCell(2); - evalsheet.clearAllCachedResultValues(); - - assertNotNull(evalsheet.getCell(0, 0), "Cell 0,0 is found"); - assertNotNull(evalsheet.getCell(0, 2), "Cell 0,2 is now also found"); - assertNull(evalsheet.getCell(1, 0), "Cell 1,0 is not found"); - - // other things - assertEquals(sheet, evalsheet.getXSSFSheet()); - } - - @Override - protected Map.Entry<Sheet, EvaluationSheet> getInstance() { - XSSFSheet sheet = new XSSFWorkbook().createSheet(); - return new AbstractMap.SimpleEntry<>(sheet, new XSSFEvaluationSheet(sheet)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenFooter.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenFooter.java deleted file mode 100644 index 7c119fa851..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenFooter.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestXSSFEvenFooter { - - private XSSFWorkbook wb; - private XSSFSheet sheet; - - @BeforeEach - void before() { - wb = new XSSFWorkbook(); - sheet = wb.createSheet(); - } - - @AfterEach - void after() throws Exception { - wb.close(); - } - - @Test - void testSetGetText() { - XSSFEvenFooter footer = (XSSFEvenFooter) sheet.getEvenFooter(); - assertNotNull(footer); - assertNull(footer.getText()); - footer.setText("this is a test"); - assertEquals("this is a test", footer.getText()); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenHeader.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenHeader.java deleted file mode 100644 index d717a699ea..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvenHeader.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestXSSFEvenHeader { - - private XSSFWorkbook wb; - private XSSFSheet sheet; - - @BeforeEach - void before() { - wb = new XSSFWorkbook(); - sheet = wb.createSheet(); - } - - @AfterEach - void after() throws Exception { - wb.close(); - } - - @Test - void testSetGetText() { - XSSFEvenHeader header = (XSSFEvenHeader) sheet.getEvenHeader(); - assertNotNull(header); - assertNull(header.getText()); - header.setText("this is a test"); - assertEquals("this is a test", header.getText()); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFExternalFunctions.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFExternalFunctions.java deleted file mode 100644 index 219b8423cc..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFExternalFunctions.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.formula.BaseTestExternalFunctions; -import org.apache.poi.xssf.XSSFITestDataProvider; - -/** - * Tests setting and evaluating user-defined functions in HSSF - */ -public final class TestXSSFExternalFunctions extends BaseTestExternalFunctions { - public TestXSSFExternalFunctions() { - super(XSSFITestDataProvider.instance, "atp.xlsx"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstFooter.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstFooter.java deleted file mode 100644 index 1914f49d54..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstFooter.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestXSSFFirstFooter { - - private XSSFWorkbook wb; - private XSSFSheet sheet; - - @BeforeEach - void before() { - wb = new XSSFWorkbook(); - sheet = wb.createSheet(); - } - - @AfterEach - void after() throws Exception { - wb.close(); - } - - @Test - void testSetGetText() { - XSSFFirstFooter footer = (XSSFFirstFooter) sheet.getFirstFooter(); - assertNotNull(footer); - assertNull(footer.getText()); - footer.setText("this is a test"); - assertEquals("this is a test", footer.getText()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstHeader.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstHeader.java deleted file mode 100644 index 8a67d6aa3b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFirstHeader.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestXSSFFirstHeader { - - private XSSFWorkbook wb; - private XSSFSheet sheet; - - @BeforeEach - void before() { - wb = new XSSFWorkbook(); - sheet = wb.createSheet(); - } - - @AfterEach - void after() throws Exception { - wb.close(); - } - - @Test - void testSetGetText() { - XSSFFirstHeader header = (XSSFFirstHeader) sheet.getFirstHeader(); - assertNotNull(header); - assertNull(header.getText()); - header.setText("this is a test"); - assertEquals("this is a test", header.getText()); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFont.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFont.java deleted file mode 100644 index 6ec3eb8aaa..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFont.java +++ /dev/null @@ -1,499 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import java.io.IOException; -import java.util.stream.Stream; - -import org.apache.poi.common.usermodel.fonts.FontCharset; -import org.apache.poi.ooxml.POIXMLException; -import org.apache.poi.ss.usermodel.BaseTestFont; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.FontFamily; -import org.apache.poi.ss.usermodel.FontScheme; -import org.apache.poi.ss.usermodel.FontUnderline; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.SheetUtil; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.provider.Arguments; -import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STVerticalAlignRun; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBooleanProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFontFamily; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFontName; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFontScheme; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFontSize; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTIntProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTUnderlineProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTVerticalAlignFontProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STFontScheme; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STUnderlineValues; - -public final class TestXSSFFont extends BaseTestFont{ - - public TestXSSFFont() { - super(XSSFITestDataProvider.instance); - } - - @SuppressWarnings("unused") - public static Stream<Arguments> defaultFont() { - return Stream.of(Arguments.of("Calibri", (short) 220, IndexedColors.BLACK.getIndex())); - } - - @Test - void testConstructor() { - XSSFFont xssfFont=new XSSFFont(); - assertNotNull(xssfFont.getCTFont()); - } - - @Test - void testBold() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTBooleanProperty bool=ctFont.addNewB(); - bool.setVal(false); - ctFont.setBArray(0,bool); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertFalse(xssfFont.getBold()); - - - xssfFont.setBold(true); - assertEquals(ctFont.sizeOfBArray(),1); - assertTrue(ctFont.getBArray(0).getVal()); - } - - @SuppressWarnings("deprecation") - @Test - void testCharSetWithDeprecatedFontCharset() throws IOException { - CTFont ctFont=CTFont.Factory.newInstance(); - CTIntProperty prop=ctFont.addNewCharset(); - prop.setVal(org.apache.poi.ss.usermodel.FontCharset.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()); - - // 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()); - // 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()); - - // This one isn't allowed - assertNull(org.apache.poi.ss.usermodel.FontCharset.valueOf(9999)); - assertThrows(POIXMLException.class, () -> xssfFont.setCharSet(9999), - "Shouldn't be able to set an invalid charset"); - - // Now try with a few sample files - - // Normal charset - try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx")) { - assertEquals(0, - wb1.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - } - - // GB2312 charset - try (XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("49273.xlsx")) { - assertEquals(134, - wb2.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - } - } - - @Test - void testCharSet() throws IOException { - CTFont ctFont=CTFont.Factory.newInstance(); - CTIntProperty prop=ctFont.addNewCharset(); - prop.setVal(FontCharset.ANSI.getNativeId()); - - ctFont.setCharsetArray(0,prop); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(Font.ANSI_CHARSET,xssfFont.getCharSet()); - - xssfFont.setCharSet(FontCharset.DEFAULT); - assertEquals(FontCharset.DEFAULT.getNativeId(),ctFont.getCharsetArray(0).getVal()); - - // Try with a few less usual ones: - // Set with the Charset itself - xssfFont.setCharSet(FontCharset.RUSSIAN); - assertEquals(FontCharset.RUSSIAN.getNativeId(), xssfFont.getCharSet()); - // And set with the Charset index - xssfFont.setCharSet(FontCharset.ARABIC.getNativeId()); - assertEquals(FontCharset.ARABIC.getNativeId(), xssfFont.getCharSet()); - xssfFont.setCharSet((byte)(FontCharset.ARABIC.getNativeId())); - assertEquals(FontCharset.ARABIC.getNativeId(), xssfFont.getCharSet()); - - // This one isn't allowed - assertNull(FontCharset.valueOf(9999)); - assertThrows(POIXMLException.class, () -> xssfFont.setCharSet(9999), "Shouldn't be able to set an invalid charset"); - - // Now try with a few sample files - - // Normal charset - try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx")) { - assertEquals(0, - wb1.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - } - - // GB2312 charset - try (XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("49273.xlsx")) { - assertEquals(134, - wb2.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - } - } - - @Test - void testFontName() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontName fname=ctFont.addNewName(); - fname.setVal("Arial"); - ctFont.setNameArray(0,fname); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals("Arial", xssfFont.getFontName()); - - xssfFont.setFontName("Courier"); - assertEquals("Courier",ctFont.getNameArray(0).getVal()); - } - - @Test - void testItalic() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTBooleanProperty bool=ctFont.addNewI(); - bool.setVal(false); - ctFont.setIArray(0,bool); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertFalse(xssfFont.getItalic()); - - xssfFont.setItalic(true); - assertEquals(ctFont.sizeOfIArray(),1); - assertTrue(ctFont.getIArray(0).getVal()); - assertTrue(ctFont.getIArray(0).getVal()); - } - - @Test - void testStrikeout() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTBooleanProperty bool=ctFont.addNewStrike(); - bool.setVal(false); - ctFont.setStrikeArray(0,bool); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertFalse(xssfFont.getStrikeout()); - - xssfFont.setStrikeout(true); - assertEquals(ctFont.sizeOfStrikeArray(),1); - assertTrue(ctFont.getStrikeArray(0).getVal()); - assertTrue(ctFont.getStrikeArray(0).getVal()); - } - - @Test - void testFontHeight() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontSize size=ctFont.addNewSz(); - size.setVal(11); - ctFont.setSzArray(0,size); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(11,xssfFont.getFontHeightInPoints()); - - xssfFont.setFontHeight(20); - assertEquals(20.0, ctFont.getSzArray(0).getVal(), 0.0); - } - - @Test - void testFontHeightInPoint() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontSize size=ctFont.addNewSz(); - size.setVal(14); - ctFont.setSzArray(0,size); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(14,xssfFont.getFontHeightInPoints()); - - xssfFont.setFontHeightInPoints((short)20); - assertEquals(20.0, ctFont.getSzArray(0).getVal(), 0.0); - } - - @Test - void testUnderline() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTUnderlineProperty underlinePropr=ctFont.addNewU(); - underlinePropr.setVal(STUnderlineValues.SINGLE); - ctFont.setUArray(0,underlinePropr); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(Font.U_SINGLE, xssfFont.getUnderline()); - - xssfFont.setUnderline(Font.U_DOUBLE); - assertEquals(ctFont.sizeOfUArray(),1); - assertEquals(STUnderlineValues.DOUBLE,ctFont.getUArray(0).getVal()); - - xssfFont.setUnderline(FontUnderline.DOUBLE_ACCOUNTING); - assertEquals(ctFont.sizeOfUArray(),1); - assertEquals(STUnderlineValues.DOUBLE_ACCOUNTING,ctFont.getUArray(0).getVal()); - } - - @Test - void testColor() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTColor color=ctFont.addNewColor(); - color.setIndexed(XSSFFont.DEFAULT_FONT_COLOR); - ctFont.setColorArray(0,color); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(IndexedColors.BLACK.getIndex(),xssfFont.getColor()); - - xssfFont.setColor(IndexedColors.RED.getIndex()); - assertEquals(IndexedColors.RED.getIndex(), ctFont.getColorArray(0).getIndexed()); - } - - @Test - void testRgbColor() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTColor color=ctFont.addNewColor(); - - color.setRgb(Integer.toHexString(0xFFFFFF).getBytes(LocaleUtil.CHARSET_1252)); - ctFont.setColorArray(0,color); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(ctFont.getColorArray(0).getRgb()[0],xssfFont.getXSSFColor().getRGB()[0]); - assertEquals(ctFont.getColorArray(0).getRgb()[1],xssfFont.getXSSFColor().getRGB()[1]); - assertEquals(ctFont.getColorArray(0).getRgb()[2],xssfFont.getXSSFColor().getRGB()[2]); - assertEquals(ctFont.getColorArray(0).getRgb()[3],xssfFont.getXSSFColor().getRGB()[3]); - - xssfFont.setColor((short)23); - - byte[] bytes = Integer.toHexString(0xF1F1F1).getBytes(LocaleUtil.CHARSET_1252); - color.setRgb(bytes); - XSSFColor newColor=XSSFColor.from(color, null); - xssfFont.setColor(newColor); - assertEquals(ctFont.getColorArray(0).getRgb()[2],newColor.getRGB()[2]); - - assertArrayEquals(bytes, xssfFont.getXSSFColor().getRGB()); - assertEquals(0, xssfFont.getColor()); - } - - @Test - void testThemeColor() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTColor color=ctFont.addNewColor(); - color.setTheme(1); - ctFont.setColorArray(0,color); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(ctFont.getColorArray(0).getTheme(),xssfFont.getThemeColor()); - - xssfFont.setThemeColor(IndexedColors.RED.getIndex()); - assertEquals(IndexedColors.RED.getIndex(),ctFont.getColorArray(0).getTheme()); - } - - @Test - void testFamily() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontFamily family=ctFont.addNewFamily(); - family.setVal(FontFamily.MODERN.getValue()); - ctFont.setFamilyArray(0,family); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(FontFamily.MODERN.getValue(),xssfFont.getFamily()); - } - - @Test - void testScheme() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontScheme scheme=ctFont.addNewScheme(); - scheme.setVal(STFontScheme.MAJOR); - ctFont.setSchemeArray(0,scheme); - - XSSFFont font=new XSSFFont(ctFont); - assertEquals(FontScheme.MAJOR,font.getScheme()); - - font.setScheme(FontScheme.NONE); - assertEquals(STFontScheme.NONE,ctFont.getSchemeArray(0).getVal()); - } - - @Test - void testTypeOffset() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTVerticalAlignFontProperty valign=ctFont.addNewVertAlign(); - valign.setVal(STVerticalAlignRun.BASELINE); - ctFont.setVertAlignArray(0,valign); - - XSSFFont font=new XSSFFont(ctFont); - assertEquals(Font.SS_NONE,font.getTypeOffset()); - - font.setTypeOffset(XSSFFont.SS_SUPER); - assertEquals(STVerticalAlignRun.SUPERSCRIPT,ctFont.getVertAlignArray(0).getVal()); - } - - // store test from TestSheetUtil here as it uses XSSF - @Test - void testCanComputeWidthXSSF() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - - // cannot check on result because on some machines we get back false here! - SheetUtil.canComputeColumnWidth(wb.getFontAt(0)); - - } - } - - // store test from TestSheetUtil here as it uses XSSF - @Test - void testCanComputeWidthInvalidFont() { - Font font = new XSSFFont(CTFont.Factory.newInstance()); - font.setFontName("some non existing font name"); - - // Even with invalid fonts we still get back useful data most of the time... - SheetUtil.canComputeColumnWidth(font); - } - - /** - * Test that fonts get added properly - */ - @Test - void testFindFont() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - assertEquals(1, wb.getNumberOfFonts()); - - XSSFSheet s = wb.createSheet(); - s.createRow(0); - s.createRow(1); - s.getRow(0).createCell(0); - s.getRow(1).createCell(0); - - assertEquals(1, wb.getNumberOfFonts()); - - XSSFFont f1 = wb.getFontAt(0); - assertFalse(f1.getBold()); - - // Check that asking for the same font - // multiple times gives you the same thing. - // Otherwise, our tests wouldn't work! - assertSame(wb.getFontAt(0), wb.getFontAt(0)); - assertEquals( - wb.getFontAt(0), - wb.getFontAt(0) - ); - - // Look for a new font we have - // yet to add - assertNull( - wb.findFont( - false, IndexedColors.INDIGO.getIndex(), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - assertNull( - wb.getStylesSource().findFont( - false, new XSSFColor(IndexedColors.INDIGO, new DefaultIndexedColorMap()), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - - XSSFFont nf = wb.createFont(); - assertEquals(2, wb.getNumberOfFonts()); - - assertEquals(1, nf.getIndex()); - assertEquals(nf, wb.getFontAt(1)); - - nf.setBold(false); - nf.setColor(IndexedColors.INDIGO.getIndex()); - nf.setFontHeight((short) 22); - nf.setFontName("Thingy"); - nf.setItalic(false); - nf.setStrikeout(true); - nf.setTypeOffset((short) 2); - nf.setUnderline((byte) 2); - - assertEquals(2, wb.getNumberOfFonts()); - assertEquals(nf, wb.getFontAt(1)); - - assertNotSame(wb.getFontAt(0), wb.getFontAt(1)); - - // Find it now - assertNotNull( - wb.findFont( - false, IndexedColors.INDIGO.getIndex(), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - assertNotNull( - wb.getStylesSource().findFont( - false, new XSSFColor(IndexedColors.INDIGO, new DefaultIndexedColorMap()), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - - XSSFFont font = wb.findFont( - false, IndexedColors.INDIGO.getIndex(), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ); - assertNotNull(font); - assertEquals( - 1, - font.getIndex() - ); - assertEquals(nf, - wb.findFont( - false, IndexedColors.INDIGO.getIndex(), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - assertEquals(nf, - wb.getStylesSource().findFont( - false, new XSSFColor(IndexedColors.INDIGO, new DefaultIndexedColorMap()), (short) 22, - "Thingy", false, true, (short) 2, (byte) 2 - ) - ); - - } - } - - @Test - void testEquals() { - XSSFFont font = new XSSFFont(); - XSSFFont equ = new XSSFFont(); - XSSFFont notequ = new XSSFFont(); - notequ.setItalic(true); - - assertEquals(equ, font); - assertNotEquals(font, notequ); - - notequ.setItalic(false); - notequ.setThemeColor((short)123); - assertNotEquals(font, notequ); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFForkedEvaluator.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFForkedEvaluator.java deleted file mode 100644 index 9a391019f5..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFForkedEvaluator.java +++ /dev/null @@ -1,29 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.formula.eval.forked.BaseTestForkedEvaluator; -import org.apache.poi.ss.usermodel.Workbook; - -class TestXSSFForkedEvaluator extends BaseTestForkedEvaluator { - - @Override - protected Workbook newWorkbook() { - return new XSSFWorkbook(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java deleted file mode 100644 index 887e23ae11..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java +++ /dev/null @@ -1,447 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { - - public TestXSSFFormulaEvaluation() { - super(XSSFITestDataProvider.instance); - } - - @Test - void testSharedFormulas_evaluateInCell() throws IOException { - try (Workbook wb = _testDataProvider.openSampleWorkbook("49872.xlsx")) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet sheet = wb.getSheetAt(0); - - double result = 3.0; - - // B3 is a master shared formula, C3 and D3 don't have the formula written in their f element. - // Instead, the attribute si for a particular cell is used to figure what the formula expression - // should be based on the cell's relative location to the master formula, e.g. - // B3: <f t="shared" ref="B3:D3" si="0">B1+B2</f> - // C3 and D3: <f t="shared" si="0"/> - - // get B3 and evaluate it in the cell - Cell b3 = sheet.getRow(2).getCell(1); - assertEquals(result, evaluator.evaluateInCell(b3).getNumericCellValue(), 0); - - //at this point the master formula is gone, but we are still able to evaluate dependent cells - Cell c3 = sheet.getRow(2).getCell(2); - assertEquals(result, evaluator.evaluateInCell(c3).getNumericCellValue(), 0); - - Cell d3 = sheet.getRow(2).getCell(3); - assertEquals(result, evaluator.evaluateInCell(d3).getNumericCellValue(), 0); - } - } - - /** - * Evaluation of cell references with column indexes greater than 255. See bugzilla 50096 - */ - @Test - void testEvaluateColumnGreaterThan255() throws IOException { - try (Workbook wb = _testDataProvider.openSampleWorkbook("50096.xlsx")) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - /* - * The first row simply contains the numbers 1 - 300. - * The second row simply refers to the cell value above in the first row by a simple formula. - */ - for (int i = 245; i < 265; i++) { - Cell cell_noformula = wb.getSheetAt(0).getRow(0).getCell(i); - Cell cell_formula = wb.getSheetAt(0).getRow(1).getCell(i); - - CellReference ref_noformula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex()); - CellReference ref_formula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex()); - String fmla = cell_formula.getCellFormula(); - // assure that the formula refers to the cell above. - // the check below is 'deep' and involves conversion of the shared formula: - // in the sample file a shared formula in GN1 is spanned in the range GN2:IY2, - assertEquals(ref_noformula.formatAsString(), fmla); - - CellValue cv_noformula = evaluator.evaluate(cell_noformula); - CellValue cv_formula = evaluator.evaluate(cell_formula); - assertEquals(cv_noformula.getNumberValue(), cv_formula.getNumberValue(), 0, - "Wrong evaluation result in " + ref_formula.formatAsString()); - } - } - } - - /** - * Related to bugs #56737 and #56752 - XSSF workbooks which have - * formulas that refer to cells and named ranges in multiple other - * workbooks, both HSSF and XSSF ones - */ - @Test - void testReferencesToOtherWorkbooks() throws Exception { - try (Workbook wb = _testDataProvider.openSampleWorkbook("ref2-56737.xlsx")) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet s = wb.getSheetAt(0); - - // References to a .xlsx file - Row rXSLX = s.getRow(2); - Cell cXSLX_cell = rXSLX.getCell(4); - Cell cXSLX_sNR = rXSLX.getCell(6); - Cell cXSLX_gNR = rXSLX.getCell(8); - assertEquals("[1]Uses!$A$1", cXSLX_cell.getCellFormula()); - assertEquals("[1]Defines!NR_To_A1", cXSLX_sNR.getCellFormula()); - assertEquals("[1]!NR_Global_B2", cXSLX_gNR.getCellFormula()); - - assertEquals("Hello!", cXSLX_cell.getStringCellValue()); - assertEquals("Test A1", cXSLX_sNR.getStringCellValue()); - assertEquals(142.0, cXSLX_gNR.getNumericCellValue(), 0); - - // References to a .xls file - Row rXSL = s.getRow(4); - Cell cXSL_cell = rXSL.getCell(4); - Cell cXSL_sNR = rXSL.getCell(6); - Cell cXSL_gNR = rXSL.getCell(8); - assertEquals("[2]Uses!$C$1", cXSL_cell.getCellFormula()); - assertEquals("[2]Defines!NR_To_A1", cXSL_sNR.getCellFormula()); - assertEquals("[2]!NR_Global_B2", cXSL_gNR.getCellFormula()); - - assertEquals("Hello!", cXSL_cell.getStringCellValue()); - assertEquals("Test A1", cXSL_sNR.getStringCellValue()); - assertEquals(142.0, cXSL_gNR.getNumericCellValue(), 0); - - // Try to evaluate without references, won't work - // (At least, not unit we fix bug #56752 that is) - assertThrows(Exception.class, () -> evaluator.evaluate(cXSL_cell), - "Without a fix for #56752, shouldn't be able to evaluate a reference to a non-provided linked workbook"); - - // Setup the environment - Map<String, FormulaEvaluator> evaluators = new HashMap<>(); - evaluators.put("ref2-56737.xlsx", evaluator); - try (Workbook wbEval1 = _testDataProvider.openSampleWorkbook("56737.xlsx"); - Workbook wbEval2 = HSSFTestDataSamples.openSampleWorkbook("56737.xls")) { - evaluators.put("56737.xlsx", wbEval1.getCreationHelper().createFormulaEvaluator()); - evaluators.put("56737.xls", wbEval2.getCreationHelper().createFormulaEvaluator()); - evaluator.setupReferencedWorkbooks(evaluators); - - // Try evaluating all of them, ensure we don't blow up - for (Row r : s) { - for (Cell c : r) { - evaluator.evaluate(c); - } - } - // And evaluate the other way too - evaluator.evaluateAll(); - - // Static evaluator won't work, as no references passed in - assertThrows(Exception.class, () -> XSSFFormulaEvaluator.evaluateAllFormulaCells(wb), - "Static method lacks references, shouldn't work"); - - // Evaluate specific cells and check results - assertEquals("\"Hello!\"", evaluator.evaluate(cXSLX_cell).formatAsString()); - assertEquals("\"Test A1\"", evaluator.evaluate(cXSLX_sNR).formatAsString()); - assertEquals("142.0", evaluator.evaluate(cXSLX_gNR).formatAsString()); - - assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell).formatAsString()); - assertEquals("\"Test A1\"", evaluator.evaluate(cXSL_sNR).formatAsString()); - assertEquals("142.0", evaluator.evaluate(cXSL_gNR).formatAsString()); - - - // Add another formula referencing these workbooks - Cell cXSL_cell2 = rXSL.createCell(40); - cXSL_cell2.setCellFormula("[56737.xls]Uses!$C$1"); - // TODO Shouldn't it become [2] like the others? - assertEquals("[56737.xls]Uses!$C$1", cXSL_cell2.getCellFormula()); - assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell2).formatAsString()); - - - // Now add a formula that refers to yet another (different) workbook - // Won't work without the workbook being linked - Cell cXSLX_nw_cell = rXSLX.createCell(42); - assertThrows(Exception.class, () -> cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1"), - "New workbook not linked, shouldn't be able to add"); - } - - // Link and re-try - try (Workbook alt = new XSSFWorkbook()) { - alt.createSheet().createRow(0).createCell(0).setCellValue("In another workbook"); - // TODO Implement the rest of this, see bug #57184 -/* - wb.linkExternalWorkbook("alt.xlsx", alt); - - cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1"); - // Check it - TODO Is this correct? Or should it become [3]Sheet1!$A$1 ? - assertEquals("[alt.xlsx]Sheet1!$A$1", cXSLX_nw_cell.getCellFormula()); - - // Evaluate it, without a link to that workbook - assertThrows(Exception.class, () -> evaluator.evaluate(cXSLX_nw_cell), - "No cached value and no link to workbook, shouldn't evaluate"); - - // Add a link, check it does - evaluators.put("alt.xlsx", alt.getCreationHelper().createFormulaEvaluator()); - evaluator.setupReferencedWorkbooks(evaluators); - - evaluator.evaluate(cXSLX_nw_cell); - assertEquals("In another workbook", cXSLX_nw_cell.getStringCellValue()); -*/ - } - } - } - - /* - * If a formula references cells or named ranges in another workbook, - * but that isn't available at evaluation time, the cached values - * should be used instead - * TODO Add the support then add a unit test - * See bug #56752 - */ -// @Disabled -// void testCachedReferencesToOtherWorkbooks() { -// } - - /** - * A handful of functions (such as SUM, COUNTA, MIN) support - * multi-sheet references (eg Sheet1:Sheet3!A1 = Cell A1 from - * Sheets 1 through Sheet 3). - * This test, based on common test files for HSSF and XSSF, checks - * that we can correctly evaluate these - */ - @ParameterizedTest - @ValueSource(strings = {"55906-MultiSheetRefs.xls","55906-MultiSheetRefs.xlsx"}) - void testMultiSheetReferencesHSSFandXSSF(String sampleFileName) throws Exception { - Function<String, Workbook> fun = sampleFileName.endsWith("x") - ? XSSFTestDataSamples::openSampleWorkbook : HSSFTestDataSamples::openSampleWorkbook; - - try (Workbook wb = fun.apply(sampleFileName)) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet s1 = wb.getSheetAt(0); - - - // Simple SUM over numbers - Cell sumF = s1.getRow(2).getCell(0); - assertNotNull(sumF); - assertEquals("SUM(Sheet1:Sheet3!A1)", sumF.getCellFormula()); - assertEquals("66.0", evaluator.evaluate(sumF).formatAsString(), "Failed for " + wb.getClass()); - - - // Various Stats formulas on numbers - Cell avgF = s1.getRow(2).getCell(1); - assertNotNull(avgF); - assertEquals("AVERAGE(Sheet1:Sheet3!A1)", avgF.getCellFormula()); - assertEquals("22.0", evaluator.evaluate(avgF).formatAsString()); - - Cell minF = s1.getRow(3).getCell(1); - assertNotNull(minF); - assertEquals("MIN(Sheet1:Sheet3!A$1)", minF.getCellFormula()); - assertEquals("11.0", evaluator.evaluate(minF).formatAsString()); - - Cell maxF = s1.getRow(4).getCell(1); - assertNotNull(maxF); - assertEquals("MAX(Sheet1:Sheet3!A$1)", maxF.getCellFormula()); - assertEquals("33.0", evaluator.evaluate(maxF).formatAsString()); - - Cell countF = s1.getRow(5).getCell(1); - assertNotNull(countF); - assertEquals("COUNT(Sheet1:Sheet3!A$1)", countF.getCellFormula()); - assertEquals("3.0", evaluator.evaluate(countF).formatAsString()); - - - // Various CountAs on Strings - Cell countA_1F = s1.getRow(2).getCell(2); - assertNotNull(countA_1F); - assertEquals("COUNTA(Sheet1:Sheet3!C1)", countA_1F.getCellFormula()); - assertEquals("3.0", evaluator.evaluate(countA_1F).formatAsString()); - - Cell countA_2F = s1.getRow(2).getCell(3); - assertNotNull(countA_2F); - assertEquals("COUNTA(Sheet1:Sheet3!D1)", countA_2F.getCellFormula()); - assertEquals("0.0", evaluator.evaluate(countA_2F).formatAsString()); - - Cell countA_3F = s1.getRow(2).getCell(4); - assertNotNull(countA_3F); - assertEquals("COUNTA(Sheet1:Sheet3!E1)", countA_3F.getCellFormula()); - assertEquals("3.0", evaluator.evaluate(countA_3F).formatAsString()); - } - } - - /** - * A handful of functions (such as SUM, COUNTA, MIN) support - * multi-sheet areas (eg Sheet1:Sheet3!A1:B2 = Cell A1 to Cell B2, - * from Sheets 1 through Sheet 3). - * This test, based on common test files for HSSF and XSSF, checks - * that we can correctly evaluate these - */ - @ParameterizedTest - @ValueSource(strings = {"55906-MultiSheetRefs.xls","55906-MultiSheetRefs.xlsx"}) - void testMultiSheetAreasHSSFandXSSF(String sampleFileName) throws Exception { - Function<String, Workbook> fun = sampleFileName.endsWith("x") - ? XSSFTestDataSamples::openSampleWorkbook : HSSFTestDataSamples::openSampleWorkbook; - - try (Workbook wb = fun.apply(sampleFileName)) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet s1 = wb.getSheetAt(0); - - - // SUM over a range - Cell sumFA = s1.getRow(2).getCell(7); - assertNotNull(sumFA); - assertEquals("SUM(Sheet1:Sheet3!A1:B2)", sumFA.getCellFormula()); - assertEquals("110.0", evaluator.evaluate(sumFA).formatAsString(), "Failed for " + wb.getClass()); - - - // Various Stats formulas on ranges of numbers - Cell avgFA = s1.getRow(2).getCell(8); - assertNotNull(avgFA); - assertEquals("AVERAGE(Sheet1:Sheet3!A1:B2)", avgFA.getCellFormula()); - assertEquals("27.5", evaluator.evaluate(avgFA).formatAsString()); - - Cell minFA = s1.getRow(3).getCell(8); - assertNotNull(minFA); - assertEquals("MIN(Sheet1:Sheet3!A$1:B$2)", minFA.getCellFormula()); - assertEquals("11.0", evaluator.evaluate(minFA).formatAsString()); - - Cell maxFA = s1.getRow(4).getCell(8); - assertNotNull(maxFA); - assertEquals("MAX(Sheet1:Sheet3!A$1:B$2)", maxFA.getCellFormula()); - assertEquals("44.0", evaluator.evaluate(maxFA).formatAsString()); - - Cell countFA = s1.getRow(5).getCell(8); - assertNotNull(countFA); - assertEquals("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.getCellFormula()); - assertEquals("4.0", evaluator.evaluate(countFA).formatAsString()); - } - } - - @ParameterizedTest - @ValueSource(strings = { - // bug 57721 - "evaluate_formula_with_structured_table_references.xlsx" - - // bug 57840: - // Takes over a minute to evaluate all formulas in this large workbook. Run this test when profiling for formula evaluation speed. - // , "StructuredRefs-lots-with-lookups.xlsx" - }) - void verifyAllFormulasInWorkbookCanBeEvaluated(String sampleWorkbook) throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(sampleWorkbook)) { - assertDoesNotThrow(() -> XSSFFormulaEvaluator.evaluateAllFormulaCells(wb)); - } - } - - @Test - void test59736() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("59736.xlsx")) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell = wb.getSheetAt(0).getRow(0).getCell(0); - assertEquals(1, cell.getNumericCellValue(), 0.001); - - cell = wb.getSheetAt(0).getRow(1).getCell(0); - CellValue value = evaluator.evaluate(cell); - assertEquals(1, value.getNumberValue(), 0.001); - - cell = wb.getSheetAt(0).getRow(2).getCell(0); - value = evaluator.evaluate(cell); - assertEquals(1, value.getNumberValue(), 0.001); - } - } - - @Test - void evaluateInCellReturnsSameDataType() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - wb.createSheet().createRow(0).createCell(0); - XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0); - XSSFCell same = evaluator.evaluateInCell(cell); - assertSame(cell, same); - } - } - - @Test - void testBug61468() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("simple-monthly-budget.xlsx")) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell = wb.getSheetAt(0).getRow(8).getCell(4); - assertEquals(3750, cell.getNumericCellValue(), 0.001); - - CellValue value = evaluator.evaluate(cell); - assertEquals(3750, value.getNumberValue(), 0.001); - } - } - - @Test - @Disabled("this is from an open bug/discussion over handling localization for number formats") - void testBug61495() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("61495-test.xlsm")) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell = wb.getSheetAt(0).getRow(0).getCell(1); - // assertEquals("D 67.10", cell.getStringCellValue()); - - String act = evaluator.evaluate(cell).getStringValue(); - assertEquals("D 67.10", act); - - cell = wb.getSheetAt(0).getRow(1).getCell(1); - act = evaluator.evaluate(cell).getStringValue(); - assertEquals("D 0,068", act); - } - } - - - /** - * see bug 62834, handle when a shared formula range doesn't contain only formula cells - */ - @Test - void testBug62834() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("62834.xlsx")) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Cell a2 = wb.getSheetAt(0).getRow(1).getCell(0); - Cell value = evaluator.evaluateInCell(a2); - assertEquals("a value", value.getStringCellValue(), "wrong value A2"); - - // evaluator.clearAllCachedResultValues(); - - Cell a3 = wb.getSheetAt(0).getRow(2).getCell(0); - value = evaluator.evaluateInCell(a3); - assertEquals("a value", value.getStringCellValue(), "wrong value A3"); - - Cell a5 = wb.getSheetAt(0).getRow(4).getCell(0); - value = evaluator.evaluateInCell(a5); - assertEquals("another value", value.getStringCellValue(), "wrong value A5"); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaParser.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaParser.java deleted file mode 100644 index 7b56cf8965..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaParser.java +++ /dev/null @@ -1,726 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaParsingWorkbook; -import org.apache.poi.ss.formula.FormulaRenderingWorkbook; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.WorkbookDependentFormula; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.Area3DPxg; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.ErrPtg; -import org.apache.poi.ss.formula.ptg.FuncPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.IntPtg; -import org.apache.poi.ss.formula.ptg.IntersectionPtg; -import org.apache.poi.ss.formula.ptg.MemAreaPtg; -import org.apache.poi.ss.formula.ptg.MemFuncPtg; -import org.apache.poi.ss.formula.ptg.NamePtg; -import org.apache.poi.ss.formula.ptg.NameXPxg; -import org.apache.poi.ss.formula.ptg.ParenthesisPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.Ref3DPtg; -import org.apache.poi.ss.formula.ptg.Ref3DPxg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.formula.ptg.StringPtg; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -public final class TestXSSFFormulaParser { - private static Ptg[] parse(FormulaParsingWorkbook fpb, String fmla) { - return FormulaParser.parse(fmla, fpb, FormulaType.CELL, -1); - } - private static Ptg[] parse(FormulaParsingWorkbook fpb, String fmla, int rowIndex) { - return FormulaParser.parse(fmla, fpb, FormulaType.CELL, -1, rowIndex); - } - - @Test - void basicParsing() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - ptgs = parse(fpb, "ABC10"); - assertEquals(1, ptgs.length); - assertTrue(ptgs[0] instanceof RefPtg, "Had " + Arrays.toString(ptgs)); - - ptgs = parse(fpb, "A500000"); - assertEquals(1, ptgs.length); - assertTrue(ptgs[0] instanceof RefPtg, "Had " + Arrays.toString(ptgs)); - - ptgs = parse(fpb, "ABC500000"); - assertEquals(1, ptgs.length); - assertTrue(ptgs[0] instanceof RefPtg, "Had " + Arrays.toString(ptgs)); - - //highest allowed rows and column (XFD and 0x100000) - ptgs = parse(fpb, "XFD1048576"); - assertEquals(1, ptgs.length); - assertTrue(ptgs[0] instanceof RefPtg, "Had " + Arrays.toString(ptgs)); - - - //column greater than XFD - FormulaParseException e; - e = assertThrows(FormulaParseException.class, () -> parse(fpb, "XFE10")); - assertEquals("Specified named range 'XFE10' does not exist in the current workbook.", e.getMessage()); - - //row greater than 0x100000 - e = assertThrows(FormulaParseException.class, () -> parse(fpb, "XFD1048577")); - assertEquals("Specified named range 'XFD1048577' does not exist in the current workbook.", e.getMessage()); - - // Formula referencing one cell - ptgs = parse(fpb, "ISEVEN(A1)"); - assertEquals(3, ptgs.length); - assertEquals(NameXPxg.class, ptgs[0].getClass()); - assertEquals(RefPtg.class, ptgs[1].getClass()); - assertEquals(FuncVarPtg.class, ptgs[2].getClass()); - assertEquals("ISEVEN", ptgs[0].toFormulaString()); - assertEquals("A1", ptgs[1].toFormulaString()); - assertEquals("#external#", ptgs[2].toFormulaString()); - - // Formula referencing an area - ptgs = parse(fpb, "SUM(A1:B3)"); - assertEquals(2, ptgs.length); - assertEquals(AreaPtg.class, ptgs[0].getClass()); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals("A1:B3", ptgs[0].toFormulaString()); - assertEquals("SUM", ptgs[1].toFormulaString()); - - // Formula referencing one cell in a different sheet - ptgs = parse(fpb, "SUM(Sheet1!A1)"); - assertEquals(2, ptgs.length); - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals("Sheet1!A1", ptgs[0].toFormulaString()); - assertEquals("SUM", ptgs[1].toFormulaString()); - - // Formula referencing an area in a different sheet - ptgs = parse(fpb, "SUM(Sheet1!A1:B3)"); - assertEquals(2, ptgs.length); - assertEquals(Area3DPxg.class,ptgs[0].getClass()); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals("Sheet1!A1:B3", ptgs[0].toFormulaString()); - assertEquals("SUM", ptgs[1].toFormulaString()); - - wb.close(); - } - - @Test - void builtInFormulas() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - ptgs = parse(fpb, "LOG10"); - assertEquals(1, ptgs.length); - assertTrue(ptgs[0] instanceof RefPtg); - - ptgs = parse(fpb, "LOG10(100)"); - assertEquals(2, ptgs.length); - assertTrue(ptgs[0] instanceof IntPtg); - assertTrue(ptgs[1] instanceof FuncPtg); - - wb.close(); - } - - @Test - void formulaReferencesSameWorkbook() throws IOException { - // Use a test file with "other workbook" style references - // to itself - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx"); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // Reference to a named range in our own workbook, as if it - // were defined in a different workbook - ptgs = parse(fpb, "[0]!NR_Global_B2"); - assertEquals(1, ptgs.length); - assertEquals(NameXPxg.class, ptgs[0].getClass()); - assertEquals(0, ((NameXPxg)ptgs[0]).getExternalWorkbookNumber()); - assertNull(((NameXPxg) ptgs[0]).getSheetName()); - assertEquals("NR_Global_B2",((NameXPxg)ptgs[0]).getNameName()); - assertEquals("[0]!NR_Global_B2", ptgs[0].toFormulaString()); - - wb.close(); - } - - @Test - void formulaReferencesOtherSheets() throws IOException { - // Use a test file with the named ranges in place - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx"); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // Reference to a single cell in a different sheet - ptgs = parse(fpb, "Uses!A1"); - assertEquals(1, ptgs.length); - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - assertEquals(-1, ((Ref3DPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals("A1", ((Ref3DPxg)ptgs[0]).format2DRefAsString()); - assertEquals("Uses!A1", ptgs[0].toFormulaString()); - - // Reference to a single cell in a different sheet, which needs quoting - ptgs = parse(fpb, "'Testing 47100'!A1"); - assertEquals(1, ptgs.length); - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - assertEquals(-1, ((Ref3DPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals("Testing 47100", ((Ref3DPxg)ptgs[0]).getSheetName()); - assertEquals("A1", ((Ref3DPxg)ptgs[0]).format2DRefAsString()); - assertEquals("'Testing 47100'!A1", ptgs[0].toFormulaString()); - - // Reference to a sheet scoped named range from another sheet - ptgs = parse(fpb, "Defines!NR_To_A1"); - assertEquals(1, ptgs.length); - assertEquals(NameXPxg.class, ptgs[0].getClass()); - assertEquals(-1, ((NameXPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals("Defines", ((NameXPxg)ptgs[0]).getSheetName()); - assertEquals("NR_To_A1",((NameXPxg)ptgs[0]).getNameName()); - assertEquals("Defines!NR_To_A1", ptgs[0].toFormulaString()); - - // Reference to a workbook scoped named range - ptgs = parse(fpb, "NR_Global_B2"); - assertEquals(1, ptgs.length); - assertEquals(NamePtg.class, ptgs[0].getClass()); - assertEquals("NR_Global_B2",((NamePtg)ptgs[0]).toFormulaString(fpb)); - - wb.close(); - } - - @Test - void formulaReferencesOtherWorkbook() throws IOException { - // Use a test file with the external linked table in place - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("ref-56737.xlsx"); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // Reference to a single cell in a different workbook - ptgs = parse(fpb, "[1]Uses!$A$1"); - assertEquals(1, ptgs.length); - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - assertEquals(1, ((Ref3DPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals("Uses",((Ref3DPxg)ptgs[0]).getSheetName()); - assertEquals("$A$1",((Ref3DPxg)ptgs[0]).format2DRefAsString()); - assertEquals("[1]Uses!$A$1", ptgs[0].toFormulaString()); - - // Reference to a sheet-scoped named range in a different workbook - ptgs = parse(fpb, "[1]Defines!NR_To_A1"); - assertEquals(1, ptgs.length); - assertEquals(NameXPxg.class, ptgs[0].getClass()); - assertEquals(1, ((NameXPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals("Defines", ((NameXPxg)ptgs[0]).getSheetName()); - assertEquals("NR_To_A1",((NameXPxg)ptgs[0]).getNameName()); - assertEquals("[1]Defines!NR_To_A1", ptgs[0].toFormulaString()); - - // Reference to a global named range in a different workbook - ptgs = parse(fpb, "[1]!NR_Global_B2"); - assertEquals(1, ptgs.length); - assertEquals(NameXPxg.class, ptgs[0].getClass()); - assertEquals(1, ((NameXPxg)ptgs[0]).getExternalWorkbookNumber()); - assertNull(((NameXPxg) ptgs[0]).getSheetName()); - assertEquals("NR_Global_B2",((NameXPxg)ptgs[0]).getNameName()); - assertEquals("[1]!NR_Global_B2", ptgs[0].toFormulaString()); - - wb.close(); - } - - /** - * A handful of functions (such as SUM, COUNTA, MIN) support - * multi-sheet references (eg Sheet1:Sheet3!A1 = Cell A1 from - * Sheets 1 through Sheet 3) and multi-sheet area references - * (eg Sheet1:Sheet3!A1:B2 = Cells A1 through B2 from Sheets - * 1 through Sheet 3). - * This test, based on common test files for HSSF and XSSF, checks - * that we can read and parse these kinds of references - * (but not evaluate - that's elsewhere in the test suite) - */ - @Test - void multiSheetReferencesHSSFandXSSF() throws IOException { - Workbook[] wbs = new Workbook[] { - HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls"), - XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx") - }; - for (Workbook wb : wbs) { - Sheet s1 = wb.getSheetAt(0); - Ptg[] ptgs; - - // Check the contents - Cell sumF = s1.getRow(2).getCell(0); - assertNotNull(sumF); - assertEquals("SUM(Sheet1:Sheet3!A1)", sumF.getCellFormula()); - - Cell avgF = s1.getRow(2).getCell(1); - assertNotNull(avgF); - assertEquals("AVERAGE(Sheet1:Sheet3!A1)", avgF.getCellFormula()); - - Cell countAF = s1.getRow(2).getCell(2); - assertNotNull(countAF); - assertEquals("COUNTA(Sheet1:Sheet3!C1)", countAF.getCellFormula()); - - Cell maxF = s1.getRow(4).getCell(1); - assertNotNull(maxF); - assertEquals("MAX(Sheet1:Sheet3!A$1)", maxF.getCellFormula()); - - - Cell sumFA = s1.getRow(2).getCell(7); - assertNotNull(sumFA); - assertEquals("SUM(Sheet1:Sheet3!A1:B2)", sumFA.getCellFormula()); - - Cell avgFA = s1.getRow(2).getCell(8); - assertNotNull(avgFA); - assertEquals("AVERAGE(Sheet1:Sheet3!A1:B2)", avgFA.getCellFormula()); - - Cell maxFA = s1.getRow(4).getCell(8); - assertNotNull(maxFA); - assertEquals("MAX(Sheet1:Sheet3!A$1:B$2)", maxFA.getCellFormula()); - - Cell countFA = s1.getRow(5).getCell(8); - assertNotNull(countFA); - assertEquals("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.getCellFormula()); - - - // Create a formula parser - final FormulaParsingWorkbook fpb; - if (wb instanceof HSSFWorkbook) - fpb = HSSFEvaluationWorkbook.create((HSSFWorkbook)wb); - else - fpb = XSSFEvaluationWorkbook.create((XSSFWorkbook)wb); - - // Check things parse as expected: - - // SUM to one cell over 3 workbooks, relative reference - ptgs = parse(fpb, "SUM(Sheet1:Sheet3!A1)"); - assertEquals(2, ptgs.length); - if (wb instanceof HSSFWorkbook) { - assertEquals(Ref3DPtg.class, ptgs[0].getClass()); - } else { - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - } - assertEquals("Sheet1:Sheet3!A1", toFormulaString(ptgs[0], fpb)); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals("SUM", toFormulaString(ptgs[1], fpb)); - - // MAX to one cell over 3 workbooks, absolute row reference - ptgs = parse(fpb, "MAX(Sheet1:Sheet3!A$1)"); - assertEquals(2, ptgs.length); - if (wb instanceof HSSFWorkbook) { - assertEquals(Ref3DPtg.class, ptgs[0].getClass()); - } else { - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - } - assertEquals("Sheet1:Sheet3!A$1", toFormulaString(ptgs[0], fpb)); - assertEquals(FuncVarPtg.class, ptgs[1].getClass()); - assertEquals("MAX", toFormulaString(ptgs[1], fpb)); - - // MIN to one cell over 3 workbooks, absolute reference - ptgs = parse(fpb, "MIN(Sheet1:Sheet3!$A$1)"); - assertEquals(2, ptgs.length); - if (wb instanceof HSSFWorkbook) { - assertEquals(Ref3DPtg.class, ptgs[0].getClass()); - } else { - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - } - assertEquals("Sheet1:Sheet3!$A$1", toFormulaString(ptgs[0], fpb)); - assertEquals(FuncVarPtg.class, ptgs[1].getClass()); - assertEquals("MIN", toFormulaString(ptgs[1], fpb)); - - // SUM to a range of cells over 3 workbooks - ptgs = parse(fpb, "SUM(Sheet1:Sheet3!A1:B2)"); - assertEquals(2, ptgs.length); - if (wb instanceof HSSFWorkbook) { - assertEquals(Area3DPtg.class, ptgs[0].getClass()); - } else { - assertEquals(Area3DPxg.class, ptgs[0].getClass()); - } - assertEquals("Sheet1:Sheet3!A1:B2", toFormulaString(ptgs[0], fpb)); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals("SUM", toFormulaString(ptgs[1], fpb)); - - // MIN to a range of cells over 3 workbooks, absolute reference - ptgs = parse(fpb, "MIN(Sheet1:Sheet3!$A$1:$B$2)"); - assertEquals(2, ptgs.length); - if (wb instanceof HSSFWorkbook) { - assertEquals(Area3DPtg.class, ptgs[0].getClass()); - } else { - assertEquals(Area3DPxg.class, ptgs[0].getClass()); - } - assertEquals("Sheet1:Sheet3!$A$1:$B$2", toFormulaString(ptgs[0], fpb)); - assertEquals(FuncVarPtg.class, ptgs[1].getClass()); - assertEquals("MIN", toFormulaString(ptgs[1], fpb)); - - // Check we can round-trip - try to set a new one to a new single cell - Cell newF = s1.getRow(0).createCell(10, CellType.FORMULA); - newF.setCellFormula("SUM(Sheet2:Sheet3!A1)"); - assertEquals("SUM(Sheet2:Sheet3!A1)", newF.getCellFormula()); - - // Check we can round-trip - try to set a new one to a cell range - newF = s1.getRow(0).createCell(11, CellType.FORMULA); - newF.setCellFormula("MIN(Sheet1:Sheet2!A1:B2)"); - assertEquals("MIN(Sheet1:Sheet2!A1:B2)", newF.getCellFormula()); - - wb.close(); - } - } - - private static String toFormulaString(Ptg ptg, FormulaParsingWorkbook wb) { - if (ptg instanceof WorkbookDependentFormula) { - return ((WorkbookDependentFormula)ptg).toFormulaString((FormulaRenderingWorkbook)wb); - } - return ptg.toFormulaString(); - } - - @Test - void test58648Single() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - ptgs = parse(fpb, "(ABC10 )"); - assertEquals(2, ptgs.length, "Had: " + Arrays.toString(ptgs)); - assertTrue(ptgs[0] instanceof RefPtg, "Had " + Arrays.toString(ptgs)); - assertTrue(ptgs[1] instanceof ParenthesisPtg, "Had " + Arrays.toString(ptgs)); - } - } - - @Test - void test58648Basic() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // verify whitespaces in different places - ptgs = parse(fpb, "(ABC10)"); - assertEquals(2, ptgs.length); - assertTrue(ptgs[0] instanceof RefPtg); - assertTrue(ptgs[1] instanceof ParenthesisPtg); - - ptgs = parse(fpb, "( ABC10)"); - assertEquals(2, ptgs.length); - assertTrue(ptgs[0] instanceof RefPtg); - assertTrue(ptgs[1] instanceof ParenthesisPtg); - - ptgs = parse(fpb, "(ABC10 )"); - assertEquals(2, ptgs.length); - assertTrue(ptgs[0] instanceof RefPtg); - assertTrue(ptgs[1] instanceof ParenthesisPtg); - - ptgs = parse(fpb, "((ABC10))"); - assertEquals(3, ptgs.length); - assertTrue(ptgs[0] instanceof RefPtg); - assertTrue(ptgs[1] instanceof ParenthesisPtg); - assertTrue(ptgs[2] instanceof ParenthesisPtg); - - ptgs = parse(fpb, "((ABC10) )"); - assertEquals(3, ptgs.length); - assertTrue(ptgs[0] instanceof RefPtg); - assertTrue(ptgs[1] instanceof ParenthesisPtg); - assertTrue(ptgs[2] instanceof ParenthesisPtg); - - ptgs = parse(fpb, "( (ABC10))"); - assertEquals(3, ptgs.length); - assertTrue(ptgs[0] instanceof RefPtg); - assertTrue(ptgs[1] instanceof ParenthesisPtg); - assertTrue(ptgs[2] instanceof ParenthesisPtg); - - wb.close(); - } - - @Test - void test58648FormulaParsing() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58648.xlsx"); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - for (int i = 0; i < wb.getNumberOfSheets(); i++) { - Sheet xsheet = wb.getSheetAt(i); - - for (Row row : xsheet) { - for (Cell cell : row) { - if (cell.getCellType() == CellType.FORMULA) { - try { - evaluator.evaluateFormulaCell(cell); - } catch (Exception e) { - CellReference cellRef = new CellReference(cell.getRowIndex(), cell.getColumnIndex()); - throw new RuntimeException("error at: " + cellRef, e); - } - } - } - } - } - - Sheet sheet = wb.getSheet("my-sheet"); - Cell cell = sheet.getRow(1).getCell(4); - - assertEquals(5d, cell.getNumericCellValue(), 0d); - - wb.close(); - } - - @Test - void testWhitespaceInFormula() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // verify whitespaces in different places - ptgs = parse(fpb, "INTERCEPT(A2:A5, B2:B5)"); - assertEquals(3, ptgs.length); - assertTrue(ptgs[0] instanceof AreaPtg); - assertTrue(ptgs[1] instanceof AreaPtg); - assertTrue(ptgs[2] instanceof FuncPtg); - - ptgs = parse(fpb, " INTERCEPT ( \t \r A2 : \nA5 , B2 : B5 ) \t"); - assertEquals(3, ptgs.length); - assertTrue(ptgs[0] instanceof AreaPtg); - assertTrue(ptgs[1] instanceof AreaPtg); - assertTrue(ptgs[2] instanceof FuncPtg); - - ptgs = parse(fpb, "(VLOOKUP(\"item1\", A2:B3, 2, FALSE) - VLOOKUP(\"item2\", A2:B3, 2, FALSE) )"); - assertEquals(12, ptgs.length); - assertTrue(ptgs[0] instanceof StringPtg); - assertTrue(ptgs[1] instanceof AreaPtg); - assertTrue(ptgs[2] instanceof IntPtg); - - ptgs = parse(fpb, "A1:B1 B1:B2"); - assertEquals(4, ptgs.length); - assertTrue(ptgs[0] instanceof MemAreaPtg); - assertTrue(ptgs[1] instanceof AreaPtg); - assertTrue(ptgs[2] instanceof AreaPtg); - assertTrue(ptgs[3] instanceof IntersectionPtg); - - ptgs = parse(fpb, "A1:B1 B1:B2"); - assertEquals(4, ptgs.length); - assertTrue(ptgs[0] instanceof MemAreaPtg); - assertTrue(ptgs[1] instanceof AreaPtg); - assertTrue(ptgs[2] instanceof AreaPtg); - assertTrue(ptgs[3] instanceof IntersectionPtg); - - wb.close(); - } - - @Test - void testWhitespaceInComplexFormula() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // verify whitespaces in different places - ptgs = parse(fpb, "SUM(A1:INDEX(1:1048576,MAX(IFERROR(MATCH(99^99,B:B,1),0),IFERROR(MATCH(\"zzzz\",B:B,1),0)),MAX(IFERROR(MATCH(99^99,1:1,1),0),IFERROR(MATCH(\"zzzz\",1:1,1),0))))"); - assertEquals(40, ptgs.length); - assertTrue(ptgs[0] instanceof MemFuncPtg); - assertTrue(ptgs[1] instanceof RefPtg); - assertTrue(ptgs[2] instanceof AreaPtg); - assertTrue(ptgs[3] instanceof NameXPxg); - - ptgs = parse(fpb, "SUM ( A1 : INDEX( 1 : 1048576 , MAX( IFERROR ( MATCH ( 99 ^ 99 , B : B , 1 ) , 0 ) , IFERROR ( MATCH ( \"zzzz\" , B:B , 1 ) , 0 ) ) , MAX ( IFERROR ( MATCH ( 99 ^ 99 , 1 : 1 , 1 ) , 0 ) , IFERROR ( MATCH ( \"zzzz\" , 1 : 1 , 1 ) , 0 ) ) ) )"); - assertEquals(40, ptgs.length); - assertTrue(ptgs[0] instanceof MemFuncPtg); - assertTrue(ptgs[1] instanceof RefPtg); - assertTrue(ptgs[2] instanceof AreaPtg); - assertTrue(ptgs[3] instanceof NameXPxg); - - wb.close(); - } - - @Test - void parseStructuredReferences() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - /* - The following cases are tested (copied from FormulaParser.parseStructuredReference) - 1 Table1[col] - 2 Table1[[#Totals],[col]] - 3 Table1[#Totals] - 4 Table1[#All] - 5 Table1[#Data] - 6 Table1[#Headers] - 7 Table1[#Totals] - 8 Table1[#This Row] - 9 Table1[[#All],[col]] - 10 Table1[[#Headers],[col]] - 11 Table1[[#Totals],[col]] - 12 Table1[[#All],[col1]:[col2]] - 13 Table1[[#Data],[col1]:[col2]] - 14 Table1[[#Headers],[col1]:[col2]] - 15 Table1[[#Totals],[col1]:[col2]] - 16 Table1[[#Headers],[#Data],[col2]] - 17 Table1[[#This Row], [col1]] - 18 Table1[ [col1]:[col2] ] - */ - - final String tbl = "\\_Prime.1"; - final String noTotalsRowReason = ": Tables without a Totals row should return #REF! on [#Totals]"; - - ////// Case 1: Evaluate Table1[col] with apostrophe-escaped #-signs //////// - ptgs = parse(fpb, "SUM("+tbl+"[calc='#*'#])"); - assertEquals(2, ptgs.length); - - // Area3DPxg [sheet=Table ! A2:A7] - assertTrue(ptgs[0] instanceof Area3DPxg); - Area3DPxg ptg0 = (Area3DPxg) ptgs[0]; - assertEquals("Table", ptg0.getSheetName()); - assertEquals("A2:A7", ptg0.format2DRefAsString()); - // Note: structured references are evaluated and resolved to regular 3D area references. - assertEquals("Table!A2:A7", ptg0.toFormulaString()); - - // AttrPtg [sum ] - assertTrue(ptgs[1] instanceof AttrPtg); - AttrPtg ptg1 = (AttrPtg) ptgs[1]; - assertTrue(ptg1.isSum()); - - ////// Case 1: Evaluate "Table1[col]" //////// - ptgs = parse(fpb, tbl+"[Name]"); - assertEquals(1, ptgs.length); - assertEquals("Table!B2:B7", ptgs[0].toFormulaString(), "Table1[col]"); - - ////// Case 2: Evaluate "Table1[[#Totals],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#Totals],[col]]"); - assertEquals(1, ptgs.length); - assertEquals(ErrPtg.REF_INVALID, ptgs[0], "Table1[[#Totals],[col]]" + noTotalsRowReason); - - ////// Case 3: Evaluate "Table1[#Totals]" //////// - ptgs = parse(fpb, tbl+"[#Totals]"); - assertEquals(1, ptgs.length); - assertEquals(ErrPtg.REF_INVALID, ptgs[0], "Table1[#Totals]" + noTotalsRowReason); - - ////// Case 4: Evaluate "Table1[#All]" //////// - ptgs = parse(fpb, tbl+"[#All]"); - assertEquals(1, ptgs.length); - assertEquals("Table!A1:C7", ptgs[0].toFormulaString(), "Table1[#All]"); - - ////// Case 5: Evaluate "Table1[#Data]" (excludes Header and Data rows) //////// - ptgs = parse(fpb, tbl+"[#Data]"); - assertEquals(1, ptgs.length); - assertEquals("Table!A2:C7", ptgs[0].toFormulaString(), "Table1[#Data]"); - - ////// Case 6: Evaluate "Table1[#Headers]" //////// - ptgs = parse(fpb, tbl+"[#Headers]"); - assertEquals(1, ptgs.length); - assertEquals("Table!A1:C1", ptgs[0].toFormulaString(), "Table1[#Headers]"); - - ////// Case 7: Evaluate "Table1[#Totals]" //////// - ptgs = parse(fpb, tbl+"[#Totals]"); - assertEquals(1, ptgs.length); - assertEquals(ErrPtg.REF_INVALID, ptgs[0], "Table1[#Totals]" + noTotalsRowReason); - - ////// Case 8: Evaluate "Table1[#This Row]" //////// - ptgs = parse(fpb, tbl+"[#This Row]", 2); - assertEquals(1, ptgs.length); - assertEquals("Table!A3:C3", ptgs[0].toFormulaString(), "Table1[#This Row]"); - - ////// Evaluate "Table1[@]" (equivalent to "Table1[#This Row]") //////// - ptgs = parse(fpb, tbl+"[@]", 2); - assertEquals(1, ptgs.length); - assertEquals("Table!A3:C3", ptgs[0].toFormulaString()); - - ////// Evaluate "Table1[#This Row]" when rowIndex is outside Table //////// - ptgs = parse(fpb, tbl+"[#This Row]", 10); - assertEquals(1, ptgs.length); - assertEquals(ErrPtg.VALUE_INVALID, ptgs[0], "Table1[#This Row]"); - - ////// Evaluate "Table1[@]" when rowIndex is outside Table //////// - ptgs = parse(fpb, tbl+"[@]", 10); - assertEquals(1, ptgs.length); - assertEquals(ErrPtg.VALUE_INVALID, ptgs[0], "Table1[@]"); - - ////// Evaluate "Table1[[#Data],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#Data], [Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table!C2:C7", ptgs[0].toFormulaString(), "Table1[[#Data],[col]]"); - - - ////// Case 9: Evaluate "Table1[[#All],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#All], [Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table!C1:C7", ptgs[0].toFormulaString(), "Table1[[#All],[col]]"); - - ////// Case 10: Evaluate "Table1[[#Headers],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#Headers], [Number]]"); - assertEquals(1, ptgs.length); - // also acceptable: Table1!B1 - assertEquals("Table!C1:C1", ptgs[0].toFormulaString(), "Table1[[#Headers],[col]]"); - - ////// Case 11: Evaluate "Table1[[#Totals],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#Totals],[Name]]"); - assertEquals(1, ptgs.length); - assertEquals(ErrPtg.REF_INVALID, ptgs[0], "Table1[[#Totals],[col]]" + noTotalsRowReason); - - ////// Case 12: Evaluate "Table1[[#All],[col1]:[col2]]" //////// - ptgs = parse(fpb, tbl+"[[#All], [Name]:[Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table!B1:C7", ptgs[0].toFormulaString(), "Table1[[#All],[col1]:[col2]]"); - - ////// Case 13: Evaluate "Table1[[#Data],[col]:[col2]]" //////// - ptgs = parse(fpb, tbl+"[[#Data], [Name]:[Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table!B2:C7", ptgs[0].toFormulaString(), "Table1[[#Data],[col]:[col2]]"); - - ////// Case 14: Evaluate "Table1[[#Headers],[col1]:[col2]]" //////// - ptgs = parse(fpb, tbl+"[[#Headers], [Name]:[Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table!B1:C1", ptgs[0].toFormulaString(), "Table1[[#Headers],[col1]:[col2]]"); - - ////// Case 15: Evaluate "Table1[[#Totals],[col]:[col2]]" //////// - ptgs = parse(fpb, tbl+"[[#Totals], [Name]:[Number]]"); - assertEquals(1, ptgs.length); - assertEquals(ErrPtg.REF_INVALID, ptgs[0], "Table1[[#Totals],[col]:[col2]]" + noTotalsRowReason); - - ////// Case 16: Evaluate "Table1[[#Headers],[#Data],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#Headers],[#Data],[Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table!C1:C7", ptgs[0].toFormulaString(), "Table1[[#Headers],[#Data],[col]]"); - - ////// Case 17: Evaluate "Table1[[#This Row], [col1]]" //////// - ptgs = parse(fpb, tbl+"[[#This Row], [Number]]", 2); - assertEquals(1, ptgs.length); - // also acceptable: Table!C3 - assertEquals("Table!C3:C3", ptgs[0].toFormulaString(), "Table1[[#This Row], [col1]]"); - - ////// Case 18: Evaluate "Table1[[col]:[col2]]" //////// - ptgs = parse(fpb, tbl+"[[Name]:[Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table!B2:C7", ptgs[0].toFormulaString(), "Table1[[col]:[col2]]"); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHeaderFooterProperties.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHeaderFooterProperties.java deleted file mode 100644 index 654bf75b31..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHeaderFooterProperties.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestXSSFHeaderFooterProperties { - - private XSSFWorkbook wb; - private XSSFSheet sheet; - private XSSFHeaderFooterProperties hfProp; - - @BeforeEach - void before() { - wb = new XSSFWorkbook(); - sheet = wb.createSheet(); - hfProp = sheet.getHeaderFooterProperties(); - } - - @AfterEach - void after() throws Exception { - wb.close(); - } - - @Test - void testGetAlignWithMargins() { - assertFalse(hfProp.getAlignWithMargins()); - hfProp.setAlignWithMargins(true); - assertTrue(hfProp.getAlignWithMargins()); - } - - @Test - void testGetDifferentFirst() { - assertFalse(hfProp.getDifferentFirst()); - hfProp.setDifferentFirst(true); - assertTrue(hfProp.getDifferentFirst()); - hfProp.setDifferentFirst(false); - assertFalse(hfProp.getDifferentFirst()); - } - - @Test - void testGetDifferentOddEven() { - assertFalse(hfProp.getDifferentOddEven()); - hfProp.setDifferentOddEven(true); - assertTrue(hfProp.getDifferentOddEven()); - hfProp.setDifferentOddEven(false); - assertFalse(hfProp.getDifferentOddEven()); - } - - @Test - void testGetScaleWithDoc() { - assertFalse(hfProp.getScaleWithDoc()); - hfProp.setScaleWithDoc(true); - assertTrue(hfProp.getScaleWithDoc()); - } - - @Test - void testRemoveAlignWithMargins() { - hfProp.setAlignWithMargins(true); - assertTrue(hfProp.getHeaderFooter().isSetAlignWithMargins()); - hfProp.removeAlignWithMargins(); - assertFalse(hfProp.getHeaderFooter().isSetAlignWithMargins()); - } - - @Test - void testRemoveDifferentFirst() { - hfProp.setDifferentFirst(true); - assertTrue(hfProp.getHeaderFooter().isSetDifferentFirst()); - hfProp.removeDifferentFirst(); - assertFalse(hfProp.getHeaderFooter().isSetDifferentFirst()); - } - - @Test - void testRemoveDifferentOddEven() { - hfProp.setDifferentOddEven(true); - assertTrue(hfProp.getHeaderFooter().isSetDifferentOddEven()); - hfProp.removeDifferentOddEven(); - assertFalse(hfProp.getHeaderFooter().isSetDifferentOddEven()); - } - - @Test - void testRemoveScaleWithDoc() { - hfProp.setScaleWithDoc(true); - assertTrue(hfProp.getHeaderFooter().isSetScaleWithDoc()); - hfProp.removeScaleWithDoc(); - assertFalse(hfProp.getHeaderFooter().isSetScaleWithDoc()); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java deleted file mode 100644 index 203fbba80c..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java +++ /dev/null @@ -1,375 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.usermodel.HSSFHyperlink; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.*; - -public final class TestXSSFHyperlink extends BaseTestHyperlink { - public TestXSSFHyperlink() { - super(XSSFITestDataProvider.instance); - } - - @Test - void testLoadExisting() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx")) { - assertEquals(3, workbook.getNumberOfSheets()); - - XSSFSheet sheet = workbook.getSheetAt(0); - - // Check the hyperlinks - assertEquals(4, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); - } - } - - @Test - void testCreate() throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - XSSFRow row = sheet.createRow(0); - XSSFCreationHelper createHelper = workbook.getCreationHelper(); - - String[] urls = { - "http://apache.org", - "www.apache.org", - "/temp", - "c:/temp", - "http://apache.org/default.php?s=isTramsformed&submit=Search&la=*&li=*"}; - for(int i = 0; i < urls.length; i++){ - String s = urls[i]; - XSSFHyperlink link = createHelper.createHyperlink(HyperlinkType.URL); - link.setAddress(s); - - XSSFCell cell = row.createCell(i); - cell.setHyperlink(link); - } - workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook); - sheet = workbook.getSheetAt(0); - PackageRelationshipCollection rels = sheet.getPackagePart().getRelationships(); - assertEquals(urls.length, rels.size()); - for(int i = 0; i < rels.size(); i++){ - PackageRelationship rel = rels.getRelationship(i); - // there should be a relationship for each URL - assertNotNull(rel); - assertEquals(urls[i], rel.getTargetURI().toString()); - } - - // Bugzilla 53041: Hyperlink relations are duplicated when saving XSSF file - workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook); - sheet = workbook.getSheetAt(0); - rels = sheet.getPackagePart().getRelationships(); - assertEquals(urls.length, rels.size()); - for(int i = 0; i < rels.size(); i++){ - PackageRelationship rel = rels.getRelationship(i); - // there should be a relationship for each URL - assertNotNull(rel); - assertEquals(urls[i], rel.getTargetURI().toString()); - } - } - - @Test - void testInvalidURLs() throws IOException { - try (XSSFWorkbook workbook = new XSSFWorkbook()) { - XSSFCreationHelper createHelper = workbook.getCreationHelper(); - - String[] invalidURLs = { - "http:\\apache.org", - "www.apache .org", - "c:\\temp", - "\\poi"}; - for (String s : invalidURLs) { - assertThrows(IllegalArgumentException.class, - () -> createHelper.createHyperlink(HyperlinkType.URL).setAddress(s)); - } - } - } - - @Test - void testLoadSave() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx")) { - CreationHelper createHelper = workbook.getCreationHelper(); - assertEquals(3, workbook.getNumberOfSheets()); - XSSFSheet sheet = workbook.getSheetAt(0); - - // Check hyperlinks - assertEquals(4, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); - - - // Write out, and check - - // Load up again, check all links still there - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertEquals(3, wb2.getNumberOfSheets()); - assertNotNull(wb2.getSheetAt(0)); - assertNotNull(wb2.getSheetAt(1)); - assertNotNull(wb2.getSheetAt(2)); - - sheet = wb2.getSheetAt(0); - - - // Check hyperlinks again - assertEquals(4, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); - - - // Add one more, and re-check - Row r17 = sheet.createRow(17); - Cell r17c = r17.createCell(2); - - Hyperlink hyperlink = createHelper.createHyperlink(HyperlinkType.URL); - hyperlink.setAddress("http://poi.apache.org/spreadsheet/"); - hyperlink.setLabel("POI SS Link"); - r17c.setHyperlink(hyperlink); - - assertEquals(5, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); - - assertEquals(HyperlinkType.URL, - sheet.getRow(17).getCell(2).getHyperlink().getType()); - assertEquals("POI SS Link", - sheet.getRow(17).getCell(2).getHyperlink().getLabel()); - assertEquals("http://poi.apache.org/spreadsheet/", - sheet.getRow(17).getCell(2).getHyperlink().getAddress()); - - - // Save and re-load once more - - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - assertEquals(3, wb3.getNumberOfSheets()); - assertNotNull(wb3.getSheetAt(0)); - assertNotNull(wb3.getSheetAt(1)); - assertNotNull(wb3.getSheetAt(2)); - - sheet = wb3.getSheetAt(0); - - assertEquals(5, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); - - assertEquals(HyperlinkType.URL, - sheet.getRow(17).getCell(2).getHyperlink().getType()); - assertEquals("POI SS Link", - sheet.getRow(17).getCell(2).getHyperlink().getLabel()); - assertEquals("http://poi.apache.org/spreadsheet/", - sheet.getRow(17).getCell(2).getHyperlink().getAddress()); - } - } - - /** - * Only for WithMoreVariousData.xlsx ! - */ - private static void doTestHyperlinkContents(XSSFSheet sheet) { - assertNotNull(sheet.getRow(3).getCell(2).getHyperlink()); - assertNotNull(sheet.getRow(14).getCell(2).getHyperlink()); - assertNotNull(sheet.getRow(15).getCell(2).getHyperlink()); - assertNotNull(sheet.getRow(16).getCell(2).getHyperlink()); - - // First is a link to poi - assertEquals(HyperlinkType.URL, - sheet.getRow(3).getCell(2).getHyperlink().getType()); - assertNull(sheet.getRow(3).getCell(2).getHyperlink().getLabel()); - assertEquals("http://poi.apache.org/", - sheet.getRow(3).getCell(2).getHyperlink().getAddress()); - - // Next is an internal doc link - assertEquals(HyperlinkType.DOCUMENT, - sheet.getRow(14).getCell(2).getHyperlink().getType()); - assertEquals("Internal hyperlink to A2", - sheet.getRow(14).getCell(2).getHyperlink().getLabel()); - assertEquals("Sheet1!A2", - sheet.getRow(14).getCell(2).getHyperlink().getAddress()); - - // Next is a file - assertEquals(HyperlinkType.FILE, - sheet.getRow(15).getCell(2).getHyperlink().getType()); - assertNull(sheet.getRow(15).getCell(2).getHyperlink().getLabel()); - assertEquals("WithVariousData.xlsx", - sheet.getRow(15).getCell(2).getHyperlink().getAddress()); - - // Last is a mailto - assertEquals(HyperlinkType.EMAIL, - sheet.getRow(16).getCell(2).getHyperlink().getType()); - assertNull(sheet.getRow(16).getCell(2).getHyperlink().getLabel()); - assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", - sheet.getRow(16).getCell(2).getHyperlink().getAddress()); - } - - @Test - void test52716() throws IOException { - try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("52716.xlsx")) { - XSSFSheet sh1 = wb1.getSheetAt(0); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - XSSFSheet sh2 = wb2.getSheetAt(0); - - assertEquals(sh1.getNumberOfComments(), sh2.getNumberOfComments()); - XSSFHyperlink l1 = sh1.getHyperlink(0, 1); - assertEquals(HyperlinkType.DOCUMENT, l1.getType()); - assertEquals("B1", l1.getCellRef()); - assertEquals("Sort on Titel", l1.getTooltip()); - - XSSFHyperlink l2 = sh2.getHyperlink(0, 1); - assertEquals(l1.getTooltip(), l2.getTooltip()); - assertEquals(HyperlinkType.DOCUMENT, l2.getType()); - assertEquals("B1", l2.getCellRef()); - } - } - - @Test - void test53734() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53734.xlsx")) { - Hyperlink link = wb.getSheetAt(0).getRow(0).getCell(0).getHyperlink(); - assertEquals("javascript:///", link.getAddress()); - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) { - link = wb2.getSheetAt(0).getRow(0).getCell(0).getHyperlink(); - assertEquals("javascript:///", link.getAddress()); - } - } - } - - @Test - void test53282() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53282.xlsx")) { - Hyperlink link = wb.getSheetAt(0).getRow(0).getCell(14).getHyperlink(); - assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress()); - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) { - link = wb2.getSheetAt(0).getRow(0).getCell(14).getHyperlink(); - assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress()); - } - } - } - - @Override - public XSSFHyperlink copyHyperlink(Hyperlink link) { - return new XSSFHyperlink(link); - } - - @Test - void testCopyHSSFHyperlink() throws IOException { - HSSFWorkbook hssfworkbook = new HSSFWorkbook(); - HSSFHyperlink hlink = hssfworkbook.getCreationHelper().createHyperlink(HyperlinkType.URL); - hlink.setAddress("http://poi.apache.org/"); - hlink.setFirstColumn(3); - hlink.setFirstRow(2); - hlink.setLastColumn(5); - hlink.setLastRow(6); - hlink.setLabel("label"); - XSSFHyperlink xlink = new XSSFHyperlink(hlink); - - assertEquals("http://poi.apache.org/", xlink.getAddress()); - assertEquals(new CellReference(2, 3), new CellReference(xlink.getCellRef())); - // Are HSSFHyperlink.label and XSSFHyperlink.tooltip the same? If so, perhaps one of these needs renamed for a consistent Hyperlink interface - // assertEquals("label", xlink.getTooltip()); - - hssfworkbook.close(); - } - - /* bug 59775: XSSFHyperlink has wrong type if it contains a location (CTHyperlink#getLocation) - * URLs with a hash mark (#) are still URL hyperlinks, not document links - */ - @Test - void testURLsWithHashMark() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("59775.xlsx"); - XSSFSheet sh = wb.getSheetAt(0); - CellAddress A2 = new CellAddress("A2"); - CellAddress A3 = new CellAddress("A3"); - CellAddress A4 = new CellAddress("A4"); - CellAddress A7 = new CellAddress("A7"); - - XSSFHyperlink link = sh.getHyperlink(A2); - assertEquals("A2", link.getCellRef(), "address"); - assertEquals(HyperlinkType.URL, link.getType(), "link type"); - assertEquals("http://twitter.com/#!/apacheorg", link.getAddress(), "link target"); - - link = sh.getHyperlink(A3); - assertEquals("A3", link.getCellRef(), "address"); - assertEquals(HyperlinkType.URL, link.getType(), "link type"); - assertEquals("http://www.bailii.org/databases.html#ie", link.getAddress(), "link target"); - - link = sh.getHyperlink(A4); - assertEquals("A4", link.getCellRef(), "address"); - assertEquals(HyperlinkType.URL, link.getType(), "link type"); - assertEquals("https://en.wikipedia.org/wiki/Apache_POI#See_also", link.getAddress(), "link target"); - - link = sh.getHyperlink(A7); - assertEquals("A7", link.getCellRef(), "address"); - assertEquals(HyperlinkType.DOCUMENT, link.getType(), "link type"); - assertEquals("Sheet1", link.getAddress(), "link target"); - - wb.close(); - } - - @Test - void test() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - - CreationHelper createHelper = wb.getCreationHelper(); - XSSFCellStyle hlinkStyle = wb.createCellStyle(); - Font hlinkFont = wb.createFont(); - - Sheet sheet = wb.createSheet("test"); - - Row rowDet = sheet.createRow(0); - - Cell cellDet = rowDet.createCell(7); - cellDet.setCellValue("http://www.google.at"); - //set up style to be able to create hyperlinks - hlinkFont.setColor(IndexedColors.BLUE.getIndex()); - hlinkStyle.setFont(hlinkFont); - Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL); - link.setAddress("http://www.example.com"); - cellDet.setHyperlink(link); - cellDet.setCellStyle(hlinkStyle); - - //set up style to be able to create hyperlinks - hlinkFont.setColor(IndexedColors.BLUE.getIndex()); - hlinkStyle.setFont(hlinkFont); - link = createHelper.createHyperlink(HyperlinkType.URL); - - //string for hyperlink - cellDet = rowDet.createCell(13); - cellDet.setCellValue("http://www.other.com"); - link.setAddress("http://www.gmx.at"); - cellDet.setHyperlink(link); - cellDet.setCellStyle(hlinkStyle); - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - - assertNotNull(wbBack.getSheetAt(0).getRow(0).getCell(7).getHyperlink()); - assertNotNull(wbBack.getSheetAt(0).getRow(0).getCell(13).getHyperlink()); - - wb.close(); - wbBack.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFName.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFName.java deleted file mode 100644 index 0792ddc655..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFName.java +++ /dev/null @@ -1,153 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.ss.usermodel.BaseTestNamedRange; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -public final class TestXSSFName extends BaseTestNamedRange { - - public TestXSSFName() { - super(XSSFITestDataProvider.instance); - } - - //TODO combine testRepeatingRowsAndColums() for HSSF and XSSF - @Test - void testRepeatingRowsAndColums() throws Exception { - // First test that setting RR&C for same sheet more than once only creates a - // single Print_Titles built-in record - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet1 = wb.createSheet("First Sheet"); - - sheet1.setRepeatingRows(null); - sheet1.setRepeatingColumns(null); - - // set repeating rows and columns twice for the first sheet - for (int i = 0; i < 2; i++) { - sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:A")); - //sheet.createFreezePane(0, 3); - } - assertEquals(1, wb.getNumberOfNames()); - XSSFName nr1 = wb.getName(XSSFName.BUILTIN_PRINT_TITLE); - - assertEquals("'First Sheet'!$A:$A,'First Sheet'!$1:$4", nr1.getRefersToFormula()); - - //remove the columns part - sheet1.setRepeatingColumns(null); - assertEquals("'First Sheet'!$1:$4", nr1.getRefersToFormula()); - - //revert - sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:A")); - - //remove the rows part - sheet1.setRepeatingRows(null); - assertEquals("'First Sheet'!$A:$A", nr1.getRefersToFormula()); - - //revert - sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - - // Save and re-open - XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - - assertEquals(1, nwb.getNumberOfNames()); - nr1 = nwb.getName(XSSFName.BUILTIN_PRINT_TITLE); - - assertEquals("'First Sheet'!$A:$A,'First Sheet'!$1:$4", nr1.getRefersToFormula()); - - // check that setting RR&C on a second sheet causes a new Print_Titles built-in - // name to be created - XSSFSheet sheet2 = nwb.createSheet("SecondSheet"); - sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:1")); - sheet2.setRepeatingColumns(CellRangeAddress.valueOf("B:C")); - - assertEquals(2, nwb.getNumberOfNames()); - XSSFName nr2 = nwb.getNames(XSSFName.BUILTIN_PRINT_TITLE).get(1); - - assertEquals(XSSFName.BUILTIN_PRINT_TITLE, nr2.getNameName()); - assertEquals("SecondSheet!$B:$C,SecondSheet!$1:$1", nr2.getRefersToFormula()); - - sheet2.setRepeatingRows(null); - sheet2.setRepeatingColumns(null); - nwb.close(); - } - - @Test - void testSetNameName() throws Exception { - // Test that renaming named ranges doesn't break our new named range map - XSSFWorkbook wb = new XSSFWorkbook(); - wb.createSheet("First Sheet"); - - // Two named ranges called "name1", one scoped to sheet1 and one globally - XSSFName nameSheet1 = wb.createName(); - nameSheet1.setNameName("name1"); - nameSheet1.setRefersToFormula("'First Sheet'!$A$1"); - nameSheet1.setSheetIndex(0); - - XSSFName nameGlobal = wb.createName(); - nameGlobal.setNameName("name1"); - nameGlobal.setRefersToFormula("'First Sheet'!$B$1"); - - // Rename sheet-scoped name to "name2", check everything is updated properly - // and that the other name is unaffected - nameSheet1.setNameName("name2"); - assertEquals(1, wb.getNames("name1").size()); - assertEquals(1, wb.getNames("name2").size()); - assertEquals(nameGlobal, wb.getName("name1")); - assertEquals(nameSheet1, wb.getName("name2")); - - // Rename the other name to "name" and check everything again - nameGlobal.setNameName("name2"); - assertEquals(0, wb.getNames("name1").size()); - assertEquals(2, wb.getNames("name2").size()); - assertTrue(wb.getNames("name2").contains(nameGlobal)); - assertTrue(wb.getNames("name2").contains(nameSheet1)); - - wb.close(); - } - - //github-55 - @Test - void testSetNameNameCellAddress() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - wb.createSheet("First Sheet"); - XSSFName name = wb.createName(); - - // Cell addresses/references are not allowed - for (String ref : Arrays.asList("A1", "$A$1", "A1:B2")) { - assertThrows(IllegalArgumentException.class, () -> name.setNameName(ref), - "cell addresses are not allowed: " + ref); - } - - // Name that looks similar to a cell reference but is outside the cell reference row and column limits - name.setNameName("A0"); - name.setNameName("F04030020010"); - name.setNameName("XFDXFD10"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddFooter.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddFooter.java deleted file mode 100644 index 4113de6225..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddFooter.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestXSSFOddFooter { - - private XSSFWorkbook wb; - private XSSFSheet sheet; - - @BeforeEach - void before() { - wb = new XSSFWorkbook(); - sheet = wb.createSheet(); - } - - @AfterEach - void after() throws Exception { - wb.close(); - } - - @Test - void testSetGetText() { - XSSFOddFooter footer = (XSSFOddFooter) sheet.getOddFooter(); - assertNotNull(footer); - assertNull(footer.getText()); - footer.setText("this is a test"); - assertEquals("this is a test", footer.getText()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddHeader.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddHeader.java deleted file mode 100644 index 4f88009127..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFOddHeader.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TestXSSFOddHeader { - - private XSSFWorkbook wb; - private XSSFSheet sheet; - - @BeforeEach - void before() { - wb = new XSSFWorkbook(); - sheet = wb.createSheet(); - } - - @AfterEach - void after() throws Exception { - wb.close(); - } - - @Test - void testSetGetText() { - XSSFOddHeader header = (XSSFOddHeader) sheet.getOddHeader(); - assertNotNull(header); - assertNull(header.getText()); - header.setText("this is a test"); - assertEquals("this is a test", header.getText()); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPicture.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPicture.java deleted file mode 100644 index b544f916ac..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPicture.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -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 java.io.IOException; -import java.util.List; - -import org.apache.poi.ss.usermodel.BaseTestPicture; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Picture; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.STEditAs; - -public final class TestXSSFPicture extends BaseTestPicture { - - public TestXSSFPicture() { - super(XSSFITestDataProvider.instance); - } - - protected Picture getPictureShape(Drawing<?> pat, int picIdx) { - return (Picture)((XSSFDrawing)pat).getShapes().get(picIdx); - } - - @Test - void create() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - byte[] jpegData = "test jpeg data".getBytes(LocaleUtil.CHARSET_1252); - - List<XSSFPictureData> pictures = wb.getAllPictures(); - assertEquals(0, pictures.size()); - - int jpegIdx = wb.addPicture(jpegData, XSSFWorkbook.PICTURE_TYPE_JPEG); - assertEquals(1, pictures.size()); - assertEquals("jpeg", pictures.get(jpegIdx).suggestFileExtension()); - assertArrayEquals(jpegData, pictures.get(jpegIdx).getData()); - - XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30); - assertEquals(AnchorType.MOVE_AND_RESIZE, anchor.getAnchorType()); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - assertEquals(AnchorType.DONT_MOVE_AND_RESIZE, anchor.getAnchorType()); - - XSSFPicture shape = drawing.createPicture(anchor, jpegIdx); - assertEquals(anchor, shape.getAnchor()); - assertNotNull(shape.getPictureData()); - assertArrayEquals(jpegData, shape.getPictureData().getData()); - - CTTwoCellAnchor ctShapeHolder = drawing.getCTDrawing().getTwoCellAnchorArray(0); - // STEditAs.ABSOLUTE corresponds to ClientAnchor.DONT_MOVE_AND_RESIZE - assertEquals(STEditAs.ABSOLUTE, ctShapeHolder.getEditAs()); - } - } - - /** - * test that ShapeId in CTNonVisualDrawingProps is incremented - * - * See Bugzilla 50458 - */ - @Test - void incrementShapeId() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30); - byte[] jpegData = "picture1".getBytes(LocaleUtil.CHARSET_1252); - int jpegIdx = wb.addPicture(jpegData, XSSFWorkbook.PICTURE_TYPE_JPEG); - - XSSFPicture shape1 = drawing.createPicture(anchor, jpegIdx); - assertEquals(1, shape1.getCTPicture().getNvPicPr().getCNvPr().getId()); - - jpegData = "picture2".getBytes(LocaleUtil.CHARSET_1252); - jpegIdx = wb.addPicture(jpegData, XSSFWorkbook.PICTURE_TYPE_JPEG); - XSSFPicture shape2 = drawing.createPicture(anchor, jpegIdx); - assertEquals(2, shape2.getCTPicture().getNvPicPr().getCNvPr().getId()); - } - } - - /** - * same image refrerred by mulitple sheets - */ - @Test - void multiRelationShips() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - byte[] pic1Data = "test jpeg data".getBytes(LocaleUtil.CHARSET_1252); - byte[] pic2Data = "test png data".getBytes(LocaleUtil.CHARSET_1252); - - List<XSSFPictureData> pictures = wb1.getAllPictures(); - assertEquals(0, pictures.size()); - - int pic1 = wb1.addPicture(pic1Data, XSSFWorkbook.PICTURE_TYPE_JPEG); - int pic2 = wb1.addPicture(pic2Data, XSSFWorkbook.PICTURE_TYPE_PNG); - - XSSFSheet sheet1 = wb1.createSheet(); - XSSFDrawing drawing1 = sheet1.createDrawingPatriarch(); - XSSFPicture shape1 = drawing1.createPicture(new XSSFClientAnchor(), pic1); - XSSFPicture shape2 = drawing1.createPicture(new XSSFClientAnchor(), pic2); - - XSSFSheet sheet2 = wb1.createSheet(); - XSSFDrawing drawing2 = sheet2.createDrawingPatriarch(); - XSSFPicture shape3 = drawing2.createPicture(new XSSFClientAnchor(), pic2); - XSSFPicture shape4 = drawing2.createPicture(new XSSFClientAnchor(), pic1); - - assertEquals(2, pictures.size()); - - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { - pictures = wb2.getAllPictures(); - assertEquals(2, pictures.size()); - - sheet1 = wb2.getSheetAt(0); - drawing1 = sheet1.createDrawingPatriarch(); - XSSFPicture shape11 = (XSSFPicture) drawing1.getShapes().get(0); - assertArrayEquals(shape1.getPictureData().getData(), shape11.getPictureData().getData()); - XSSFPicture shape22 = (XSSFPicture) drawing1.getShapes().get(1); - assertArrayEquals(shape2.getPictureData().getData(), shape22.getPictureData().getData()); - - sheet2 = wb2.getSheetAt(1); - drawing2 = sheet2.createDrawingPatriarch(); - XSSFPicture shape33 = (XSSFPicture) drawing2.getShapes().get(0); - assertArrayEquals(shape3.getPictureData().getData(), shape33.getPictureData().getData()); - XSSFPicture shape44 = (XSSFPicture) drawing2.getShapes().get(1); - assertArrayEquals(shape4.getPictureData().getData(), shape44.getPictureData().getData()); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPictureData.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPictureData.java deleted file mode 100644 index 5f8514c87b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPictureData.java +++ /dev/null @@ -1,146 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -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.assertSame; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * @author Yegor Kozlov - */ -public final class TestXSSFPictureData { - @Test - void testRead() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx"); - List<XSSFPictureData> pictures = wb.getAllPictures(); - //wb.getAllPictures() should return the same instance across multiple calls - assertSame(pictures, wb.getAllPictures()); - - assertEquals(5, pictures.size()); - String[] ext = {"jpeg", "emf", "png", "emf", "wmf"}; - String[] mimetype = {"image/jpeg", "image/x-emf", "image/png", "image/x-emf", "image/x-wmf"}; - for (int i = 0; i < pictures.size(); i++) { - assertEquals(ext[i], pictures.get(i).suggestFileExtension()); - assertEquals(mimetype[i], pictures.get(i).getMimeType()); - } - - int num = pictures.size(); - - byte[] pictureData = {0xA, 0xB, 0XC, 0xD, 0xE, 0xF}; - - int idx = wb.addPicture(pictureData, XSSFWorkbook.PICTURE_TYPE_JPEG); - assertEquals(num + 1, pictures.size()); - //idx is 0-based index in the #pictures array - assertEquals(pictures.size() - 1, idx); - XSSFPictureData pict = pictures.get(idx); - assertEquals("jpeg", pict.suggestFileExtension()); - assertArrayEquals(pictureData, pict.getData()); - wb.close(); - } - - @Test - void testNew() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - byte[] jpegData = "test jpeg data".getBytes(LocaleUtil.CHARSET_1252); - byte[] wmfData = "test wmf data".getBytes(LocaleUtil.CHARSET_1252); - byte[] pngData = "test png data".getBytes(LocaleUtil.CHARSET_1252); - - List<XSSFPictureData> pictures = wb.getAllPictures(); - assertEquals(0, pictures.size()); - - int jpegIdx = wb.addPicture(jpegData, XSSFWorkbook.PICTURE_TYPE_JPEG); - assertEquals(1, pictures.size()); - assertEquals("jpeg", pictures.get(jpegIdx).suggestFileExtension()); - assertArrayEquals(jpegData, pictures.get(jpegIdx).getData()); - - int wmfIdx = wb.addPicture(wmfData, XSSFWorkbook.PICTURE_TYPE_WMF); - assertEquals(2, pictures.size()); - assertEquals("wmf", pictures.get(wmfIdx).suggestFileExtension()); - assertArrayEquals(wmfData, pictures.get(wmfIdx).getData()); - - int pngIdx = wb.addPicture(pngData, XSSFWorkbook.PICTURE_TYPE_PNG); - assertEquals(3, pictures.size()); - assertEquals("png", pictures.get(pngIdx).suggestFileExtension()); - assertArrayEquals(pngData, pictures.get(pngIdx).getData()); - - //TODO finish usermodel API for XSSFPicture - XSSFPicture p1 = drawing.createPicture(new XSSFClientAnchor(), jpegIdx); - assertNotNull(p1); - XSSFPicture p2 = drawing.createPicture(new XSSFClientAnchor(), wmfIdx); - assertNotNull(p2); - XSSFPicture p3 = drawing.createPicture(new XSSFClientAnchor(), pngIdx); - assertNotNull(p3); - - //check that the added pictures are accessible after write - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - List<XSSFPictureData> pictures2 = wbBack.getAllPictures(); - assertEquals(3, pictures2.size()); - - assertEquals("jpeg", pictures2.get(jpegIdx).suggestFileExtension()); - assertArrayEquals(jpegData, pictures2.get(jpegIdx).getData()); - - assertEquals("wmf", pictures2.get(wmfIdx).suggestFileExtension()); - assertArrayEquals(wmfData, pictures2.get(wmfIdx).getData()); - - assertEquals("png", pictures2.get(pngIdx).suggestFileExtension()); - assertArrayEquals(pngData, pictures2.get(pngIdx).getData()); - wbBack.close(); - wb.close(); - } - - /** - * Bug 53568: XSSFPicture.getPictureData() can return null. - */ - @Test - void test53568() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53568.xlsx"); - List<XSSFPictureData> pictures = wb.getAllPictures(); - assertNotNull(pictures); - assertEquals(4, pictures.size()); - - XSSFSheet sheet1 = wb.getSheetAt(0); - List<XSSFShape> shapes1 = sheet1.createDrawingPatriarch().getShapes(); - assertNotNull(shapes1); - assertEquals(5, shapes1.size()); - - for(int i = 0; i < wb.getNumberOfSheets(); i++){ - XSSFSheet sheet = wb.getSheetAt(i); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - for(XSSFShape shape : drawing.getShapes()){ - if(shape instanceof XSSFPicture){ - XSSFPicture pic = (XSSFPicture)shape; - XSSFPictureData picData = pic.getPictureData(); - assertNotNull(picData); - } - } - } - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableName.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableName.java deleted file mode 100644 index fc001229ce..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableName.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.BeforeEach; - -/** - * Test pivot tables created by named range - */ -class TestXSSFPivotTableName extends BaseTestXSSFPivotTable { - - @Override - @BeforeEach - protected void setUp(){ - wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - - Row row1 = sheet.createRow(0); - // Create a cell and put a value in it. - Cell cell = row1.createCell(0); - cell.setCellValue("Names"); - Cell cell2 = row1.createCell(1); - cell2.setCellValue("#"); - Cell cell7 = row1.createCell(2); - cell7.setCellValue("Data"); - Cell cell10 = row1.createCell(3); - cell10.setCellValue("Value"); - - Row row2 = sheet.createRow(1); - Cell cell3 = row2.createCell(0); - cell3.setCellValue("Jan"); - Cell cell4 = row2.createCell(1); - cell4.setCellValue(10); - Cell cell8 = row2.createCell(2); - cell8.setCellValue("Apa"); - Cell cell11 = row1.createCell(3); - cell11.setCellValue(11.11); - - Row row3 = sheet.createRow(2); - Cell cell5 = row3.createCell(0); - cell5.setCellValue("Ben"); - Cell cell6 = row3.createCell(1); - cell6.setCellValue(9); - Cell cell9 = row3.createCell(2); - cell9.setCellValue("Bepa"); - Cell cell12 = row1.createCell(3); - cell12.setCellValue(12.12); - - XSSFName namedRange = sheet.getWorkbook().createName(); - namedRange.setRefersToFormula(sheet.getSheetName() + "!" + "A1:C2"); - pivotTable = sheet.createPivotTable(namedRange, new CellReference("H5")); - - XSSFSheet offsetSheet = wb.createSheet(); - - Row tableRow_1 = offsetSheet.createRow(1); - offsetOuterCell = tableRow_1.createCell(1); - offsetOuterCell.setCellValue(-1); - Cell tableCell_1_1 = tableRow_1.createCell(2); - tableCell_1_1.setCellValue("Row #"); - Cell tableCell_1_2 = tableRow_1.createCell(3); - tableCell_1_2.setCellValue("Exponent"); - Cell tableCell_1_3 = tableRow_1.createCell(4); - tableCell_1_3.setCellValue("10^Exponent"); - - Row tableRow_2 = offsetSheet.createRow(2); - Cell tableCell_2_1 = tableRow_2.createCell(2); - tableCell_2_1.setCellValue(0); - Cell tableCell_2_2 = tableRow_2.createCell(3); - tableCell_2_2.setCellValue(0); - Cell tableCell_2_3 = tableRow_2.createCell(4); - tableCell_2_3.setCellValue(1); - - Row tableRow_3= offsetSheet.createRow(3); - Cell tableCell_3_1 = tableRow_3.createCell(2); - tableCell_3_1.setCellValue(1); - Cell tableCell_3_2 = tableRow_3.createCell(3); - tableCell_3_2.setCellValue(1); - Cell tableCell_3_3 = tableRow_3.createCell(4); - tableCell_3_3.setCellValue(10); - - Row tableRow_4 = offsetSheet.createRow(4); - Cell tableCell_4_1 = tableRow_4.createCell(2); - tableCell_4_1.setCellValue(2); - Cell tableCell_4_2 = tableRow_4.createCell(3); - tableCell_4_2.setCellValue(2); - Cell tableCell_4_3 = tableRow_4.createCell(4); - tableCell_4_3.setCellValue(100); - - namedRange = sheet.getWorkbook().createName(); - namedRange.setRefersToFormula("C2:E4"); - namedRange.setSheetIndex(sheet.getWorkbook().getSheetIndex(sheet)); - offsetPivotTable = offsetSheet.createPivotTable(namedRange, new CellReference("C6")); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableRef.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableRef.java deleted file mode 100644 index 29ddf4b7ea..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableRef.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.BeforeEach; - -/** - * Test pivot tables created by area reference - */ -class TestXSSFPivotTableRef extends BaseTestXSSFPivotTable { - - @Override - @BeforeEach - protected void setUp(){ - wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - - Row row1 = sheet.createRow(0); - // Create a cell and put a value in it. - Cell cell = row1.createCell(0); - cell.setCellValue("Names"); - Cell cell2 = row1.createCell(1); - cell2.setCellValue("#"); - Cell cell7 = row1.createCell(2); - cell7.setCellValue("Data"); - Cell cell10 = row1.createCell(3); - cell10.setCellValue("Value"); - - Row row2 = sheet.createRow(1); - Cell cell3 = row2.createCell(0); - cell3.setCellValue("Jan"); - Cell cell4 = row2.createCell(1); - cell4.setCellValue(10); - Cell cell8 = row2.createCell(2); - cell8.setCellValue("Apa"); - Cell cell11 = row1.createCell(3); - cell11.setCellValue(11.11); - - Row row3 = sheet.createRow(2); - Cell cell5 = row3.createCell(0); - cell5.setCellValue("Ben"); - Cell cell6 = row3.createCell(1); - cell6.setCellValue(9); - Cell cell9 = row3.createCell(2); - cell9.setCellValue("Bepa"); - Cell cell12 = row1.createCell(3); - cell12.setCellValue(12.12); - - AreaReference source = wb.getCreationHelper().createAreaReference("A1:C2"); - pivotTable = sheet.createPivotTable(source, new CellReference("H5")); - - XSSFSheet offsetSheet = wb.createSheet(); - - Row tableRow_1 = offsetSheet.createRow(1); - offsetOuterCell = tableRow_1.createCell(1); - offsetOuterCell.setCellValue(-1); - Cell tableCell_1_1 = tableRow_1.createCell(2); - tableCell_1_1.setCellValue("Row #"); - Cell tableCell_1_2 = tableRow_1.createCell(3); - tableCell_1_2.setCellValue("Exponent"); - Cell tableCell_1_3 = tableRow_1.createCell(4); - tableCell_1_3.setCellValue("10^Exponent"); - - Row tableRow_2 = offsetSheet.createRow(2); - Cell tableCell_2_1 = tableRow_2.createCell(2); - tableCell_2_1.setCellValue(0); - Cell tableCell_2_2 = tableRow_2.createCell(3); - tableCell_2_2.setCellValue(0); - Cell tableCell_2_3 = tableRow_2.createCell(4); - tableCell_2_3.setCellValue(1); - - Row tableRow_3= offsetSheet.createRow(3); - Cell tableCell_3_1 = tableRow_3.createCell(2); - tableCell_3_1.setCellValue(1); - Cell tableCell_3_2 = tableRow_3.createCell(3); - tableCell_3_2.setCellValue(1); - Cell tableCell_3_3 = tableRow_3.createCell(4); - tableCell_3_3.setCellValue(10); - - Row tableRow_4 = offsetSheet.createRow(4); - Cell tableCell_4_1 = tableRow_4.createCell(2); - tableCell_4_1.setCellValue(2); - Cell tableCell_4_2 = tableRow_4.createCell(3); - tableCell_4_2.setCellValue(2); - Cell tableCell_4_3 = tableRow_4.createCell(4); - tableCell_4_3.setCellValue(100); - - AreaReference offsetSource = wb.getCreationHelper().createAreaReference( - new CellReference("C2"), new CellReference("E4")); - offsetPivotTable = offsetSheet.createPivotTable(offsetSource, new CellReference("C6")); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPrintSetup.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPrintSetup.java deleted file mode 100644 index f0507e3590..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPrintSetup.java +++ /dev/null @@ -1,324 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.assertTrue; - -import org.apache.poi.ss.usermodel.PageOrder; -import org.apache.poi.ss.usermodel.PaperSize; -import org.apache.poi.ss.usermodel.PrintCellComments; -import org.apache.poi.ss.usermodel.PrintOrientation; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageMargins; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageSetup; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellComments; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STOrientation; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPageOrder; - -/** - * Tests for {@link XSSFPrintSetup} - */ -class TestXSSFPrintSetup { - @Test - void testSetGetPaperSize() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setPaperSize(9); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(PaperSize.A4_PAPER, printSetup.getPaperSizeEnum()); - assertEquals(9, printSetup.getPaperSize()); - - printSetup.setPaperSize(PaperSize.A3_PAPER); - assertEquals(8, pSetup.getPaperSize()); - } - - @Test - void testSetGetScale() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setScale(9); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(9, printSetup.getScale()); - - printSetup.setScale((short) 100); - assertEquals(100, pSetup.getScale()); - } - - @Test - void testSetGetPageStart() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setFirstPageNumber(9); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(9, printSetup.getPageStart()); - - printSetup.setPageStart((short) 1); - assertEquals(1, pSetup.getFirstPageNumber()); - } - - @Test - void testSetGetFitWidthHeight() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setFitToWidth(50); - pSetup.setFitToHeight(99); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(50, printSetup.getFitWidth()); - assertEquals(99, printSetup.getFitHeight()); - - printSetup.setFitWidth((short) 66); - printSetup.setFitHeight((short) 80); - assertEquals(66, pSetup.getFitToWidth()); - assertEquals(80, pSetup.getFitToHeight()); - - } - - @Test - void testSetGetLeftToRight() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setPageOrder(STPageOrder.DOWN_THEN_OVER); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertFalse(printSetup.getLeftToRight()); - - printSetup.setLeftToRight(true); - assertEquals(PageOrder.OVER_THEN_DOWN.getValue(), pSetup.getPageOrder().intValue()); - } - - @Test - void testSetGetOrientation() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setOrientation(STOrientation.PORTRAIT); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(PrintOrientation.PORTRAIT, printSetup.getOrientation()); - assertFalse(printSetup.getLandscape()); - assertFalse(printSetup.getNoOrientation()); - - printSetup.setOrientation(PrintOrientation.LANDSCAPE); - assertEquals(pSetup.getOrientation().intValue(), printSetup.getOrientation().getValue()); - assertTrue(printSetup.getLandscape()); - assertFalse(printSetup.getNoOrientation()); - } - - @Test - void testSetGetValidSettings() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setUsePrinterDefaults(false); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertFalse(printSetup.getValidSettings()); - - printSetup.setValidSettings(true); - assertTrue(pSetup.getUsePrinterDefaults()); - } - - @Test - void testSetGetNoColor() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setBlackAndWhite(false); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertFalse(printSetup.getNoColor()); - - printSetup.setNoColor(true); - assertTrue(pSetup.getBlackAndWhite()); - } - - @Test - void testSetGetDraft() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setDraft(false); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertFalse(printSetup.getDraft()); - - printSetup.setDraft(true); - assertTrue(pSetup.getDraft()); - } - - @Test - void testSetGetNotes() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setCellComments(STCellComments.NONE); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertFalse(printSetup.getNotes()); - - printSetup.setNotes(true); - assertEquals(PrintCellComments.AS_DISPLAYED.getValue(), pSetup.getCellComments().intValue()); - } - - @Test - void testSetGetUsePage() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setUseFirstPageNumber(false); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertFalse(printSetup.getUsePage()); - - printSetup.setUsePage(true); - assertTrue(pSetup.getUseFirstPageNumber()); - } - - @Test - void testSetGetHVResolution() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setHorizontalDpi(120); - pSetup.setVerticalDpi(100); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(120, printSetup.getHResolution()); - assertEquals(100, printSetup.getVResolution()); - - printSetup.setHResolution((short) 150); - printSetup.setVResolution((short) 130); - assertEquals(150, pSetup.getHorizontalDpi()); - assertEquals(130, pSetup.getVerticalDpi()); - } - - @Test - void testSetGetHeaderFooterMargin() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageMargins pMargins = worksheet.addNewPageMargins(); - pMargins.setHeader(1.5); - pMargins.setFooter(2); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(1.5, printSetup.getHeaderMargin(), 0.0); - assertEquals(2.0, printSetup.getFooterMargin(), 0.0); - - printSetup.setHeaderMargin(5); - printSetup.setFooterMargin(3.5); - assertEquals(5.0, pMargins.getHeader(), 0.0); - assertEquals(3.5, pMargins.getFooter(), 0.0); - } - - @Test - void testSetGetMargins() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageMargins pMargins = worksheet.addNewPageMargins(); - pMargins.setTop(5.3); - pMargins.setBottom(1.5); - pMargins.setLeft(2); - pMargins.setRight(3.2); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(5.3, printSetup.getTopMargin(), 0.0); - assertEquals(1.5, printSetup.getBottomMargin(), 0.0); - assertEquals(2, printSetup.getLeftMargin(), 0.0); - assertEquals(3.2, printSetup.getRightMargin(), 0.0); - - printSetup.setTopMargin(9); - printSetup.setBottomMargin(6.4); - printSetup.setLeftMargin(7.8); - printSetup.setRightMargin(8.1); - assertEquals(9, pMargins.getTop(), 0.0); - assertEquals(6.4, pMargins.getBottom(), 0.0); - assertEquals(7.8, pMargins.getLeft(), 0.0); - assertEquals(8.1, pMargins.getRight(), 0.0); - } - - @Test - void testSetGetCopies() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setCopies(9); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(9, printSetup.getCopies()); - - printSetup.setCopies((short) 15); - assertEquals(15, pSetup.getCopies()); - } - - @Test - void testSetSaveRead() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet s1 = wb.createSheet(); - assertFalse(s1.getCTWorksheet().isSetPageSetup()); - assertTrue(s1.getCTWorksheet().isSetPageMargins()); - - XSSFPrintSetup print = s1.getPrintSetup(); - assertTrue(s1.getCTWorksheet().isSetPageSetup()); - assertTrue(s1.getCTWorksheet().isSetPageMargins()); - - print.setCopies((short)3); - print.setLandscape(true); - assertEquals(3, print.getCopies()); - assertTrue(print.getLandscape()); - - XSSFSheet s2 = wb.createSheet(); - assertFalse(s2.getCTWorksheet().isSetPageSetup()); - assertTrue(s2.getCTWorksheet().isSetPageMargins()); - - // Round trip and check - XSSFWorkbook wbBack = XSSFITestDataProvider.instance.writeOutAndReadBack(wb); - - s1 = wbBack.getSheetAt(0); - s2 = wbBack.getSheetAt(1); - - assertTrue(s1.getCTWorksheet().isSetPageSetup()); - assertTrue(s1.getCTWorksheet().isSetPageMargins()); - assertFalse(s2.getCTWorksheet().isSetPageSetup()); - assertTrue(s2.getCTWorksheet().isSetPageMargins()); - - print = s1.getPrintSetup(); - assertEquals(3, print.getCopies()); - assertTrue(print.getLandscape()); - - wb.close(); - } - - /** - * Open a file with print settings, save and check. - * Then, change, save, read, check - */ - @Disabled - void testRoundTrip() { - // TODO - } - - @Test - void testSetLandscapeFalse() { - XSSFPrintSetup ps = new XSSFPrintSetup(CTWorksheet.Factory.newInstance()); - - assertFalse(ps.getLandscape()); - - ps.setLandscape(true); - assertTrue(ps.getLandscape()); - - ps.setLandscape(false); - assertFalse(ps.getLandscape()); - } - - @Test - void testSetLeftToRight() { - XSSFPrintSetup ps = new XSSFPrintSetup(CTWorksheet.Factory.newInstance()); - - assertFalse(ps.getLeftToRight()); - - ps.setLeftToRight(true); - assertTrue(ps.getLeftToRight()); - - ps.setLeftToRight(false); - assertFalse(ps.getLeftToRight()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java deleted file mode 100644 index 9a0215e1b0..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java +++ /dev/null @@ -1,562 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.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; -import java.util.Objects; -import java.util.Spliterator; -import java.util.TreeMap; -import java.util.stream.IntStream; -import java.util.stream.StreamSupport; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.StylesTable; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STXstring; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; - -/** - * Tests functionality of the XSSFRichTextRun object - */ -public final class TestXSSFRichTextString { - - @Test - void testCreate() { - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - assertEquals("Apache POI", rt.getString()); - assertFalse(rt.hasFormatting()); - - CTRst st = rt.getCTRst(); - assertTrue(st.isSetT()); - assertEquals("Apache POI", st.getT()); - assertFalse(rt.hasFormatting()); - - rt.append(" is cool stuff"); - assertEquals(2, st.sizeOfRArray()); - assertFalse(st.isSetT()); - - assertEquals("Apache POI is cool stuff", rt.getString()); - assertFalse(rt.hasFormatting()); - } - - @Test - void testEmpty() { - XSSFRichTextString rt = new XSSFRichTextString(); - assertEquals(0, rt.getIndexOfFormattingRun(9999)); - assertEquals(-1, rt.getLengthOfFormattingRun(9999)); - assertNull(rt.getFontAtIndex(9999)); - } - - @Test - void testApplyFont() { - XSSFRichTextString rt = new XSSFRichTextString(); - rt.append("123"); - rt.append("4567"); - rt.append("89"); - - assertEquals("123456789", rt.getString()); - assertFalse(rt.hasFormatting()); - - XSSFFont font1 = new XSSFFont(); - font1.setBold(true); - - rt.applyFont(2, 5, font1); - assertTrue(rt.hasFormatting()); - - assertEquals(4, rt.numFormattingRuns()); - assertEquals(0, rt.getIndexOfFormattingRun(0)); - assertEquals("12", rt.getCTRst().getRArray(0).getT()); - - assertEquals(2, rt.getIndexOfFormattingRun(1)); - assertEquals("345", rt.getCTRst().getRArray(1).getT()); - - assertEquals(5, rt.getIndexOfFormattingRun(2)); - assertEquals(2, rt.getLengthOfFormattingRun(2)); - assertEquals("67", rt.getCTRst().getRArray(2).getT()); - - assertEquals(7, rt.getIndexOfFormattingRun(3)); - assertEquals(2, rt.getLengthOfFormattingRun(3)); - assertEquals("89", rt.getCTRst().getRArray(3).getT()); - - - assertEquals(-1, rt.getIndexOfFormattingRun(9999)); - assertEquals(-1, rt.getLengthOfFormattingRun(9999)); - assertNull(rt.getFontAtIndex(9999)); - } - - @Test - void testApplyFontIndex() { - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - rt.applyFont(0, 10, (short)1); - - rt.applyFont((short)1); - - assertNotNull(rt.getFontAtIndex(0)); - } - - @Test - void testApplyFontWithStyles() { - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - - StylesTable tbl = new StylesTable(); - rt.setStylesTableReference(tbl); - assertThrows(IndexOutOfBoundsException.class, () -> rt.applyFont(0, 10, (short)1), "Fails without styles in the table"); - - tbl.putFont(new XSSFFont()); - rt.applyFont(0, 10, (short)1); - rt.applyFont((short)1); - } - - @Test - void testApplyFontException() { - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - - rt.applyFont(0, 0, (short)1); - IllegalArgumentException e; - e = assertThrows(IllegalArgumentException.class, () -> rt.applyFont(11, 10, (short)1)); - assertTrue(e.getMessage().contains("11")); - - e = assertThrows(IllegalArgumentException.class, () -> rt.applyFont(-1, 10, (short)1)); - assertTrue(e.getMessage().contains("-1")); - - e = assertThrows(IllegalArgumentException.class, () -> rt.applyFont(0, 555, (short)1)); - assertTrue(e.getMessage().contains("555")); - } - - @Test - void testClearFormatting() { - - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - assertEquals("Apache POI", rt.getString()); - assertFalse(rt.hasFormatting()); - - rt.clearFormatting(); - - CTRst st = rt.getCTRst(); - assertTrue(st.isSetT()); - assertEquals("Apache POI", rt.getString()); - assertEquals(0, rt.numFormattingRuns()); - assertFalse(rt.hasFormatting()); - - XSSFFont font = new XSSFFont(); - font.setBold(true); - - rt.applyFont(7, 10, font); - assertEquals(2, rt.numFormattingRuns()); - assertTrue(rt.hasFormatting()); - - rt.clearFormatting(); - - assertEquals("Apache POI", rt.getString()); - assertEquals(0, rt.numFormattingRuns()); - assertFalse(rt.hasFormatting()); - } - - @Test - void testGetFonts() { - - XSSFRichTextString rt = new XSSFRichTextString(); - - XSSFFont font1 = new XSSFFont(); - font1.setFontName("Arial"); - font1.setItalic(true); - rt.append("The quick", font1); - - XSSFFont font1$ = rt.getFontOfFormattingRun(0); - assertEquals(font1.getItalic(), font1$.getItalic()); - assertEquals(font1.getFontName(), font1$.getFontName()); - - XSSFFont font2 = new XSSFFont(); - font2.setFontName("Courier"); - font2.setBold(true); - rt.append(" brown fox", font2); - - XSSFFont font2$ = rt.getFontOfFormattingRun(1); - assertEquals(font2.getBold(), font2$.getBold()); - assertEquals(font2.getFontName(), font2$.getFontName()); - } - - /** - * make sure we insert xml:space="preserve" attribute - * if a string has leading or trailing white spaces - */ - @Test - void testPreserveSpaces() { - XSSFRichTextString rt = new XSSFRichTextString("Apache"); - CTRst ct = rt.getCTRst(); - STXstring xs = ct.xgetT(); - assertEquals("<xml-fragment>Apache</xml-fragment>", xs.xmlText()); - rt.setString(" Apache"); - assertEquals("<xml-fragment xml:space=\"preserve\"> Apache</xml-fragment>", xs.xmlText()); - - rt.append(" POI"); - rt.append(" "); - assertEquals(" Apache POI ", rt.getString()); - assertEquals("<xml-fragment xml:space=\"preserve\"> Apache</xml-fragment>", rt.getCTRst().getRArray(0).xgetT().xmlText()); - assertEquals("<xml-fragment xml:space=\"preserve\"> POI</xml-fragment>", rt.getCTRst().getRArray(1).xgetT().xmlText()); - assertEquals("<xml-fragment xml:space=\"preserve\"> </xml-fragment>", rt.getCTRst().getRArray(2).xgetT().xmlText()); - } - - /** - * test that unicode representation_ xHHHH_ is properly processed - */ - @Test - void testUtfDecode() { - CTRst st = CTRst.Factory.newInstance(); - st.setT("abc_x000D_2ef_x000D_"); - XSSFRichTextString rt = new XSSFRichTextString(st); - //_x000D_ is converted into carriage return - assertEquals("abc\r2ef\r", rt.getString()); - - // Test Lowercase case - CTRst st2 = CTRst.Factory.newInstance(); - st2.setT("abc_x000d_2ef_x000d_"); - XSSFRichTextString rt2 = new XSSFRichTextString(st2); - assertEquals("abc\r2ef\r", rt2.getString()); - } - - @Test - void testApplyFont_lowlevel(){ - CTRst st = CTRst.Factory.newInstance(); - String text = "Apache Software Foundation"; - XSSFRichTextString str = new XSSFRichTextString(text); - assertEquals(26, text.length()); - - st.addNewR().setT(text); - - TreeMap<Integer, CTRPrElt> formats = str.getFormatMap(st); - assertEquals(1, formats.size()); - assertEquals(26, (int)formats.firstKey()); - assertNull(formats.get( formats.firstKey() )); - - CTRPrElt fmt1 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 0, 6, fmt1); - assertEquals(2, formats.size()); - assertEquals("[6, 26]", formats.keySet().toString()); - Object[] runs1 = formats.values().toArray(); - assertSame(fmt1, runs1[0]); - assertSame(null, runs1[1]); - - CTRPrElt fmt2 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 7, 15, fmt2); - assertEquals(4, formats.size()); - assertEquals("[6, 7, 15, 26]", formats.keySet().toString()); - Object[] runs2 = formats.values().toArray(); - assertSame(fmt1, runs2[0]); - assertSame(null, runs2[1]); - assertSame(fmt2, runs2[2]); - assertSame(null, runs2[3]); - - CTRPrElt fmt3 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 6, 7, fmt3); - assertEquals(4, formats.size()); - assertEquals("[6, 7, 15, 26]", formats.keySet().toString()); - Object[] runs3 = formats.values().toArray(); - assertSame(fmt1, runs3[0]); - assertSame(fmt3, runs3[1]); - assertSame(fmt2, runs3[2]); - assertSame(null, runs3[3]); - - CTRPrElt fmt4 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 0, 7, fmt4); - assertEquals(3, formats.size()); - assertEquals("[7, 15, 26]", formats.keySet().toString()); - Object[] runs4 = formats.values().toArray(); - assertSame(fmt4, runs4[0]); - assertSame(fmt2, runs4[1]); - assertSame(null, runs4[2]); - - CTRPrElt fmt5 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 0, 26, fmt5); - assertEquals(1, formats.size()); - assertEquals("[26]", formats.keySet().toString()); - Object[] runs5 = formats.values().toArray(); - assertSame(fmt5, runs5[0]); - - CTRPrElt fmt6 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 15, 26, fmt6); - assertEquals(2, formats.size()); - assertEquals("[15, 26]", formats.keySet().toString()); - Object[] runs6 = formats.values().toArray(); - assertSame(fmt5, runs6[0]); - assertSame(fmt6, runs6[1]); - - str.applyFont(formats, 0, 26, null); - assertEquals(1, formats.size()); - assertEquals("[26]", formats.keySet().toString()); - Object[] runs7 = formats.values().toArray(); - assertSame(null, runs7[0]); - - str.applyFont(formats, 15, 26, fmt6); - assertEquals(2, formats.size()); - assertEquals("[15, 26]", formats.keySet().toString()); - Object[] runs8 = formats.values().toArray(); - assertSame(null, runs8[0]); - assertSame(fmt6, runs8[1]); - - str.applyFont(formats, 15, 26, fmt5); - assertEquals(2, formats.size()); - assertEquals("[15, 26]", formats.keySet().toString()); - Object[] runs9 = formats.values().toArray(); - assertSame(null, runs9[0]); - assertSame(fmt5, runs9[1]); - - str.applyFont(formats, 2, 20, fmt6); - assertEquals(3, formats.size()); - assertEquals("[2, 20, 26]", formats.keySet().toString()); - Object[] runs10 = formats.values().toArray(); - assertSame(null, runs10[0]); - assertSame(fmt6, runs10[1]); - assertSame(fmt5, runs10[2]); - - str.applyFont(formats, 22, 24, fmt4); - assertEquals(5, formats.size()); - assertEquals("[2, 20, 22, 24, 26]", formats.keySet().toString()); - Object[] runs11 = formats.values().toArray(); - assertSame(null, runs11[0]); - assertSame(fmt6, runs11[1]); - assertSame(fmt5, runs11[2]); - assertSame(fmt4, runs11[3]); - assertSame(fmt5, runs11[4]); - - str.applyFont(formats, 0, 10, fmt1); - assertEquals(5, formats.size()); - assertEquals("[10, 20, 22, 24, 26]", formats.keySet().toString()); - Object[] runs12 = formats.values().toArray(); - assertSame(fmt1, runs12[0]); - assertSame(fmt6, runs12[1]); - assertSame(fmt5, runs12[2]); - assertSame(fmt4, runs12[3]); - assertSame(fmt5, runs12[4]); - } - - @Test - void testApplyFont_usermodel(){ - String text = "Apache Software Foundation"; - XSSFRichTextString str = new XSSFRichTextString(text); - XSSFFont font1 = new XSSFFont(); - XSSFFont font2 = new XSSFFont(); - XSSFFont font3 = new XSSFFont(); - str.applyFont(font1); - assertEquals(1, str.numFormattingRuns()); - - str.applyFont(0, 6, font1); - str.applyFont(6, text.length(), font2); - assertEquals(2, str.numFormattingRuns()); - assertEquals("Apache", str.getCTRst().getRArray(0).getT()); - assertEquals(" Software Foundation", str.getCTRst().getRArray(1).getT()); - - str.applyFont(15, 26, font3); - assertEquals(3, str.numFormattingRuns()); - assertEquals("Apache", str.getCTRst().getRArray(0).getT()); - assertEquals(" Software", str.getCTRst().getRArray(1).getT()); - assertEquals(" Foundation", str.getCTRst().getRArray(2).getT()); - - str.applyFont(6, text.length(), font2); - assertEquals(2, str.numFormattingRuns()); - assertEquals("Apache", str.getCTRst().getRArray(0).getT()); - assertEquals(" Software Foundation", str.getCTRst().getRArray(1).getT()); - } - - @Test - void testLineBreaks_bug48877() { - - XSSFFont font = new XSSFFont(); - font.setBold(true); - font.setFontHeightInPoints((short) 14); - XSSFRichTextString str; - STXstring t1, t2, t3; - - str = new XSSFRichTextString("Incorrect\nLine-Breaking"); - str.applyFont(0, 8, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - assertEquals("<xml-fragment>Incorrec</xml-fragment>", t1.xmlText()); - assertEquals("<xml-fragment>t\nLine-Breaking</xml-fragment>", t2.xmlText()); - - str = new XSSFRichTextString("Incorrect\nLine-Breaking"); - str.applyFont(0, 9, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - assertEquals("<xml-fragment>Incorrect</xml-fragment>", t1.xmlText()); - assertEquals("<xml-fragment xml:space=\"preserve\">\nLine-Breaking</xml-fragment>", t2.xmlText()); - - str = new XSSFRichTextString("Incorrect\n Line-Breaking"); - str.applyFont(0, 9, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - assertEquals("<xml-fragment>Incorrect</xml-fragment>", t1.xmlText()); - assertEquals("<xml-fragment xml:space=\"preserve\">\n Line-Breaking</xml-fragment>", t2.xmlText()); - - str = new XSSFRichTextString("Tab\tseparated\n"); - t1 = str.getCTRst().xgetT(); - // trailing \n causes must be preserved - assertEquals("<xml-fragment xml:space=\"preserve\">Tab\tseparated\n</xml-fragment>", t1.xmlText()); - - str.applyFont(0, 3, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - assertEquals("<xml-fragment>Tab</xml-fragment>", t1.xmlText()); - assertEquals("<xml-fragment xml:space=\"preserve\">\tseparated\n</xml-fragment>", t2.xmlText()); - - str = new XSSFRichTextString("Tab\tseparated\n"); - str.applyFont(0, 4, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - assertEquals("<xml-fragment xml:space=\"preserve\">Tab\t</xml-fragment>", t1.xmlText()); - assertEquals("<xml-fragment xml:space=\"preserve\">separated\n</xml-fragment>", t2.xmlText()); - - str = new XSSFRichTextString("\n\n\nNew Line\n\n"); - str.applyFont(0, 3, font); - str.applyFont(11, 13, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - t3 = str.getCTRst().getRArray(2).xgetT(); - // YK: don't know why, but XmlBeans converts leading tab characters to spaces - assertEquals("<xml-fragment xml:space=\"preserve\">\n\n\n</xml-fragment>", t1.xmlText()); - assertEquals("<xml-fragment>New Line</xml-fragment>", t2.xmlText()); - assertEquals("<xml-fragment xml:space=\"preserve\">\n\n</xml-fragment>", t3.xmlText()); - } - - @Test - void testBug56511() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56511.xlsx")) { - int[] idx = { 0 }; - StreamSupport.stream(wb::spliterator, Spliterator.IMMUTABLE, false) - .flatMap(sheet -> StreamSupport.stream(sheet::spliterator, Spliterator.IMMUTABLE, false)) - .filter(Objects::nonNull) - .flatMap(row -> StreamSupport.stream(row::spliterator, Spliterator.IMMUTABLE, false)) - .filter(Objects::nonNull) - .map(Cell::getRichStringCellValue) - .map(XSSFRichTextString.class::cast) - .flatMap(x -> IntStream.range(0, x.numFormattingRuns()).mapToObj(x::getFontOfFormattingRun)) - .forEach(f -> { if (idx[0]++ == 2) { assertNull(f); } else { assertNotNull(f); }} ); - } - } - - @Test - void testBug56511_values() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56511.xlsx")) { - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - - // verify the values to ensure future changes keep the returned information equal - XSSFRichTextString rt = (XSSFRichTextString) row.getCell(0).getRichStringCellValue(); - assertEquals(0, rt.numFormattingRuns()); - assertNull(rt.getFontOfFormattingRun(0)); - assertEquals(-1, rt.getLengthOfFormattingRun(0)); - - rt = (XSSFRichTextString) row.getCell(1).getRichStringCellValue(); - assertEquals(0, row.getCell(1).getRichStringCellValue().numFormattingRuns()); - assertNull(rt.getFontOfFormattingRun(1)); - assertEquals(-1, rt.getLengthOfFormattingRun(1)); - - rt = (XSSFRichTextString) row.getCell(2).getRichStringCellValue(); - assertEquals(2, rt.numFormattingRuns()); - assertNotNull(rt.getFontOfFormattingRun(0)); - assertEquals(4, rt.getLengthOfFormattingRun(0)); - - assertNotNull(rt.getFontOfFormattingRun(1)); - assertEquals(9, rt.getLengthOfFormattingRun(1)); - - assertNull(rt.getFontOfFormattingRun(2)); - - rt = (XSSFRichTextString) row.getCell(3).getRichStringCellValue(); - assertEquals(3, rt.numFormattingRuns()); - assertNull(rt.getFontOfFormattingRun(0)); - assertEquals(1, rt.getLengthOfFormattingRun(0)); - - assertNotNull(rt.getFontOfFormattingRun(1)); - assertEquals(3, rt.getLengthOfFormattingRun(1)); - - assertNotNull(rt.getFontOfFormattingRun(2)); - assertEquals(9, rt.getLengthOfFormattingRun(2)); - } - } - - @Test - void testToString() { - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - assertNotNull(rt.toString()); - - rt = new XSSFRichTextString(); - assertEquals("", rt.toString()); - } - - @Test - void test59008Font() { - XSSFFont font = new XSSFFont(CTFont.Factory.newInstance()); - - XSSFRichTextString rts = new XSSFRichTextString(); - rts.append("This is correct "); - int s1 = rts.length(); - rts.append("This is Bold Red", font); - int s2 = rts.length(); - rts.append(" This uses the default font rather than the cell style font"); - int s3 = rts.length(); - - assertEquals("<xml-fragment/>", rts.getFontAtIndex(s1-1).toString()); - assertEquals(font, rts.getFontAtIndex(s2-1)); - assertEquals("<xml-fragment/>", rts.getFontAtIndex(s3-1).toString()); - } - - @Test - void test60289UtfDecode() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("60289.xlsx"); - assertEquals("Rich Text\r\nTest", wb.getSheetAt(0).getRow(1).getCell(1).getRichStringCellValue().getString()); - wb.close(); - } - - @Test - void testUtfDecode_withApplyFont() { - XSSFFont font = new XSSFFont(); - font.setBold(true); - font.setFontHeightInPoints((short) 14); - - CTRst st = CTRst.Factory.newInstance(); - st.setT("abc_x000D_2ef_x000D_"); - XSSFRichTextString rt = new XSSFRichTextString(st); - rt.applyFont(font); - assertEquals("abc\r2ef\r", rt.getString()); - } - - @Test - void testUtfLength() { - assertEquals(0, XSSFRichTextString.utfLength(null)); - assertEquals(0, XSSFRichTextString.utfLength("")); - - assertEquals(3, XSSFRichTextString.utfLength("abc")); - assertEquals(3, XSSFRichTextString.utfLength("ab_x0032_")); - assertEquals(3, XSSFRichTextString.utfLength("a_x0032__x0032_")); - assertEquals(3, XSSFRichTextString.utfLength("_x0032_a_x0032_")); - assertEquals(3, XSSFRichTextString.utfLength("_x0032__x0032_a")); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java deleted file mode 100644 index 4e6899dfc2..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java +++ /dev/null @@ -1,234 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.assertSame; - -import java.io.IOException; - -import org.apache.poi.ss.tests.usermodel.BaseTestXRow; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellCopyPolicy; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * Tests for XSSFRow - */ -public final class TestXSSFRow extends BaseTestXRow { - - public TestXSSFRow() { - super(XSSFITestDataProvider.instance); - } - - @Test - void testCopyRowFrom() throws IOException { - final XSSFWorkbook workbook = new XSSFWorkbook(); - final XSSFSheet sheet = workbook.createSheet("test"); - final XSSFRow srcRow = sheet.createRow(0); - srcRow.createCell(0).setCellValue("Hello"); - final XSSFRow destRow = sheet.createRow(1); - - destRow.copyRowFrom(srcRow, new CellCopyPolicy()); - assertNotNull(destRow.getCell(0)); - assertEquals("Hello", destRow.getCell(0).getStringCellValue()); - - workbook.close(); - } - - @Test - void testCopyRowFromExternalSheet() throws IOException { - final XSSFWorkbook workbook = new XSSFWorkbook(); - final Sheet srcSheet = workbook.createSheet("src"); - final XSSFSheet destSheet = workbook.createSheet("dest"); - workbook.createSheet("other"); - - final Row srcRow = srcSheet.createRow(0); - int col = 0; - //Test 2D and 3D Ref Ptgs (Pxg for OOXML Workbooks) - srcRow.createCell(col++).setCellFormula("B5"); - srcRow.createCell(col++).setCellFormula("src!B5"); - srcRow.createCell(col++).setCellFormula("dest!B5"); - srcRow.createCell(col++).setCellFormula("other!B5"); - - //Test 2D and 3D Ref Ptgs with absolute row - srcRow.createCell(col++).setCellFormula("B$5"); - srcRow.createCell(col++).setCellFormula("src!B$5"); - srcRow.createCell(col++).setCellFormula("dest!B$5"); - srcRow.createCell(col++).setCellFormula("other!B$5"); - - //Test 2D and 3D Area Ptgs (Pxg for OOXML Workbooks) - srcRow.createCell(col++).setCellFormula("SUM(B5:D$5)"); - srcRow.createCell(col++).setCellFormula("SUM(src!B5:D$5)"); - srcRow.createCell(col++).setCellFormula("SUM(dest!B5:D$5)"); - srcRow.createCell(col++).setCellFormula("SUM(other!B5:D$5)"); - - ////////////////// - - final XSSFRow destRow = destSheet.createRow(1); - destRow.copyRowFrom(srcRow, new CellCopyPolicy()); - - ////////////////// - - //Test 2D and 3D Ref Ptgs (Pxg for OOXML Workbooks) - col = 0; - Cell cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("B6", cell.getCellFormula(), "RefPtg"); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("src!B6", cell.getCellFormula(), "Ref3DPtg"); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("dest!B6", cell.getCellFormula(), "Ref3DPtg"); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("other!B6", cell.getCellFormula(), "Ref3DPtg"); - - ///////////////////////////////////////////// - - //Test 2D and 3D Ref Ptgs with absolute row (Ptg row number shouldn't change) - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("B$5", cell.getCellFormula(), "RefPtg"); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("src!B$5", cell.getCellFormula(), "Ref3DPtg"); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("dest!B$5", cell.getCellFormula(), "Ref3DPtg"); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("other!B$5", cell.getCellFormula(), "Ref3DPtg"); - - ////////////////////////////////////////// - - //Test 2D and 3D Area Ptgs (Pxg for OOXML Workbooks) - // Note: absolute row changes from last cell to first cell in order - // to maintain topLeft:bottomRight order - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("SUM(B$5:D6)", cell.getCellFormula(), "Area2DPtg"); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("SUM(src!B$5:D6)", cell.getCellFormula(), "Area3DPtg"); - - cell = destRow.getCell(col++); - assertNotNull(destRow.getCell(6)); - assertEquals("SUM(dest!B$5:D6)", cell.getCellFormula(), "Area3DPtg"); - - cell = destRow.getCell(col++); - assertNotNull(destRow.getCell(7)); - assertEquals("SUM(other!B$5:D6)", cell.getCellFormula(), "Area3DPtg"); - - workbook.close(); - } - - @Test - void testCopyRowOverwritesExistingRow() throws IOException { - final XSSFWorkbook workbook = new XSSFWorkbook(); - final XSSFSheet sheet1 = workbook.createSheet("Sheet1"); - final Sheet sheet2 = workbook.createSheet("Sheet2"); - - final Row srcRow = sheet1.createRow(0); - final XSSFRow destRow = sheet1.createRow(1); - final Row observerRow = sheet1.createRow(2); - final Row externObserverRow = sheet2.createRow(0); - - srcRow.createCell(0).setCellValue("hello"); - srcRow.createCell(1).setCellValue("world"); - destRow.createCell(0).setCellValue(5.0); //A2 -> 5.0 - destRow.createCell(1).setCellFormula("A1"); // B2 -> A1 -> "hello" - observerRow.createCell(0).setCellFormula("A2"); // A3 -> A2 -> 5.0 - observerRow.createCell(1).setCellFormula("B2"); // B3 -> B2 -> A1 -> "hello" - externObserverRow.createCell(0).setCellFormula("Sheet1!A2"); //Sheet2!A1 -> Sheet1!A2 -> 5.0 - - // overwrite existing destRow with row-copy of srcRow - destRow.copyRowFrom(srcRow, new CellCopyPolicy()); - - // copyRowFrom should update existing destRow, rather than creating a new row and reassigning the destRow pointer - // to the new row (and allow the old row to be garbage collected) - // this is mostly so existing references to rows that are overwritten are updated - // rather than allowing users to continue updating rows that are no longer part of the sheet - assertSame(srcRow, sheet1.getRow(0), "existing references to srcRow are still valid"); - assertSame(destRow, sheet1.getRow(1), "existing references to destRow are still valid"); - assertSame(observerRow, sheet1.getRow(2), "existing references to observerRow are still valid"); - assertSame(externObserverRow, sheet2.getRow(0), "existing references to externObserverRow are still valid"); - - // Make sure copyRowFrom actually copied row (this is tested elsewhere) - assertEquals(CellType.STRING, destRow.getCell(0).getCellType()); - assertEquals("hello", destRow.getCell(0).getStringCellValue()); - - // We don't want #REF! errors if we copy a row that contains cells that are referred to by other cells outside of copied region - assertEquals("A2", observerRow.getCell(0).getCellFormula(), "references to overwritten cells are unmodified"); - assertEquals("B2", observerRow.getCell(1).getCellFormula(), "references to overwritten cells are unmodified"); - assertEquals("Sheet1!A2", externObserverRow.getCell(0).getCellFormula(), "references to overwritten cells are unmodified"); - - workbook.close(); - } - - @Test - void testMultipleEditWriteCycles() { - final XSSFWorkbook wb1 = new XSSFWorkbook(); - final XSSFSheet sheet1 = wb1.createSheet("Sheet1"); - XSSFRow srcRow = sheet1.createRow(0); - srcRow.createCell(0).setCellValue("hello"); - srcRow.createCell(3).setCellValue("world"); - - // discard result - XSSFTestDataSamples.writeOutAndReadBack(wb1); - - assertEquals("hello", srcRow.getCell(0).getStringCellValue()); - assertEquals("hello", - wb1.getSheet("Sheet1").getRow(0).getCell(0).getStringCellValue()); - assertEquals("world", srcRow.getCell(3).getStringCellValue()); - assertEquals("world", - wb1.getSheet("Sheet1").getRow(0).getCell(3).getStringCellValue()); - - srcRow.createCell(1).setCellValue("cruel"); - - // discard result - XSSFTestDataSamples.writeOutAndReadBack(wb1); - - assertEquals("hello", srcRow.getCell(0).getStringCellValue()); - assertEquals("hello", wb1.getSheet("Sheet1").getRow(0).getCell(0).getStringCellValue()); - assertEquals("cruel", srcRow.getCell(1).getStringCellValue()); - assertEquals("cruel", wb1.getSheet("Sheet1").getRow(0).getCell(1).getStringCellValue()); - assertEquals("world", srcRow.getCell(3).getStringCellValue()); - assertEquals("world", wb1.getSheet("Sheet1").getRow(0).getCell(3).getStringCellValue()); - - srcRow.getCell(1).setCellValue((RichTextString) null); - - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals(CellType.BLANK, wb3.getSheet("Sheet1").getRow(0).getCell(1).getCellType(), "Cell should be blank"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFShape.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFShape.java deleted file mode 100644 index 67486d6f64..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFShape.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * Tests for XSSFShape - */ -public final class TestXSSFShape { - - @Test - void test58325_one() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("58325_lt.xlsx")) { - check58325(wb, 1); - } - } - - @Test - void test58325_three() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("58325_db.xlsx")) { - check58325(wb, 3); - } - } - - private void check58325(XSSFWorkbook wb, int expectedShapes) { - XSSFSheet sheet = wb.getSheet("MetasNM001"); - assertNotNull(sheet); - - StringBuilder str = new StringBuilder(); - str.append("sheet ").append(sheet.getSheetName()).append(" - "); - - XSSFDrawing drawing = sheet.getDrawingPatriarch(); - //drawing = ((XSSFSheet)sheet).createDrawingPatriarch(); - - List<XSSFShape> shapes = drawing.getShapes(); - str.append("drawing.getShapes().size() = ").append(shapes.size()); - for (XSSFShape shape : shapes) { - str.append(", ").append(shape); - str.append(", Col1:").append(((XSSFClientAnchor) shape.getAnchor()).getCol1()); - str.append(", Col2:").append(((XSSFClientAnchor) shape.getAnchor()).getCol2()); - str.append(", Row1:").append(((XSSFClientAnchor) shape.getAnchor()).getRow1()); - str.append(", Row2:").append(((XSSFClientAnchor) shape.getAnchor()).getRow2()); - } - - assertEquals(expectedShapes, shapes.size(), "Having shapes: " + str); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java deleted file mode 100644 index 1ca51d3dcc..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java +++ /dev/null @@ -1,2023 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook; -import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack; -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.assertNotSame; -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; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ooxml.POIXMLException; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.ss.tests.usermodel.BaseTestXSheet; -import org.apache.poi.ss.usermodel.AutoFilter; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellCopyPolicy; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.IgnoredErrorType; -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.util.AreaReference; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.ss.util.CellUtil; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.CalculationChain; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.model.StylesTable; -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.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComments; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTIgnoredError; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetProtection; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCalcMode; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPane; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STUnsignedShortHex; - - -public final class TestXSSFSheet extends BaseTestXSheet { - public TestXSSFSheet() { - super(XSSFITestDataProvider.instance); - } - - //TODO column styles are not yet supported by XSSF - @Override - protected void defaultColumnStyle() { - //super.defaultColumnStyle(); - } - - @Test - void existingHeaderFooter() throws IOException { - try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("45540_classic_Header.xlsx")) { - XSSFOddHeader hdr; - XSSFOddFooter ftr; - - // Sheet 1 has a header with center and right text - XSSFSheet s1 = wb1.getSheetAt(0); - assertNotNull(s1.getHeader()); - assertNotNull(s1.getFooter()); - hdr = (XSSFOddHeader) s1.getHeader(); - ftr = (XSSFOddFooter) s1.getFooter(); - - assertEquals("&Ctestdoc&Rtest phrase", hdr.getText()); - assertNull(ftr.getText()); - - assertEquals("", hdr.getLeft()); - assertEquals("testdoc", hdr.getCenter()); - assertEquals("test phrase", hdr.getRight()); - - assertEquals("", ftr.getLeft()); - assertEquals("", ftr.getCenter()); - assertEquals("", ftr.getRight()); - - // Sheet 2 has a footer, but it's empty - XSSFSheet s2 = wb1.getSheetAt(1); - assertNotNull(s2.getHeader()); - assertNotNull(s2.getFooter()); - hdr = (XSSFOddHeader) s2.getHeader(); - ftr = (XSSFOddFooter) s2.getFooter(); - - assertNull(hdr.getText()); - assertEquals("&L&F", ftr.getText()); - - assertEquals("", hdr.getLeft()); - assertEquals("", hdr.getCenter()); - assertEquals("", hdr.getRight()); - - assertEquals("&F", ftr.getLeft()); - assertEquals("", ftr.getCenter()); - assertEquals("", ftr.getRight()); - - // Save and reload - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { - hdr = (XSSFOddHeader) wb2.getSheetAt(0).getHeader(); - ftr = (XSSFOddFooter) wb2.getSheetAt(0).getFooter(); - - assertEquals("", hdr.getLeft()); - assertEquals("testdoc", hdr.getCenter()); - assertEquals("test phrase", hdr.getRight()); - - assertEquals("", ftr.getLeft()); - assertEquals("", ftr.getCenter()); - assertEquals("", ftr.getRight()); - } - } - } - - @Test - void getAllHeadersFooters() throws IOException { - try (XSSFWorkbook workbook = new XSSFWorkbook()) { - XSSFSheet sheet = workbook.createSheet("Sheet 1"); - assertNotNull(sheet.getOddFooter()); - assertNotNull(sheet.getEvenFooter()); - assertNotNull(sheet.getFirstFooter()); - assertNotNull(sheet.getOddHeader()); - assertNotNull(sheet.getEvenHeader()); - assertNotNull(sheet.getFirstHeader()); - - assertEquals("", sheet.getOddFooter().getLeft()); - sheet.getOddFooter().setLeft("odd footer left"); - assertEquals("odd footer left", sheet.getOddFooter().getLeft()); - - assertEquals("", sheet.getEvenFooter().getLeft()); - sheet.getEvenFooter().setLeft("even footer left"); - assertEquals("even footer left", sheet.getEvenFooter().getLeft()); - - assertEquals("", sheet.getFirstFooter().getLeft()); - sheet.getFirstFooter().setLeft("first footer left"); - assertEquals("first footer left", sheet.getFirstFooter().getLeft()); - - assertEquals("", sheet.getOddHeader().getLeft()); - sheet.getOddHeader().setLeft("odd header left"); - assertEquals("odd header left", sheet.getOddHeader().getLeft()); - - assertEquals("", sheet.getOddHeader().getRight()); - sheet.getOddHeader().setRight("odd header right"); - assertEquals("odd header right", sheet.getOddHeader().getRight()); - - assertEquals("", sheet.getOddHeader().getCenter()); - sheet.getOddHeader().setCenter("odd header center"); - assertEquals("odd header center", sheet.getOddHeader().getCenter()); - - // Defaults are odd - assertEquals("odd footer left", sheet.getFooter().getLeft()); - assertEquals("odd header center", sheet.getHeader().getCenter()); - } - } - - @Test - void autoSizeColumn() throws IOException { - try (XSSFWorkbook workbook = new XSSFWorkbook()) { - XSSFSheet sheet = workbook.createSheet("Sheet 1"); - sheet.createRow(0).createCell(13).setCellValue("test"); - - sheet.autoSizeColumn(13); - - ColumnHelper columnHelper = sheet.getColumnHelper(); - CTCol col = columnHelper.getColumn(13, false); - assertTrue(col.getBestFit()); - } - } - - - @Test - void setCellComment() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - - 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.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(); - } - - @Test - void getActiveCell() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CellAddress R5 = new CellAddress("R5"); - sheet.setActiveCell(R5); - - assertEquals(R5, sheet.getActiveCell()); - workbook.close(); - } - - @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); - assertEquals(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); - assertEquals(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane()); - - workbook.close(); - } - - @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(); - } - - @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(); - } - - - @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(); - } - - @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(); - - 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()); - - assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); - - workbook.close(); - } - - @Test - void setZoom() throws IOException { - try (XSSFWorkbook workBook = new XSSFWorkbook()) { - XSSFSheet sheet1 = workBook.createSheet("new sheet"); - sheet1.setZoom(75); // 75 percent magnification - long zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale(); - assertEquals(zoom, 75); - - sheet1.setZoom(200); - zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale(); - assertEquals(zoom, 200); - - // Valid scale values range from 10 to 400 - assertThrows(IllegalArgumentException.class, () -> sheet1.setZoom(500)); - } - } - - /** - * TODO - while this is internally consistent, I'm not - * completely clear in all cases what it's supposed to - * be doing... Someone who understands the goals a little - * better should really review this! - */ - @Test - void setColumnGroupCollapsed() throws IOException { - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - XSSFSheet sheet1 = wb1.createSheet(); - - CTCols cols = sheet1.getCTWorksheet().getColsArray(0); - assertEquals(0, cols.sizeOfColArray()); - - sheet1.groupColumn(4, 7); - - assertEquals(1, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - - sheet1.groupColumn(9, 12); - - assertEquals(2, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 9, 12); // false, true - - sheet1.groupColumn(10, 11); - - assertEquals(4, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 9, 9); // false, true - checkColumnGroup(cols.getColArray(2), 10, 11); // false, true - checkColumnGroup(cols.getColArray(3), 12, 12); // false, true - - // collapse columns - 1 - sheet1.setColumnGroupCollapsed(5, true); - - // FIXME: we grew a column? - assertEquals(5, cols.sizeOfColArray()); - checkColumnGroupIsCollapsed(cols.getColArray(0), 4, 7); // true, true - checkColumnGroup(cols.getColArray(1), 8, 8); // false, true - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroup(cols.getColArray(3), 10, 11); // false, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - - - // expand columns - 1 - sheet1.setColumnGroupCollapsed(5, false); - assertEquals(5, cols.sizeOfColArray()); - - checkColumnGroupIsExpanded(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroup(cols.getColArray(3), 10, 11); // false, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - - - //collapse - 2 - sheet1.setColumnGroupCollapsed(9, true); - // it grew again? - assertEquals(6, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroupIsCollapsed(cols.getColArray(2), 9, 9); // true, true - checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true - checkColumnGroupIsCollapsed(cols.getColArray(4), 12, 12); // true, true - // why was this column group added? - checkColumnGroup(cols.getColArray(5), 13, 13); // false, true - - - //expand - 2 - sheet1.setColumnGroupCollapsed(9, false); - assertEquals(6, cols.sizeOfColArray()); - - //outline level 2: the line under ==> collapsed==True - assertEquals(2, cols.getColArray(3).getOutlineLevel()); - assertTrue(cols.getColArray(4).isSetCollapsed()); - - checkColumnGroup(cols.getColArray(0), 4, 7); - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - checkColumnGroup(cols.getColArray(5), 13, 13, false, false); - - //DOCUMENTARE MEGLIO IL DISCORSO DEL LIVELLO - //collapse - 3 - sheet1.setColumnGroupCollapsed(10, true); - assertEquals(6, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - checkColumnGroup(cols.getColArray(5), 13, 13, false, false); - - - //expand - 3 - sheet1.setColumnGroupCollapsed(10, false); - assertEquals(6, cols.sizeOfColArray()); - assertFalse(cols.getColArray(0).getHidden()); - assertFalse(cols.getColArray(5).getHidden()); - assertFalse(cols.getColArray(4).isSetCollapsed()); - - // write out and give back - // Save and re-load - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { - sheet1 = wb2.getSheetAt(0); - cols = sheet1.getCTWorksheet().getColsArray(0); - - assertEquals(6, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7, false, true); - checkColumnGroup(cols.getColArray(1), 8, 8, false, true); - checkColumnGroup(cols.getColArray(2), 9, 9, false, true); - checkColumnGroup(cols.getColArray(3), 10, 11, false, true); - checkColumnGroup(cols.getColArray(4), 12, 12, false, true); - checkColumnGroup(cols.getColArray(5), 13, 13, false, true); - } - } - } - - /** - * Verify that column groups were created correctly after Sheet.groupColumn - * - * @param col the column group xml bean - * @param fromColumnIndex 0-indexed - * @param toColumnIndex 0-indexed - */ - @SuppressWarnings("SameParameterValue") - private static void checkColumnGroup( - CTCol col, - int fromColumnIndex, int toColumnIndex, - boolean isSetHidden, boolean isSetCollapsed - ) { - assertEquals(fromColumnIndex, col.getMin() - 1, "from column index"); // 1 based - assertEquals(toColumnIndex, col.getMax() - 1, "to column index"); // 1 based - assertEquals(isSetHidden, col.isSetHidden(), "isSetHidden"); - assertEquals(isSetCollapsed, col.isSetCollapsed(), "isSetCollapsed"); //not necessarily set - } - - /** - * Verify that column groups were created correctly after Sheet.groupColumn - * - * @param col the column group xml bean - * @param fromColumnIndex 0-indexed - * @param toColumnIndex 0-indexed - */ - private static void checkColumnGroup(CTCol col, int fromColumnIndex, int toColumnIndex) { - assertEquals(fromColumnIndex, col.getMin() - 1, "from column index"); // 1 based - assertEquals(toColumnIndex, col.getMax() - 1, "to column index"); // 1 based - assertFalse(col.isSetHidden(), "isSetHidden"); - assertTrue(col.isSetCollapsed(), "isSetCollapsed"); //not necessarily set - } - - /** - * Verify that column groups were created correctly after Sheet.groupColumn - * - * @param col the column group xml bean - * @param fromColumnIndex 0-indexed - * @param toColumnIndex 0-indexed - */ - private static void checkColumnGroupIsCollapsed(CTCol col, int fromColumnIndex, int toColumnIndex) { - assertEquals(fromColumnIndex, col.getMin() - 1, "from column index"); // 1 based - assertEquals(toColumnIndex, col.getMax() - 1, "to column index"); // 1 based - assertTrue(col.isSetHidden(), "isSetHidden"); - assertTrue(col.isSetCollapsed(), "isSetCollapsed"); - //assertTrue(col.getCollapsed(), "getCollapsed"); - } - - /** - * Verify that column groups were created correctly after Sheet.groupColumn - * - * @param col the column group xml bean - * @param fromColumnIndex 0-indexed - * @param toColumnIndex 0-indexed - */ - @SuppressWarnings("SameParameterValue") - private static void checkColumnGroupIsExpanded(CTCol col, int fromColumnIndex, int toColumnIndex) { - assertEquals(fromColumnIndex, col.getMin() - 1, "from column index"); // 1 based - assertEquals(toColumnIndex, col.getMax() - 1, "to column index"); // 1 based - assertFalse(col.isSetHidden(), "isSetHidden"); - assertTrue(col.isSetCollapsed(), "isSetCollapsed"); - //assertTrue(!col.isSetCollapsed() || !col.getCollapsed(), "isSetCollapsed"); - //assertFalse(col.getCollapsed(), "getCollapsed"); - } - - /** - * TODO - while this is internally consistent, I'm not - * completely clear in all cases what it's supposed to - * be doing... Someone who understands the goals a little - * better should really review this! - */ - @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(); - } - - /** - * Get / Set column width and check the actual values of the underlying XML beans - */ - @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(); - } - - /** - * Setting width of a column included in a column span - */ - @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)); - } - - 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); - } - - //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); - } - - wb2.close(); - } - - /** - * Hiding a column included in a column span - */ - @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(); - } - - @Test - void commentsTable() throws IOException { - 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()); - - assertSame(comment1, sheet1.getCommentsTable(true)); - - //second sheet - XSSFSheet sheet2 = wb1.createSheet(); - CommentsTable comment2 = sheet2.getCommentsTable(false); - assertNull(comment2); - - comment2 = sheet2.getCommentsTable(true); - assertNotNull(comment2); - - assertSame(comment2, sheet2.getCommentsTable(true)); - assertEquals("/xl/comments2.xml", comment2.getPackagePart().getPartName().getName()); - - //comment1 and comment2 are different objects - assertNotSame(comment1, comment2); - wb1.close(); - - //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(); - } - - /** - * Rows and cells can be created in random order, - * but CTRows are kept in ascending order - */ - @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(); - } - - @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()); - - // auto-filter must be registered in workboook.xml, see Bugzilla 50315 - XSSFName nm = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); - assertNotNull(nm); - - 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()); - - wb.close(); - } - - @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(); - } - - @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(); - } - - @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(); - } - - - @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(); - } - - /** - * See bug #50829 test data tables - */ - @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(); - } - - /** - * Test to trigger OOXML-LITE generating to include org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetCalcPr - */ - @Test - void setForceFormulaRecalculation() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("Sheet 1"); - - assertFalse(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); - assertEquals(STCalcMode.AUTO, calcPr.getCalcMode()); - - // 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(); - } - - @Test - void bug54607() throws IOException { - // run with the file provided in the Bug-Report - runGetTopRow("54607.xlsx", true, 1, 0, 0); - runGetLeftCol("54607.xlsx", true, 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); - } - swb.close(); - } - - wb.close(); - } - - 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); - } - swb.close(); - } - - wb.close(); - } - - @Test - void bug55745() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55745.xlsx")) { - XSSFSheet sheet = wb.getSheetAt(0); - List<XSSFTable> tables = sheet.getTables(); - assertEquals(8, tables.size(), "Sheet should contain 8 tables"); - assertNotNull(sheet.getCommentsTable(false), "Sheet should contain a comments table"); - } - } - - @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)); - - CellRangeAddress range = CellRangeAddress.valueOf("A:B"); - AutoFilter 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()); - - range = CellRangeAddress.valueOf("B:C"); - filter = sheet.setAutoFilter(range); - assertNotNull(filter); - - // stored with a special name - name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); - assertNotNull(name); - assertEquals("Sheet0!$B:$C", name.getRefersToFormula()); - - wb.close(); - } - - @Timeout(value = 180, unit = SECONDS) - @Test - void bug51585() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51585.xlsx")) { - assertNotNull(wb.getSheetAt(0)); - } - } - - private XSSFWorkbook setupSheet(){ - //set up workbook - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - - Row row1 = sheet.createRow(0); - Cell cell = row1.createCell(0); - cell.setCellValue("Names"); - Cell cell2 = row1.createCell(1); - cell2.setCellValue("#"); - - Row row2 = sheet.createRow(1); - Cell cell3 = row2.createCell(0); - cell3.setCellValue("Jane"); - Cell cell4 = row2.createCell(1); - cell4.setCellValue(3); - - Row row3 = sheet.createRow(2); - Cell cell5 = row3.createCell(0); - cell5.setCellValue("John"); - Cell cell6 = row3.createCell(1); - cell6.setCellValue(3); - - return wb; - } - - @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(); - } - - @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(); - } - - @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(); - } - - @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(); - } - - @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(); - } - - @Test - void testCreatePivotTableWithConflictingDataSheets() throws IOException { - try (XSSFWorkbook wb = setupSheet()) { - XSSFSheet sheet = wb.getSheetAt(0); - XSSFSheet sheet2 = wb.createSheet("TEST"); - CellReference cr = new CellReference("H5"); - AreaReference ar = wb.getCreationHelper().createAreaReference(sheet.getSheetName() + "!A$1:B$2"); - - assertThrows(IllegalArgumentException.class, () -> sheet2.createPivotTable(ar, cr, sheet2)); - } - } - - @Test - void testReadFails() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - // Throws exception because we cannot read here - assertThrows(POIXMLException.class, sheet::onDocumentRead); - } - } - - /** - * This would be better off as a testable example rather than a simple unit test - * since Sheet.createComment() was deprecated and removed. - * https://poi.apache.org/spreadsheet/quick-guide.html#CellComments - * Feel free to relocated or delete this unit test if it doesn't belong here. - */ - @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(); - } - - private void testCopyOneRow(String copyRowsTestWorkbook) throws IOException { - final double FLOAT_PRECISION = 1e-9; - final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook); - final XSSFSheet sheet = wb.getSheetAt(0); - final CellCopyPolicy defaultCopyPolicy = new CellCopyPolicy(); - sheet.copyRows(1, 1, 6, defaultCopyPolicy); - - final Row srcRow = sheet.getRow(1); - final Row destRow = sheet.getRow(6); - int col = 0; - Cell cell; - - cell = CellUtil.getCell(destRow, col++); - assertEquals("Source row ->", cell.getStringCellValue()); - - // Style - cell = CellUtil.getCell(destRow, col++); - assertEquals("Red", cell.getStringCellValue(), "[Style] B7 cell value"); - assertEquals(CellUtil.getCell(srcRow, 1).getCellStyle(), cell.getCellStyle(), "[Style] B7 cell style"); - - // Blank - cell = CellUtil.getCell(destRow, col++); - assertEquals(CellType.BLANK, cell.getCellType(), "[Blank] C7 cell type"); - - // Error - cell = CellUtil.getCell(destRow, col++); - assertEquals(CellType.ERROR, cell.getCellType(), "[Error] D7 cell type"); - final FormulaError error = FormulaError.forInt(cell.getErrorCellValue()); - //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here - assertEquals(FormulaError.NA, error, "[Error] D7 cell value"); - - // Date - cell = CellUtil.getCell(destRow, col++); - assertEquals(CellType.NUMERIC, cell.getCellType(), "[Date] E7 cell type"); - final Date date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 1).getTime(); - assertEquals(date, cell.getDateCellValue(), "[Date] E7 cell value"); - - // Boolean - cell = CellUtil.getCell(destRow, col++); - assertEquals(CellType.BOOLEAN, cell.getCellType(), "[Boolean] F7 cell type"); - assertTrue(cell.getBooleanCellValue(), "[Boolean] F7 cell value"); - - // String - cell = CellUtil.getCell(destRow, col++); - assertEquals(CellType.STRING, cell.getCellType(), "[String] G7 cell type"); - assertEquals("Hello", cell.getStringCellValue(), "[String] G7 cell value"); - - // Int - cell = CellUtil.getCell(destRow, col++); - assertEquals(CellType.NUMERIC, cell.getCellType(), "[Int] H7 cell type"); - assertEquals(15, (int) cell.getNumericCellValue(), "[Int] H7 cell value"); - - // Float - cell = CellUtil.getCell(destRow, col++); - assertEquals(CellType.NUMERIC, cell.getCellType(), "[Float] I7 cell type"); - assertEquals(12.5, cell.getNumericCellValue(), FLOAT_PRECISION, "[Float] I7 cell value"); - - // Cell Formula - cell = CellUtil.getCell(destRow, col++); - assertEquals("Sheet1!J7", new CellReference(cell).formatAsString()); - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula] J7 cell type"); - assertEquals("5+2", cell.getCellFormula(), "[Cell Formula] J7 cell formula"); - //System.out.println("Cell formula evaluation currently unsupported"); - - // Cell Formula with Reference - // Formula row references should be adjusted by destRowNum-srcRowNum - cell = CellUtil.getCell(destRow, col++); - assertEquals("Sheet1!K7", new CellReference(cell).formatAsString()); - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference] K7 cell type"); - assertEquals("J7+H$2", cell.getCellFormula(), "[Cell Formula with Reference] K7 cell formula"); - - // Cell Formula with Reference spanning multiple rows - cell = CellUtil.getCell(destRow, col++); - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference spanning multiple rows] L7 cell type"); - assertEquals("G7&\" \"&G8", cell.getCellFormula(), "[Cell Formula with Reference spanning multiple rows] L7 cell formula"); - - // Cell Formula with Reference spanning multiple rows - cell = CellUtil.getCell(destRow, col++); - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Area Reference] M7 cell type"); - assertEquals("SUM(H7:I8)", cell.getCellFormula(), "[Cell Formula with Area Reference] M7 cell formula"); - - // Array Formula - cell = CellUtil.getCell(destRow, col++); - //System.out.println("Array formulas currently unsupported"); - // FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula() - /* - assertEquals(CellType.FORMULA, cell.getCellType(), "[Array Formula] N7 cell type"); - assertEquals("{SUM(H7:J7*{1,2,3})}", cell.getCellFormula(), "[Array Formula] N7 cell formula"); - */ - - // Data Format - cell = CellUtil.getCell(destRow, col++); - assertEquals(CellType.NUMERIC, cell.getCellType(), "[Data Format] O7 cell type"); - assertEquals(100.20, cell.getNumericCellValue(), FLOAT_PRECISION, "[Data Format] O7 cell value"); - //FIXME: currently fails - final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)"; - assertEquals(moneyFormat, cell.getCellStyle().getDataFormatString(), "[Data Format] O7 data format"); - - // Merged - cell = CellUtil.getCell(destRow, col); - assertEquals("Merged cells", cell.getStringCellValue(), "[Merged] P7:Q7 cell value"); - assertTrue(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P7:Q7")), "[Merged] P7:Q7 merged region"); - - // Merged across multiple rows - // Microsoft Excel 2013 does not copy a merged region unless all rows of - // the source merged region are selected - // POI's behavior should match this behavior - col += 2; - cell = CellUtil.getCell(destRow, col); - // Note: this behavior deviates from Microsoft Excel, - // which will not overwrite a cell in destination row if merged region extends beyond the copied row. - // The Excel way would require: - //assertEquals("[Merged across multiple rows] R7:S8 merged region", "Should NOT be overwritten", cell.getStringCellValue()); - //assertFalse("[Merged across multiple rows] R7:S8 merged region", - // sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S8"))); - // As currently implemented, cell value is copied but merged region is not copied - assertEquals("Merged cells across multiple rows", cell.getStringCellValue(), "[Merged across multiple rows] R7:S8 cell value"); - // shouldn't do 1-row merge - assertFalse(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S7")), "[Merged across multiple rows] R7:S7 merged region (one row)"); - //shouldn't do 2-row merge - assertFalse(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S8")), "[Merged across multiple rows] R7:S8 merged region"); - - // Make sure other rows are blank (off-by-one errors) - assertNull(sheet.getRow(5)); - assertNull(sheet.getRow(7)); - - wb.close(); - } - - private void testCopyMultipleRows(String copyRowsTestWorkbook) throws IOException { - final double FLOAT_PRECISION = 1e-9; - final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook); - final XSSFSheet sheet = wb.getSheetAt(0); - final CellCopyPolicy defaultCopyPolicy = new CellCopyPolicy(); - sheet.copyRows(0, 3, 8, defaultCopyPolicy); - - sheet.getRow(0); - final Row srcRow1 = sheet.getRow(1); - final Row srcRow2 = sheet.getRow(2); - final Row srcRow3 = sheet.getRow(3); - final Row destHeaderRow = sheet.getRow(8); - final Row destRow1 = sheet.getRow(9); - final Row destRow2 = sheet.getRow(10); - final Row destRow3 = sheet.getRow(11); - int col = 0; - Cell cell; - - // Header row should be copied - assertNotNull(destHeaderRow); - - // Data rows - cell = CellUtil.getCell(destRow1, col); - assertEquals("Source row ->", cell.getStringCellValue()); - - // Style - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("Red", cell.getStringCellValue(), "[Style] B10 cell value"); - assertEquals(CellUtil.getCell(srcRow1, 1).getCellStyle(), cell.getCellStyle(), "[Style] B10 cell style"); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("Blue", cell.getStringCellValue(), "[Style] B11 cell value"); - assertEquals(CellUtil.getCell(srcRow2, 1).getCellStyle(), cell.getCellStyle(), "[Style] B11 cell style"); - - // Blank - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals(CellType.BLANK, cell.getCellType(), "[Blank] C10 cell type"); - - cell = CellUtil.getCell(destRow2, col); - assertEquals(CellType.BLANK, cell.getCellType(), "[Blank] C11 cell type"); - - // Error - col++; - cell = CellUtil.getCell(destRow1, col); - FormulaError error = FormulaError.forInt(cell.getErrorCellValue()); - //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here - assertEquals(CellType.ERROR, cell.getCellType(), "[Error] D10 cell type"); - assertEquals(FormulaError.NA, error, "[Error] D10 cell value"); - - cell = CellUtil.getCell(destRow2, col); - error = FormulaError.forInt(cell.getErrorCellValue()); - //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here - assertEquals(CellType.ERROR, cell.getCellType(), "[Error] D11 cell type"); - assertEquals(FormulaError.NAME, error, "[Error] D11 cell value"); - - // Date - col++; - cell = CellUtil.getCell(destRow1, col); - Date date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 1).getTime(); - assertEquals(CellType.NUMERIC, cell.getCellType(), "[Date] E10 cell type"); - assertEquals(date, cell.getDateCellValue(), "[Date] E10 cell value"); - - cell = CellUtil.getCell(destRow2, col); - date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 2).getTime(); - assertEquals(CellType.NUMERIC, cell.getCellType(), "[Date] E11 cell type"); - assertEquals(date, cell.getDateCellValue(), "[Date] E11 cell value"); - - // Boolean - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals(CellType.BOOLEAN, cell.getCellType(), "[Boolean] F10 cell type"); - assertTrue(cell.getBooleanCellValue(), "[Boolean] F10 cell value"); - - cell = CellUtil.getCell(destRow2, col); - assertEquals(CellType.BOOLEAN, cell.getCellType(), "[Boolean] F11 cell type"); - assertFalse(cell.getBooleanCellValue(), "[Boolean] F11 cell value"); - - // String - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals(CellType.STRING, cell.getCellType(), "[String] G10 cell type"); - assertEquals("Hello", cell.getStringCellValue(), "[String] G10 cell value"); - - cell = CellUtil.getCell(destRow2, col); - assertEquals(CellType.STRING, cell.getCellType(), "[String] G11 cell type"); - assertEquals("World", cell.getStringCellValue(), "[String] G11 cell value"); - - // Int - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals(CellType.NUMERIC, cell.getCellType(), "[Int] H10 cell type"); - assertEquals(15, (int) cell.getNumericCellValue(), "[Int] H10 cell value"); - - cell = CellUtil.getCell(destRow2, col); - assertEquals(CellType.NUMERIC, cell.getCellType(), "[Int] H11 cell type"); - assertEquals(42, (int) cell.getNumericCellValue(), "[Int] H11 cell value"); - - // Float - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals(CellType.NUMERIC, cell.getCellType(), "[Float] I10 cell type"); - assertEquals(12.5, cell.getNumericCellValue(), FLOAT_PRECISION, "[Float] I10 cell value"); - - cell = CellUtil.getCell(destRow2, col); - assertEquals(CellType.NUMERIC, cell.getCellType(), "[Float] I11 cell type"); - assertEquals(5.5, cell.getNumericCellValue(), FLOAT_PRECISION, "[Float] I11 cell value"); - - // Cell Formula - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula] J10 cell type"); - assertEquals("5+2", cell.getCellFormula(), "[Cell Formula] J10 cell formula"); - - cell = CellUtil.getCell(destRow2, col); - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula] J11 cell type"); - assertEquals("6+18", cell.getCellFormula(), "[Cell Formula] J11 cell formula"); - - // Cell Formula with Reference - col++; - // Formula row references should be adjusted by destRowNum-srcRowNum - cell = CellUtil.getCell(destRow1, col); - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference] K10 cell type"); - assertEquals("J10+H$2", cell.getCellFormula(), "[Cell Formula with Reference] K10 cell formula"); - - cell = CellUtil.getCell(destRow2, col); - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference] K11 cell type"); - assertEquals("J11+H$2", cell.getCellFormula(), "[Cell Formula with Reference] K11 cell formula"); - - // Cell Formula with Reference spanning multiple rows - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference spanning multiple rows] L10 cell type"); - assertEquals("G10&\" \"&G11", cell.getCellFormula(), "[Cell Formula with Reference spanning multiple rows] L10 cell formula"); - - cell = CellUtil.getCell(destRow2, col); - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Reference spanning multiple rows] L11 cell type"); - assertEquals("G11&\" \"&G12", cell.getCellFormula(), "[Cell Formula with Reference spanning multiple rows] L11 cell formula"); - - // Cell Formula with Area Reference - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Area Reference] M10 cell type"); - assertEquals("SUM(H10:I11)", cell.getCellFormula(), "[Cell Formula with Area Reference] M10 cell formula"); - - cell = CellUtil.getCell(destRow2, col); - // Also acceptable: SUM($H10:I$3), but this AreaReference isn't in ascending order - assertEquals(CellType.FORMULA, cell.getCellType(), "[Cell Formula with Area Reference] M11 cell type"); - assertEquals("SUM($H$3:I10)", cell.getCellFormula(), "[Cell Formula with Area Reference] M11 cell formula"); - - // Array Formula - col++; - cell = CellUtil.getCell(destRow1, col); - // System.out.println("Array formulas currently unsupported"); - /* - // FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula() - assertEquals(CellType.FORMULA, cell.getCellType(), "[Array Formula] N10 cell type"); - assertEquals("{SUM(H10:J10*{1,2,3})}", cell.getCellFormula(), "[Array Formula] N10 cell formula"); - - cell = CellUtil.getCell(destRow2, col); - // FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula() - assertEquals(CellType.FORMULA, cell.getCellType(). "[Array Formula] N11 cell type"); - assertEquals("{SUM(H11:J11*{1,2,3})}", cell.getCellFormula(). "[Array Formula] N11 cell formula"); - */ - - // Data Format - col++; - cell = CellUtil.getCell(destRow2, col); - assertEquals(CellType.NUMERIC, cell.getCellType(), "[Data Format] O10 cell type"); - assertEquals(100.20, cell.getNumericCellValue(), FLOAT_PRECISION, "[Data Format] O10 cell value"); - final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)"; - assertEquals(moneyFormat, cell.getCellStyle().getDataFormatString(), "[Data Format] O10 cell data format"); - - // Merged - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("Merged cells", cell.getStringCellValue(), "[Merged] P10:Q10 cell value"); - assertTrue(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P10:Q10")), "[Merged] P10:Q10 merged region"); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("Merged cells", cell.getStringCellValue(), "[Merged] P11:Q11 cell value"); - assertTrue(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P11:Q11")), "[Merged] P11:Q11 merged region"); - - // Should Q10/Q11 be checked? - - // Merged across multiple rows - // Microsoft Excel 2013 does not copy a merged region unless all rows of - // the source merged region are selected - // POI's behavior should match this behavior - col += 2; - cell = CellUtil.getCell(destRow1, col); - assertEquals("Merged cells across multiple rows", cell.getStringCellValue(), "[Merged across multiple rows] R10:S11 cell value"); - assertTrue(sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R10:S11")), "[Merged across multiple rows] R10:S11 merged region"); - - // Row 3 (zero-based) was empty, so Row 11 (zero-based) should be empty too. - if (srcRow3 == null) { - assertNull(destRow3, "Row 3 was empty, so Row 11 should be empty"); - } - - // Make sure other rows are blank (off-by-one errors) - assertNull(sheet.getRow(7), "Off-by-one lower edge case"); //one row above destHeaderRow - assertNull(sheet.getRow(12), "Off-by-one upper edge case"); //one row below destRow3 - - wb.close(); - } - - @Test - void testCopyOneRow() throws IOException { - testCopyOneRow("XSSFSheet.copyRows.xlsx"); - } - - @Test - void testCopyMultipleRows() throws IOException { - testCopyMultipleRows("XSSFSheet.copyRows.xlsx"); - } - - @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(); - } - - @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(); - } - - @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(); - } - - @Test - void setTabColor() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sh = wb.createSheet(); - assertTrue(sh.getCTWorksheet().getSheetPr() == null || !sh.getCTWorksheet().getSheetPr().isSetTabColor()); - sh.setTabColor(new XSSFColor(IndexedColors.RED, null)); - assertTrue(sh.getCTWorksheet().getSheetPr().isSetTabColor()); - assertEquals(IndexedColors.RED.index, - sh.getCTWorksheet().getSheetPr().getTabColor().getIndexed()); - } - } - - @Test - void getTabColor() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sh = wb.createSheet(); - assertTrue(sh.getCTWorksheet().getSheetPr() == null || !sh.getCTWorksheet().getSheetPr().isSetTabColor()); - assertNull(sh.getTabColor()); - sh.setTabColor(new XSSFColor(IndexedColors.RED, null)); - XSSFColor expected = new XSSFColor(IndexedColors.RED, null); - assertEquals(expected, sh.getTabColor()); - } - } - - // Test using an existing workbook saved by Excel - @Test - void tabColor() throws IOException { - try (XSSFWorkbook wb = openSampleWorkbook("SheetTabColors.xlsx")) { - // non-colored sheets do not have a color - assertNull(wb.getSheet("default").getTabColor()); - - // test indexed-colored sheet - XSSFColor expected = new XSSFColor(IndexedColors.RED, null); - assertEquals(expected, wb.getSheet("indexedRed").getTabColor()); - - // test regular-colored (non-indexed, ARGB) sheet - expected = XSSFColor.from(CTColor.Factory.newInstance(), wb.getStylesSource().getIndexedColors()); - assertNotNull(expected); - expected.setARGBHex("FF7F2700"); - assertEquals(expected, wb.getSheet("customOrange").getTabColor()); - } - } - - /** - * See bug #52425 - */ - @Test - void testInsertCommentsToClonedSheet() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("52425.xlsx")) { - CreationHelper helper = wb.getCreationHelper(); - Sheet sheet2 = wb.createSheet("Sheet 2"); - Sheet sheet3 = wb.cloneSheet(0); - wb.setSheetName(2, "Sheet 3"); - - Sheet[] sheets = { sheet2, sheet3 }; - - for (Sheet sheet : sheets) { - Drawing<?> drawing = sheet.createDrawingPatriarch(); - - for (int i = 0; i < 2; i++) { - ClientAnchor anchor = helper.createClientAnchor(); - anchor.setCol1(0); - anchor.setRow1(i); - anchor.setCol2(2); - anchor.setRow2(3 + i); - - Comment comment = drawing.createCellComment(anchor); - comment.setString(helper.createRichTextString("BugTesting")); - - Row row = sheet.getRow(i); - if (row == null) { - row = sheet.createRow(i); - } - Cell cell = row.getCell(0); - if (cell == null) { - cell = row.createCell(0); - } - - cell.setCellComment(comment); - } - } - - for (Sheet sheet : sheets) { - for (int i = 0; i < 2; i++) { - CellAddress ref = new CellAddress(i, 0); - Comment c = sheet.getCellComment(ref); - assertNotNull(c); - assertEquals("BugTesting", c.getString().getString()); - } - } - } - } - - // bug 59687: XSSFSheet.RemoveRow doesn't handle row gaps properly when removing row comments - @Test - void testRemoveRowWithCommentAndGapAbove() throws IOException { - try (Workbook wb = _testDataProvider.openSampleWorkbook("59687.xlsx")) { - final Sheet sheet = wb.getSheetAt(0); - - // comment exists - CellAddress commentCellAddress = new CellAddress("A4"); - assertNotNull(sheet.getCellComment(commentCellAddress)); - - assertEquals(1, sheet.getCellComments().size(), "Wrong starting # of comments"); - - sheet.removeRow(sheet.getRow(commentCellAddress.getRow())); - - assertEquals(0, sheet.getCellComments().size(), "There should not be any comments left!"); - } - } - - @Test - void testGetHeaderFooterProperties() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sh = wb.createSheet(); - - XSSFHeaderFooterProperties hfProp = sh.getHeaderFooterProperties(); - assertNotNull(hfProp); - } - } - - @Test - void testSheetForceFormulaRecalculationDefaultValues() throws IOException { - try (Workbook wb = _testDataProvider.openSampleWorkbook("sample.xlsx")){ - for (Sheet s : wb) { - assertEquals(wb.getForceFormulaRecalculation(),s.getForceFormulaRecalculation()); - } - } - } - - @Test - void testWorkbookSetForceFormulaRecalculation() throws IOException { - try (Workbook wb = _testDataProvider.openSampleWorkbook("sample.xlsx")){ - wb.setForceFormulaRecalculation(true); - assertTrue(wb.getForceFormulaRecalculation()); - } - } - - @Test - void testNotCascadeWorkbookSetForceFormulaRecalculation() throws IOException { - try (Workbook wb = _testDataProvider.openSampleWorkbook("sample.xlsx")) { - // set all sheets to force recalculation - for (Sheet s : wb) { - s.setForceFormulaRecalculation(true); - assertTrue(s.getForceFormulaRecalculation()); - } - - // disable on workbook-level - wb.setForceFormulaRecalculation(false); - - // on sheet-level, the flag is still set - for (Sheet s : wb) { - assertTrue(s.getForceFormulaRecalculation(), "Sheet-level flag is still set to true"); - } - } - } - - @Test - public void bug65120() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - CreationHelper creationHelper = wb.getCreationHelper(); - - Sheet sheet1 = wb.createSheet(); - Cell cell1 = sheet1.createRow(0).createCell(0); - Comment comment1 = sheet1.createDrawingPatriarch().createCellComment(creationHelper.createClientAnchor()); - cell1.setCellComment(comment1); - - Sheet sheet2 = wb.createSheet(); - Cell cell2 = sheet2.createRow(0).createCell(0); - Comment comment2 = sheet2.createDrawingPatriarch().createCellComment(creationHelper.createClientAnchor()); - cell2.setCellComment(comment2); - - wb.removeSheetAt(0); - - Sheet sheet3 = wb.createSheet(); - Cell cell3 = sheet3.createRow(0).createCell(0); - Comment comment3 = sheet3.createDrawingPatriarch().createCellComment(creationHelper.createClientAnchor()); - cell3.setCellComment(comment3); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetAutosizeColumn.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetAutosizeColumn.java deleted file mode 100644 index c9aacd2aa3..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetAutosizeColumn.java +++ /dev/null @@ -1,28 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.BaseTestSheetAutosizeColumn; -import org.apache.poi.xssf.XSSFITestDataProvider; - -public final class TestXSSFSheetAutosizeColumn extends BaseTestSheetAutosizeColumn { - - public TestXSSFSheetAutosizeColumn(){ - super(XSSFITestDataProvider.instance); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java deleted file mode 100644 index 1cce6eb861..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.apache.logging.log4j.util.Unbox.box; -import static org.junit.jupiter.api.Assertions.*; - -import java.io.IOException; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -class TestXSSFSheetMergeRegions { - - private static final Logger LOG = LogManager.getLogger(TestXSSFSheetMergeRegions.class); - - @Test - void testMergeRegionsSpeed() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57893-many-merges.xlsx")) { - long millis = Long.MAX_VALUE; - - // in order to reduce the number of false positives we run it a few times before we fail, - // sometimes it fails on machines that are busy at the moment. - for (int i = 0; i < 5; i++) { - millis = runTest(wb); - if (millis < 2000) { - break; - } - LOG.atInfo().log("Retry {} because run-time is too high: {}", box(i),box(millis)); - } - - boolean inGump = false; - String version = System.getProperty("version.id"); - if (version != null && version.startsWith("gump-")) { - inGump = true; - } - - // This time is typically ~800ms, versus ~7800ms to iterate getMergedRegion(int). - // when running in Gump, the VM is very slow, so we should allow much more time - assertTrue(inGump ? millis < 8000 : millis < 2000, - "Should have taken <2000 ms to iterate 50k merged regions but took " + millis); - } - } - - private long runTest(final XSSFWorkbook wb) { - final long start = System.currentTimeMillis(); - final XSSFSheet sheet = wb.getSheetAt(0); - final List<CellRangeAddress> mergedRegions = sheet.getMergedRegions(); - assertEquals(50000, mergedRegions.size()); - for (CellRangeAddress cellRangeAddress : mergedRegions) { - assertEquals(cellRangeAddress.getFirstRow(), cellRangeAddress.getLastRow()); - assertEquals(2, cellRangeAddress.getNumberOfCells()); - } - return System.currentTimeMillis() - start; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java deleted file mode 100644 index b6dddc2c6d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java +++ /dev/null @@ -1,423 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -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.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -public final class TestXSSFSheetRowGrouping { - - private static final int ROWS_NUMBER = 200; - private static final int GROUP_SIZE = 5; - - @Test - void test55640() { - //long startTime = System.currentTimeMillis(); - Workbook wb = new XSSFWorkbook(); - fillData(wb); - writeToFile(wb); - - //System.out.println("Number of groups: " + o_groupsNumber); - //System.out.println("Execution time: " + (System.currentTimeMillis()-startTime) + " ms"); - } - - - private void fillData(Workbook p_wb) { - Sheet sheet = p_wb.createSheet("sheet123"); - sheet.setRowSumsBelow(false); - - for (int i = 0; i < ROWS_NUMBER; i++) { - Row row = sheet.createRow(i); - Cell cell = row.createCell(0); - cell.setCellValue(i+1); - } - - int i = 1; - while (i < ROWS_NUMBER) { - int end = i+(GROUP_SIZE-2); - int start = i; // natural order -// int start = end - 1; // reverse order - while (start < end) { // natural order -// while (start >= i) { // reverse order - sheet.groupRow(start, end); - //o_groupsNumber++; - boolean collapsed = isCollapsed(); - //System.out.println("Set group " + start + "->" + end + " to " + collapsed); - sheet.setRowGroupCollapsed(start, collapsed); - start++; // natural order -// start--; // reverse order - } - i += GROUP_SIZE; - } - } - - private boolean isCollapsed() { - return Math.random() > 0.5d; - } - - private void writeToFile(Workbook p_wb) { -// FileOutputStream fileOut = new FileOutputStream("/tmp/55640.xlsx"); -// try { -// p_wb.write(fileOut); -// } finally { -// fileOut.close(); -// } - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(p_wb)); - } - - @Test - void test55640reduce1() { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet123"); - sheet.setRowSumsBelow(false); - - for (int i = 0; i < ROWS_NUMBER; i++) { - Row row = sheet.createRow(i); - Cell cell = row.createCell(0); - cell.setCellValue(i+1); - } - - int i = 1; - while (i < ROWS_NUMBER) { - int end = i+(GROUP_SIZE-2); - int start = i; // natural order - while (start < end) { // natural order - sheet.groupRow(start, end); - //o_groupsNumber++; - boolean collapsed = (start % 2) != 0; - //System.out.println("Set group " + start + "->" + end + " to " + collapsed); - sheet.setRowGroupCollapsed(start, collapsed); - start++; // natural order - } - i += GROUP_SIZE; - } - writeToFile(wb); - } - - @Test - void test55640_VerifyCases() { - // NOTE: This is currently based on current behavior of POI, somehow - // what POI returns in the calls to collapsed/hidden is not fully matching - // the examples in the spec or I did not fully understand how POI stores the data internally... - - // all expanded - verifyGroupCollapsed( - // level1, level2, level3 - false, false, false, - // collapsed: - new Boolean[] { false, false, false, false, false}, - // hidden: - new boolean[] { false, false, false, false, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3 } - ); - - - // Level 1 collapsed, others expanded, should only have 4 rows, all hidden: - verifyGroupCollapsed( - // level1, level2, level3 - true, false, false, - // collapsed: - new Boolean[] { false, false, false, false, false}, - // hidden: - new boolean[] { true, true, true, true, true}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3 } - ); - - // Level 1 and 2 collapsed, Level 3 expanded, - verifyGroupCollapsed( - // level1, level2, level3 - true, true, false, - // collapsed: - new Boolean[] { false, false, false, false, true, false}, - // hidden: - new boolean[] { true, true, true, true, true, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3, 0 } - ); - - // Level 1 collapsed, Level 2 expanded, Level 3 collapsed - verifyGroupCollapsed( - // level1, level2, level3 - true, false, true, - // collapsed: - new Boolean[] { false, false, false, false, false, true}, - // hidden: - new boolean[] { true, true, true, true, true, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3, 0 } - ); - - // Level 2 collapsed, others expanded: - verifyGroupCollapsed( - // level1, level2, level3 - false, true, false, - // collapsed: - new Boolean[] { false, false, false, false, false, false}, - // hidden: - new boolean[] { false, true, true, true, true, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3, 0 } - ); - - // Level 3 collapsed, others expanded - verifyGroupCollapsed( - // level1, level2, level3 - false, false, true, - // collapsed: - new Boolean[] { false, false, false, false, false, true}, - // hidden: - new boolean[] { false, false, true, true, true, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3, 0 } - ); - - // All collapsed - verifyGroupCollapsed( - // level1, level2, level3 - true, true, true, - // collapsed: - new Boolean[] { false, false, false, false, true, true}, - // hidden: - new boolean[] { true, true, true, true, true, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3, 0 } - ); - } - - - private void verifyGroupCollapsed(boolean level1, boolean level2, boolean level3, - Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet123"); - - for (int i = 0; i < 4; i++) { - sheet.createRow(i); - } - - sheet.groupRow(0, 4); - sheet.groupRow(1, 4); - sheet.groupRow(2, 4); - - sheet.setRowGroupCollapsed(0, level1); - sheet.setRowGroupCollapsed(1, level2); - sheet.setRowGroupCollapsed(2, level3); - - checkWorkbookGrouping(wb, collapsed, hidden, outlineLevel); - } - - @Test - void test55640_VerifyCasesSpec() { - // NOTE: This is currently based on current behavior of POI, somehow - // what POI returns in the calls to collapsed/hidden is not fully matching - // the examples in the spec or I did not fully understand how POI stores the data internally... - - // all expanded - verifyGroupCollapsedSpec( - // level3, level2, level1 - false, false, false, - // collapsed: - new Boolean[] { false, false, false, false}, - // hidden: - new boolean[] { false, false, false, false}, - // outlineLevel - new int[] { 3, 3, 2, 1 } - ); - - - verifyGroupCollapsedSpec( - // level3, level2, level1 - false, false, true, - // collapsed: - new Boolean[] { false, false, false, true}, - // hidden: - new boolean[] { true, true, true, false}, - // outlineLevel - new int[] { 3, 3, 2, 1 } - ); - - verifyGroupCollapsedSpec( - // level3, level2, level1 - false, true, false, - // collapsed: - new Boolean[] { false, false, true, false}, - // hidden: - new boolean[] { true, true, true, false}, - // outlineLevel - new int[] { 3, 3, 2, 1 } - ); - - verifyGroupCollapsedSpec( - // level3, level2, level1 - false, true, true, - // collapsed: - new Boolean[] { false, false, true, true}, - // hidden: - new boolean[] { true, true, true, false}, - // outlineLevel - new int[] { 3, 3, 2, 1 } - ); - } - - @SuppressWarnings("SameParameterValue") - private void verifyGroupCollapsedSpec(boolean level1, boolean level2, boolean level3, - Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet123"); - - for (int i = 5; i < 9; i++) { - sheet.createRow(i); - } - - sheet.groupRow(5, 6); - sheet.groupRow(5, 7); - sheet.groupRow(5, 8); - - sheet.setRowGroupCollapsed(6, level1); - sheet.setRowGroupCollapsed(7, level2); - sheet.setRowGroupCollapsed(8, level3); - - checkWorkbookGrouping(wb, collapsed, hidden, outlineLevel); - } - - private void checkWorkbookGrouping(Workbook wb, Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) { - Sheet sheet = wb.getSheetAt(0); - - assertEquals(collapsed.length, hidden.length); - assertEquals(collapsed.length, outlineLevel.length); - assertEquals(collapsed.length, sheet.getLastRowNum()-sheet.getFirstRowNum()+1, - "Expected " + collapsed.length + " rows with collapsed state, but had " + (sheet.getLastRowNum()-sheet.getFirstRowNum()+1) + " rows (" - + sheet.getFirstRowNum() + "-" + sheet.getLastRowNum() + ")"); - for(int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum();i++) { - if(collapsed[i-sheet.getFirstRowNum()] == null) { - continue; - } - XSSFRow row = (XSSFRow) sheet.getRow(i); - assertNotNull(row, "Could not read row " + i); - assertNotNull(row.getCTRow(), "Could not read row " + i); - assertEquals(collapsed[i - sheet.getFirstRowNum()], row.getCTRow().getCollapsed(), "Row: " + i + ": collapsed"); - assertEquals(hidden[i-sheet.getFirstRowNum()], row.getCTRow().getHidden(), "Row: " + i + ": hidden"); - - assertEquals(outlineLevel[i-sheet.getFirstRowNum()], row.getCTRow().getOutlineLevel(), "Row: " + i + ": level"); - } - - writeToFile(wb); - } - - @Test - void test55640working() { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet123"); - - sheet.groupRow(1, 4); - sheet.groupRow(2, 5); - sheet.groupRow(3, 6); - - sheet.setRowGroupCollapsed(1, true); - sheet.setRowGroupCollapsed(2, false); - sheet.setRowGroupCollapsed(3, false); - - writeToFile(wb); - } - - @Test - void testGroupingTest() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GroupTest.xlsx")) { - - assertEquals(31, wb.getSheetAt(0).getLastRowNum()); - - // NOTE: This is currently based on current behavior of POI, somehow - // what POI returns in the calls to collapsed/hidden is not fully matching - // the examples in the spec or I did not fully understand how POI stores the data internally... - checkWorkbookGrouping(wb, - new Boolean[]{ - // 0-4 - false, false, false, false, false, null, null, - // 7-11 - false, false, true, true, true, null, null, - // 14-18 - false, false, true, false, false, null, - // 20-24 - false, false, true, true, false, null, null, - // 27-31 - false, false, false, true, false}, - new boolean[]{ - // 0-4 - false, false, false, false, false, false, false, - // 7-11 - true, true, true, true, false, false, false, - // 14-18 - true, true, false, false, false, false, - // 20-24 - true, true, true, false, false, false, false, - // 27-31 - true, true, true, true, false}, - // outlineLevel - new int[]{ - // 0-4 - 3, 3, 2, 1, 0, 0, 0, - // 7-11 - 3, 3, 2, 1, 0, 0, 0, - // 14-18 - 3, 3, 2, 1, 0, 0, - // 20-24 - 3, 3, 2, 1, 0, 0, 0, - // 27-31 - 3, 3, 2, 1, 0, - } - ); - } - /* -Row: 0: Level: 3 Collapsed: false Hidden: false -Row: 1: Level: 3 Collapsed: false Hidden: false -Row: 2: Level: 2 Collapsed: false Hidden: false -Row: 3: Level: 1 Collapsed: false Hidden: false -Row: 4: Level: 0 Collapsed: false Hidden: false -Row: 7: Level: 3 Collapsed: false Hidden: true -Row: 8: Level: 3 Collapsed: false Hidden: true -Row: 9: Level: 2 Collapsed: true Hidden: true -Row: 10: Level: 1 Collapsed: true Hidden: true -Row: 11: Level: 0 Collapsed: true Hidden: false -Row: 14: Level: 3 Collapsed: false Hidden: true -Row: 15: Level: 3 Collapsed: false Hidden: true -Row: 16: Level: 2 Collapsed: true Hidden: false -Row: 17: Level: 1 Collapsed: false Hidden: false -Row: 18: Level: 0 Collapsed: false Hidden: false -Row: 20: Level: 3 Collapsed: false Hidden: true -Row: 21: Level: 3 Collapsed: false Hidden: true -Row: 22: Level: 2 Collapsed: true Hidden: true -Row: 23: Level: 1 Collapsed: true Hidden: false -Row: 24: Level: 0 Collapsed: false Hidden: false -Row: 27: Level: 3 Collapsed: false Hidden: true -Row: 28: Level: 3 Collapsed: false Hidden: true -Row: 29: Level: 2 Collapsed: false Hidden: true -Row: 30: Level: 1 Collapsed: true Hidden: true -Row: 31: Level: 0 Collapsed: true Hidden: false - */ - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftColumns.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftColumns.java deleted file mode 100644 index 92d5735ec5..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftColumns.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestSheetShiftColumns; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; - -class TestXSSFSheetShiftColumns extends BaseTestSheetShiftColumns { - public TestXSSFSheetShiftColumns() { - super(); - workbook = new XSSFWorkbook(); - _testDataProvider = XSSFITestDataProvider.instance; - } - - protected Workbook openWorkbook(String spreadsheetFileName) throws IOException { - return XSSFTestDataSamples.openSampleWorkbook(spreadsheetFileName); - } - - protected Workbook getReadBackWorkbook(Workbook wb) { - return XSSFTestDataSamples.writeOutAndReadBack(wb); - } - -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java deleted file mode 100644 index 06b15f7f4c..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java +++ /dev/null @@ -1,526 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.assertThrows; - -import java.io.IOException; -import java.util.stream.IntStream; - -import org.apache.poi.ss.usermodel.BaseTestSheetShiftRows; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Comment; -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.util.CellAddress; -import org.apache.poi.ss.util.CellUtil; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { - - public TestXSSFSheetShiftRows(){ - super(XSSFITestDataProvider.instance); - } - - @Override - protected void testShiftRowBreaks() { - // disabled test from superclass - // TODO - support shifting of page breaks - } - - /** Error occurred at FormulaShifter#rowMoveAreaPtg while shift rows upward. */ - @Test - void testBug54524() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("54524.xlsx"); - XSSFSheet sheet = workbook.getSheetAt(0); - sheet.shiftRows(3, 5, -1); - - Cell cell = CellUtil.getCell(sheet.getRow(1), 0); - assertEquals(1.0, cell.getNumericCellValue(), 0); - cell = CellUtil.getCell(sheet.getRow(2), 0); - assertEquals("SUM(A2:A2)", cell.getCellFormula()); - cell = CellUtil.getCell(sheet.getRow(3), 0); - assertEquals("X", cell.getStringCellValue()); - workbook.close(); - } - - /** negative row shift causes corrupted data or throws exception */ - @Test - void testBug53798() throws IOException { - // NOTE that for HSSF (.xls) negative shifts combined with positive ones do work as expected - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53798.xlsx"); - - Sheet testSheet = wb.getSheetAt(0); - // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about - // when shifted by less than -1 negative amount (try -2) - testSheet.shiftRows(3, 3, -2); - - // 2) attempt to create a new row IN PLACE of a removed row by a negative shift causes corrupted - // xlsx file with unreadable data in the negative shifted row. - // NOTE it's ok to create any other row. - Row newRow = testSheet.createRow(3); - Cell newCell = newRow.createCell(0); - newCell.setCellValue("new Cell in row "+newRow.getRowNum()); - - // 3) once a negative shift has been made any attempt to shift another group of rows - // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception: - // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException. - // NOTE: another negative shift on another group of rows is successful, provided no new rows in - // place of previously shifted rows were attempted to be created as explained above. - - // -- CHANGE the shift to positive once the behaviour of the above has been tested - testSheet.shiftRows(6, 7, 1); - - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - assertNotNull(read); - - Sheet readSheet = read.getSheetAt(0); - verifyCellContent(readSheet, 0, "0.0"); - verifyCellContent(readSheet, 1, "3.0"); - verifyCellContent(readSheet, 2, "2.0"); - verifyCellContent(readSheet, 3, "new Cell in row 3"); - verifyCellContent(readSheet, 4, "4.0"); - verifyCellContent(readSheet, 5, "5.0"); - verifyCellContent(readSheet, 6, null); - verifyCellContent(readSheet, 7, "6.0"); - verifyCellContent(readSheet, 8, "7.0"); - read.close(); - } - - private void verifyCellContent(Sheet readSheet, int row, String expect) { - Row readRow = readSheet.getRow(row); - if(expect == null) { - assertNull(readRow); - return; - } - Cell readCell = readRow.getCell(0); - if(readCell.getCellType() == CellType.NUMERIC) { - assertEquals(expect, Double.toString(readCell.getNumericCellValue())); - } else { - assertEquals(expect, readCell.getStringCellValue()); - } - } - - /** negative row shift causes corrupted data or throws exception */ - @Test - void testBug53798a() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53798.xlsx"); - - Sheet testSheet = wb.getSheetAt(0); - testSheet.shiftRows(3, 3, -1); - for (Row r : testSheet) { - r.getRowNum(); - } - testSheet.shiftRows(6, 6, 1); - - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - assertNotNull(read); - - Sheet readSheet = read.getSheetAt(0); - verifyCellContent(readSheet, 0, "0.0"); - verifyCellContent(readSheet, 1, "1.0"); - verifyCellContent(readSheet, 2, "3.0"); - verifyCellContent(readSheet, 3, null); - verifyCellContent(readSheet, 4, "4.0"); - verifyCellContent(readSheet, 5, "5.0"); - verifyCellContent(readSheet, 6, null); - verifyCellContent(readSheet, 7, "6.0"); - verifyCellContent(readSheet, 8, "8.0"); - read.close(); - } - - /** Shifting rows with comment result - Unreadable content error and comment deletion */ - @Test - void testBug56017() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56017.xlsx"); - - Sheet sheet = wb.getSheetAt(0); - - Comment comment = sheet.getCellComment(new CellAddress(0, 0)); - assertNotNull(comment); - assertEquals("Amdocs", comment.getAuthor()); - assertEquals("Amdocs:\ntest\n", comment.getString().getString()); - - sheet.shiftRows(0, 1, 1); - - // comment in row 0 is gone - comment = sheet.getCellComment(new CellAddress(0, 0)); - assertNull(comment); - - // comment is now in row 1 - comment = sheet.getCellComment(new CellAddress(1, 0)); - assertNotNull(comment); - assertEquals("Amdocs", comment.getAuthor()); - assertEquals("Amdocs:\ntest\n", comment.getString().getString()); - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - assertNotNull(wbBack); - - Sheet sheetBack = wbBack.getSheetAt(0); - - // comment in row 0 is gone - comment = sheetBack.getCellComment(new CellAddress(0, 0)); - assertNull(comment); - - // comment is now in row 1 - comment = sheetBack.getCellComment(new CellAddress(1, 0)); - assertNotNull(comment); - assertEquals("Amdocs", comment.getAuthor()); - assertEquals("Amdocs:\ntest\n", comment.getString().getString()); - wbBack.close(); - } - - /** Moving the active sheet and deleting the others results in a corrupted file */ - @Test - void test57171() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - assertEquals(5, wb.getActiveSheetIndex()); - removeAllSheetsBut(5, wb); // 5 is the active / selected sheet - assertEquals(0, wb.getActiveSheetIndex()); - - Workbook wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - assertEquals(0, wbRead.getActiveSheetIndex()); - - wbRead.removeSheetAt(0); - assertEquals(0, wbRead.getActiveSheetIndex()); - - wbRead.close(); - } - - /** Cannot delete an arbitrary sheet in an XLS workbook (only the last one) */ - @Test - void test57163() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - assertEquals(5, wb.getActiveSheetIndex()); - wb.removeSheetAt(0); - assertEquals(4, wb.getActiveSheetIndex()); - - wb.close(); - } - - @Test - void testSetSheetOrderAndAdjustActiveSheet() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - - assertEquals(5, wb.getActiveSheetIndex()); - - // move the sheets around in all possible combinations to check that the active sheet - // is set correctly in all cases - wb.setSheetOrder(wb.getSheetName(5), 4); - assertEquals(4, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(5), 5); - assertEquals(4, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(3), 5); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(4), 5); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(2), 2); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(2), 1); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(3), 5); - assertEquals(5, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(4, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(2, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(1, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(0, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(5, wb.getActiveSheetIndex()); - - wb.close(); - } - - @Test - void testRemoveSheetAndAdjustActiveSheet() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - - assertEquals(5, wb.getActiveSheetIndex()); - - wb.removeSheetAt(0); - assertEquals(4, wb.getActiveSheetIndex()); - - wb.setActiveSheet(3); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.removeSheetAt(4); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.removeSheetAt(3); - assertEquals(2, wb.getActiveSheetIndex()); - - wb.removeSheetAt(0); - assertEquals(1, wb.getActiveSheetIndex()); - - wb.removeSheetAt(1); - assertEquals(0, wb.getActiveSheetIndex()); - - wb.removeSheetAt(0); - assertEquals(0, wb.getActiveSheetIndex()); - assertThrows(IllegalArgumentException.class, () -> wb.removeSheetAt(0), - "Should catch exception as no more sheets are there"); - assertEquals(0, wb.getActiveSheetIndex()); - - wb.createSheet(); - assertEquals(0, wb.getActiveSheetIndex()); - - wb.removeSheetAt(0); - assertEquals(0, wb.getActiveSheetIndex()); - - wb.close(); - } - - /** Failed to clone a sheet from an Excel 2010 */ - @Test - void test57165() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - assertEquals(5, wb.getActiveSheetIndex()); - removeAllSheetsBut(3, wb); - assertEquals(0, wb.getActiveSheetIndex()); - wb.createSheet("New Sheet1"); - assertEquals(0, wb.getActiveSheetIndex()); - wb.cloneSheet(0); // Throws exception here - wb.setSheetName(1, "New Sheet"); - assertEquals(0, wb.getActiveSheetIndex()); - - wb.close(); - } - - private static void removeAllSheetsBut(int sheetIndex, Workbook wb) { - int sheetNb = wb.getNumberOfSheets(); - // Move this sheet at the first position - wb.setSheetOrder(wb.getSheetName(sheetIndex), 0); - // Must make this sheet active (otherwise, for XLSX, Excel might protest that active sheet no longer exists) - // I think POI should automatically handle this case when deleting sheets... - // wb.setActiveSheet(0); - for (int sn = sheetNb - 1; sn > 0; sn--) { - wb.removeSheetAt(sn); - } - } - - /** Shifting rows with cell comments only shifts comments from first such cell. Other cell comments not shifted */ - @Test - void testBug57828_OnlyOneCommentShiftedInRow() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57828.xlsx")) { - XSSFSheet sheet = wb.getSheetAt(0); - - Comment comment1 = sheet.getCellComment(new CellAddress(2, 1)); - assertNotNull(comment1); - - Comment comment2 = sheet.getCellComment(new CellAddress(2, 2)); - assertNotNull(comment2); - - Comment comment3 = sheet.getCellComment(new CellAddress(1, 1)); - assertNull(comment3, "NO comment in (1,1) and it should be null"); - - sheet.shiftRows(2, 2, -1); - - comment3 = sheet.getCellComment(new CellAddress(1, 1)); - assertNotNull(comment3, "Comment in (2,1) moved to (1,1) so its not null now."); - - comment1 = sheet.getCellComment(new CellAddress(2, 1)); - assertNull(comment1, "No comment currently in (2,1) and hence it is null"); - - comment2 = sheet.getCellComment(new CellAddress(1, 2)); - assertNotNull(comment2, "Comment in (2,2) should have moved as well because of shift rows. But its not"); - } - } - - @Test - void bug59733() throws IOException { - Workbook workbook = new XSSFWorkbook(); - Sheet sheet = workbook.createSheet(); - for (int r=0; r<4; r++) { - sheet.createRow(r); - } - - // Shift the 2nd row on top of the 0th row - sheet.shiftRows(2, 2, -2); - - sheet.removeRow(sheet.getRow(0)); - assertEquals(1, sheet.getRow(1).getRowNum()); - - workbook.close(); - } - - private static String getCellFormula(Sheet sheet, String address) { - CellAddress cellAddress = new CellAddress(address); - Row row = sheet.getRow(cellAddress.getRow()); - assertNotNull(row); - Cell cell = row.getCell(cellAddress.getColumn()); - assertNotNull(cell); - assertEquals(CellType.FORMULA, cell.getCellType()); - return cell.getCellFormula(); - } - - // bug 59983: Wrong update of shared formulas after shiftRow - @Test - void testSharedFormulas() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("TestShiftRowSharedFormula.xlsx")) { - XSSFSheet sheet = wb.getSheetAt(0); - assertEquals("SUM(C2:C4)", getCellFormula(sheet, "C5")); - assertEquals("SUM(D2:D4)", getCellFormula(sheet, "D5")); - assertEquals("SUM(E2:E4)", getCellFormula(sheet, "E5")); - - assertEquals("SUM(C3:C5)", getCellFormula(sheet, "C6")); - assertEquals("SUM(D3:D5)", getCellFormula(sheet, "D6")); - assertEquals("SUM(E3:E5)", getCellFormula(sheet, "E6")); - - sheet.shiftRows(3, sheet.getLastRowNum(), 1); - - assertEquals("SUM(C2:C5)", getCellFormula(sheet, "C6")); - assertEquals("SUM(D2:D5)", getCellFormula(sheet, "D6")); - assertEquals("SUM(E2:E5)", getCellFormula(sheet, "E6")); - - assertEquals("SUM(C3:C6)", getCellFormula(sheet, "C7")); - assertEquals("SUM(D3:D6)", getCellFormula(sheet, "D7")); - assertEquals("SUM(E3:E6)", getCellFormula(sheet, "E7")); - } - } - - // bug 59983: Wrong update of shared formulas after shiftRow - @Test - void testShiftSharedFormulas() throws Exception { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("TestShiftRowSharedFormula.xlsx")) { - XSSFSheet sheet = wb.getSheetAt(0); - assertEquals("SUM(C2:C4)", getCellFormula(sheet, "C5")); - assertEquals("SUM(D2:D4)", getCellFormula(sheet, "D5")); - assertEquals("SUM(E2:E4)", getCellFormula(sheet, "E5")); - - assertEquals("SUM(C3:C5)", getCellFormula(sheet, "C6")); - assertEquals("SUM(D3:D5)", getCellFormula(sheet, "D6")); - assertEquals("SUM(E3:E5)", getCellFormula(sheet, "E6")); - - sheet.shiftRows(sheet.getFirstRowNum(), 4, -1); - - assertEquals("SUM(C1:C3)", getCellFormula(sheet, "C4")); - assertEquals("SUM(D1:D3)", getCellFormula(sheet, "D4")); - assertEquals("SUM(E1:E3)", getCellFormula(sheet, "E4")); - - assertEquals("SUM(C2:C4)", getCellFormula(sheet, "C6")); - assertEquals("SUM(D2:D4)", getCellFormula(sheet, "D6")); - assertEquals("SUM(E2:E4)", getCellFormula(sheet, "E6")); - } - } - - // bug 60260: shift rows or rename a sheet containing a named range - // that refers to formula with a unicode (non-ASCII) sheet name formula - @Test - void shiftRowsWithUnicodeNamedRange() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("unicodeSheetName.xlsx")) { - XSSFSheet sheet = wb.getSheetAt(0); - sheet.shiftRows(1, 2, 3); - - Integer[] exp = { 1, null, null, 4, 2, 3, 7, 8, 9 }; - IntStream.rangeClosed(0, 8).forEach(i -> { - Row row = sheet.getRow(i); - if (exp[i] == null) { - assertNull(row); - } else { - assertEquals(exp[i], (int)row.getCell(0).getNumericCellValue()); - } - }); - } - } - - @Test - void test60384() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("60384.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - - assertEquals(2, sheet.getMergedRegions().size()); - assertEquals(7, sheet.getMergedRegion(0).getFirstRow()); - assertEquals(7, sheet.getMergedRegion(0).getLastRow()); - assertEquals(8, sheet.getMergedRegion(1).getFirstRow()); - assertEquals(8, sheet.getMergedRegion(1).getLastRow()); - - sheet.shiftRows(3, 8, 1); - - // after shifting, the two named regions should still be there as they - // are fully inside the shifted area - assertEquals(2, sheet.getMergedRegions().size()); - assertEquals(8, sheet.getMergedRegion(0).getFirstRow()); - assertEquals(8, sheet.getMergedRegion(0).getLastRow()); - assertEquals(9, sheet.getMergedRegion(1).getFirstRow()); - assertEquals(9, sheet.getMergedRegion(1).getLastRow()); - - /*OutputStream out = new FileOutputStream("/tmp/60384.xlsx"); - try { - wb.write(out); - } finally { - out.close(); - }*/ - - wb.close(); - } - - @Test - void test60709() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("60709.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - - assertEquals(1, sheet.getMergedRegions().size()); - assertEquals(2, sheet.getMergedRegion(0).getFirstRow()); - assertEquals(2, sheet.getMergedRegion(0).getLastRow()); - - sheet.shiftRows(1, sheet.getLastRowNum()+1, -1, true, false); - - // after shifting, the two named regions should still be there as they - // are fully inside the shifted area - assertEquals(1, sheet.getMergedRegions().size()); - assertEquals(1, sheet.getMergedRegion(0).getFirstRow()); - assertEquals(1, sheet.getMergedRegion(0).getLastRow()); - - /*OutputStream out = new FileOutputStream("/tmp/60709.xlsx"); - try { - wb.write(out); - } finally { - out.close(); - }*/ - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRowsAndColumns.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRowsAndColumns.java deleted file mode 100644 index e31332027a..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRowsAndColumns.java +++ /dev/null @@ -1,202 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Locale; - -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; - -class TestXSSFSheetShiftRowsAndColumns { - private static final File resultDir = new File("build/custom-reports-test"); - - private static final int numRows = 4; - private static final int numCols = 4; - - private static final int INSERT_ROW = 1; - private static final int INSERT_COLUMN = 1; - private static final int FIRST_MERGE_ROW = INSERT_ROW+1; - private static final int LAST_MERGE_ROW = numRows-1; - private static final int FIRST_MERGE_COL = INSERT_COLUMN+1; - private static final int LAST_MERGE_COL = numCols-1; - - private XSSFWorkbook workbook = null; - private XSSFSheet sheet = null; - private String fileName = null; - - public TestXSSFSheetShiftRowsAndColumns() { - assertTrue(resultDir.exists() || resultDir.mkdirs(), "Failed to create directory " + resultDir); - } - - /** - * This creates a workbook with one worksheet. It then puts data in rows 0 to numRows-1 and colulmns - * 0 to numCols-1. - */ - @BeforeEach - void setup() throws IOException { - final String procName = "TestXSSFSheetShiftRowsAndColumns.setup"; - fileName = procName+".xlsx"; - - workbook = new XSSFWorkbook(); - sheet = workbook.createSheet(); - - for (int nRow = 0; nRow < numRows; ++nRow) { - final XSSFRow row = sheet.createRow(nRow); - for (int nCol = 0; nCol < numCols; ++nCol) { - final XSSFCell cell = row.createCell(nCol); - cell.setCellType(CellType.STRING); - cell.setCellValue(String.format(Locale.US, "Row %d col %d", nRow, nCol)); - } - } - /* - * Add a merge area - */ - final CellRangeAddress range = new CellRangeAddress(FIRST_MERGE_ROW,LAST_MERGE_ROW,FIRST_MERGE_COL,LAST_MERGE_COL); - sheet.addMergedRegion(range); - writeFile(procName); - } - - - /** - * This method writes the workbook to resultDir/fileName. - */ - @AfterEach - void cleanup() throws IOException { - final String procName = "TestXSSFSheetRemoveTable.cleanup"; - if (workbook == null) { - return; - } - - if(fileName == null) { - return; - } - - writeFile(procName); - - workbook.close(); - } - - private void writeFile(String procName) throws IOException { - final File file = new File(resultDir,fileName); - try (OutputStream fileOut = new FileOutputStream(file)) { - workbook.write(fileOut); - } - } - - /** - * Apply no shift. The purpose of this is to test {@code testCellAddresses} and {@code testMergeRegion}. - */ - @Test - void testNoShift() { - final String procName = "testNoShift"; - fileName = procName+".xlsx"; - - testCellAddresses(procName,0,0); - testMergeRegion(procName,0,0); - } - - @Test - void testShiftOneRowAndTestAddresses() { - final String procName = "testShiftOneRowAndTestAddresses"; - fileName = procName+".xlsx"; - final int nRowsToShift = 1; - - sheet.shiftRows(INSERT_ROW, numRows-1, nRowsToShift); - testCellAddresses(procName,nRowsToShift,0); - } - - @Test - void testShiftOneRowAndTestMergeRegion() { - final String procName = "testShiftOneRowAndTestMergeRegion"; - fileName = procName+".xlsx"; - final int nRowsToShift = 1; - - sheet.shiftRows(INSERT_ROW, numRows-1, nRowsToShift); - testMergeRegion(procName,nRowsToShift,0); - } - - @Test - void testShiftOneColumnAndTestAddresses() { - final String procName = "testShiftOneColumnAndTestAddresses"; - fileName = procName+".xlsx"; - final int nShift = 1; - - sheet.shiftColumns(INSERT_COLUMN, numCols-1, nShift); - testCellAddresses(procName,0,nShift); - } - - @Test - void testShiftOneColumnAndTestMergeRegion() { - final String procName = "testShiftOneColumnAndTestMergeRegion"; - fileName = procName+".xlsx"; - final int nShift = 1; - - sheet.shiftColumns(INSERT_COLUMN, numCols-1, nShift); - testMergeRegion(procName,0, nShift); - } - - /** - * Verify that the cell addresses are consistent - */ - private void testCellAddresses(String procName,int nRowsToShift,int nColsToShift) { - final int nNumRows = nRowsToShift+ numCols; - final int nNumCols = nColsToShift+ numCols; - for(int nRow = 0;nRow<nNumRows;++nRow) { - final XSSFRow row = sheet.getRow(nRow); - if(row == null) { - continue; - } - for(int nCol = 0;nCol<nNumCols;++nCol) { - final String address = new CellAddress(nRow,nCol).formatAsString(); - final XSSFCell cell = row.getCell(nCol); - if(cell == null) { - continue; - } - final CTCell ctCell = cell.getCTCell(); - final Object cellAddress = cell.getAddress().formatAsString(); - final Object r = ctCell.getR(); - - assertEquals(address,cellAddress,String.format(Locale.US, "%s: Testing cell.getAddress",procName)); - assertEquals(address,r,String.format(Locale.US, "%s: Testing ctCell.getR",procName)); - } - } - - } - - /** - * Verify that the merge area is consistent - */ - private void testMergeRegion(String procName,int nRowsToShift,int nColsToShift) { - final CellRangeAddress range = sheet.getMergedRegion(0); - assertEquals(new CellRangeAddress(FIRST_MERGE_ROW + nRowsToShift, LAST_MERGE_ROW + nRowsToShift, - FIRST_MERGE_COL + nColsToShift, LAST_MERGE_COL + nColsToShift), range, - String.format(Locale.US, "%s: Testing merge area %s", procName, range)); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetUpdateArrayFormulas.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetUpdateArrayFormulas.java deleted file mode 100644 index 9217a2f431..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetUpdateArrayFormulas.java +++ /dev/null @@ -1,117 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestSheetUpdateArrayFormulas; -import org.apache.poi.ss.usermodel.CellRange; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType; - -/** - * Test array formulas in XSSF - */ -public final class TestXSSFSheetUpdateArrayFormulas extends BaseTestSheetUpdateArrayFormulas { - - public TestXSSFSheetUpdateArrayFormulas() { - super(XSSFITestDataProvider.instance); - } - - // Test methods common with HSSF are in superclass - // Local methods here test XSSF-specific details of updating array formulas - @Test - void testXSSFSetArrayFormula_singleCell() throws IOException { - CellRange<XSSFCell> cells; - - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - - // 1. single-cell array formula - String formula1 = "123"; - CellRangeAddress range = CellRangeAddress.valueOf("C3:C3"); - cells = sheet.setArrayFormula(formula1, range); - assertEquals(1, cells.size()); - - // check getFirstCell... - XSSFCell firstCell = cells.getTopLeftCell(); - assertSame(firstCell, sheet.getFirstCellInArrayFormula(firstCell)); - //retrieve the range and check it is the same - assertEquals(range.formatAsString(), firstCell.getArrayFormulaRange().formatAsString()); - confirmArrayFormulaCell(firstCell, "C3", formula1, "C3"); - - workbook.close(); - } - - @Test - void testXSSFSetArrayFormula_multiCell() throws IOException { - CellRange<XSSFCell> cells; - - String formula2 = "456"; - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - - CellRangeAddress range = CellRangeAddress.valueOf("C4:C6"); - cells = sheet.setArrayFormula(formula2, range); - assertEquals(3, cells.size()); - - // sheet.setArrayFormula creates rows and cells for the designated range - /* - * From the spec: - * For a multi-cell formula, the c elements for all cells except the top-left - * cell in that range shall not have an f element; - */ - // Check that each cell exists and that the formula text is set correctly on the first cell - XSSFCell firstCell = cells.getTopLeftCell(); - confirmArrayFormulaCell(firstCell, "C4", formula2, "C4:C6"); - confirmArrayFormulaCell(cells.getCell(1, 0), "C5"); - confirmArrayFormulaCell(cells.getCell(2, 0), "C6"); - - assertSame(firstCell, sheet.getFirstCellInArrayFormula(firstCell)); - workbook.close(); - } - - private static void confirmArrayFormulaCell(XSSFCell c, String cellRef) { - confirmArrayFormulaCell(c, cellRef, null, null); - } - private static void confirmArrayFormulaCell(XSSFCell c, String cellRef, String formulaText, String arrayRangeRef) { - assertNotNull(c, "Cell should not be null."); - CTCell ctCell = c.getCTCell(); - assertEquals(cellRef, ctCell.getR()); - if (formulaText == null) { - assertFalse(ctCell.isSetF()); - assertNull(ctCell.getF()); - } else { - CTCellFormula f = ctCell.getF(); - assertEquals(arrayRangeRef, f.getRef()); - assertEquals(formulaText, f.getStringValue()); - assertEquals(STCellFormulaType.ARRAY, f.getT()); - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSimpleShape.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSimpleShape.java deleted file mode 100644 index db0bb77233..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSimpleShape.java +++ /dev/null @@ -1,213 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.awt.Color; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.xddf.usermodel.text.XDDFBodyProperties; -import org.apache.poi.xddf.usermodel.text.XDDFNoAutoFit; -import org.apache.poi.xddf.usermodel.text.XDDFNormalAutoFit; -import org.apache.poi.xddf.usermodel.text.XDDFShapeAutoFit; -import org.apache.poi.xddf.usermodel.text.XDDFTextBody; -import org.apache.poi.xddf.usermodel.text.XDDFTextParagraph; -import org.junit.jupiter.api.Test; - -class TestXSSFSimpleShape { - @Test - void testXSSFTextParagraph() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - - XSSFFont font = wb.createFont(); - Color color = new Color(0, 255, 255); - font.setColor(new XSSFColor(color, wb.getStylesSource().getIndexedColors())); - font.setFontName("Arial"); - rt.applyFont(font); - - shape.setText(rt); - - assertNotNull(shape.getCTShape()); - assertNotNull(shape.iterator()); - assertNotNull(XSSFSimpleShape.prototype()); - - for (ListAutoNumber nr : ListAutoNumber.values()) { - shape.getTextParagraphs().get(0).setBullet(nr); - assertNotNull(shape.getText()); - } - - shape.getTextParagraphs().get(0).setBullet(false); - assertNotNull(shape.getText()); - - shape.setText("testtext"); - assertEquals("testtext", shape.getText()); - - shape.setText(new XSSFRichTextString()); - assertEquals("null", shape.getText()); - - shape.addNewTextParagraph(); - shape.addNewTextParagraph("test-other-text"); - shape.addNewTextParagraph(new XSSFRichTextString("rtstring")); - shape.addNewTextParagraph(new XSSFRichTextString()); - assertEquals("null\n\ntest-other-text\nrtstring\nnull", shape.getText()); - - XDDFTextBody body = shape.getTextBody(); - assertNotNull(body); - List<XDDFTextParagraph> paragraphs = body.getParagraphs(); - assertEquals(5, paragraphs.size()); - assertEquals("null", body.getParagraph(0).getText()); - assertEquals("", body.getParagraph(1).getText()); - assertEquals("test-other-text", body.getParagraph(2).getText()); - assertEquals("rtstring", body.getParagraph(3).getText()); - assertEquals("null", body.getParagraph(4).getText()); - - assertEquals(TextHorizontalOverflow.OVERFLOW, shape.getTextHorizontalOverflow()); - shape.setTextHorizontalOverflow(TextHorizontalOverflow.CLIP); - assertEquals(TextHorizontalOverflow.CLIP, shape.getTextHorizontalOverflow()); - shape.setTextHorizontalOverflow(TextHorizontalOverflow.OVERFLOW); - assertEquals(TextHorizontalOverflow.OVERFLOW, shape.getTextHorizontalOverflow()); - shape.setTextHorizontalOverflow(null); - assertEquals(TextHorizontalOverflow.OVERFLOW, shape.getTextHorizontalOverflow()); - shape.setTextHorizontalOverflow(null); - assertEquals(TextHorizontalOverflow.OVERFLOW, shape.getTextHorizontalOverflow()); - - assertEquals(TextVerticalOverflow.OVERFLOW, shape.getTextVerticalOverflow()); - shape.setTextVerticalOverflow(TextVerticalOverflow.CLIP); - assertEquals(TextVerticalOverflow.CLIP, shape.getTextVerticalOverflow()); - shape.setTextVerticalOverflow(TextVerticalOverflow.OVERFLOW); - assertEquals(TextVerticalOverflow.OVERFLOW, shape.getTextVerticalOverflow()); - shape.setTextVerticalOverflow(null); - assertEquals(TextVerticalOverflow.OVERFLOW, shape.getTextVerticalOverflow()); - shape.setTextVerticalOverflow(null); - assertEquals(TextVerticalOverflow.OVERFLOW, shape.getTextVerticalOverflow()); - - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - shape.setVerticalAlignment(VerticalAlignment.BOTTOM); - assertEquals(VerticalAlignment.BOTTOM, shape.getVerticalAlignment()); - shape.setVerticalAlignment(VerticalAlignment.TOP); - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - shape.setVerticalAlignment(null); - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - shape.setVerticalAlignment(null); - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - shape.setTextDirection(TextDirection.STACKED); - assertEquals(TextDirection.STACKED, shape.getTextDirection()); - shape.setTextDirection(TextDirection.HORIZONTAL); - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - shape.setTextDirection(null); - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - shape.setTextDirection(null); - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - - XDDFBodyProperties props = body.getBodyProperties(); - assertNotNull(props); - - assertEquals(3.6, shape.getBottomInset(), 0.01); - assertNull(props.getBottomInset()); - shape.setBottomInset(12.32); - assertEquals(12.32, shape.getBottomInset(), 0.01); - assertEquals(12.32, props.getBottomInset(), 0.01); - shape.setBottomInset(-1); - assertEquals(3.6, shape.getBottomInset(), 0.01); - assertNull(props.getBottomInset()); - shape.setBottomInset(-1); - assertEquals(3.6, shape.getBottomInset(), 0.01); - assertNull(props.getBottomInset()); - - assertEquals(3.6, shape.getLeftInset(), 0.01); - assertNull(props.getLeftInset()); - shape.setLeftInset(12.31); - assertEquals(12.31, shape.getLeftInset(), 0.01); - assertEquals(12.31, props.getLeftInset(), 0.01); - shape.setLeftInset(-1); - assertEquals(3.6, shape.getLeftInset(), 0.01); - assertNull(props.getLeftInset()); - shape.setLeftInset(-1); - assertEquals(3.6, shape.getLeftInset(), 0.01); - assertNull(props.getLeftInset()); - - assertEquals(3.6, shape.getRightInset(), 0.01); - assertNull(props.getRightInset()); - shape.setRightInset(13.31); - assertEquals(13.31, shape.getRightInset(), 0.01); - assertEquals(13.31, props.getRightInset(), 0.01); - shape.setRightInset(-1); - assertEquals(3.6, shape.getRightInset(), 0.01); - assertNull(props.getRightInset()); - shape.setRightInset(-1); - assertEquals(3.6, shape.getRightInset(), 0.01); - assertNull(props.getRightInset()); - - assertEquals(3.6, shape.getTopInset(), 0.01); - assertNull(props.getTopInset()); - shape.setTopInset(23.31); - assertEquals(23.31, shape.getTopInset(), 0.01); - assertEquals(23.31, props.getTopInset(), 0.01); - shape.setTopInset(-1); - assertEquals(3.6, shape.getTopInset(), 0.01); - assertNull(props.getTopInset()); - shape.setTopInset(-1); - assertEquals(3.6, shape.getTopInset(), 0.01); - assertNull(props.getTopInset()); - - assertTrue(shape.getWordWrap()); - shape.setWordWrap(false); - assertFalse(shape.getWordWrap()); - shape.setWordWrap(true); - assertTrue(shape.getWordWrap()); - - assertEquals(TextAutofit.NORMAL, shape.getTextAutofit()); - assertTrue(props.getAutoFit() instanceof XDDFNormalAutoFit); - shape.setTextAutofit(TextAutofit.NORMAL); - assertEquals(TextAutofit.NORMAL, shape.getTextAutofit()); - assertTrue(props.getAutoFit() instanceof XDDFNormalAutoFit); - shape.setTextAutofit(TextAutofit.SHAPE); - assertEquals(TextAutofit.SHAPE, shape.getTextAutofit()); - assertTrue(props.getAutoFit() instanceof XDDFShapeAutoFit); - shape.setTextAutofit(TextAutofit.NONE); - assertEquals(TextAutofit.NONE, shape.getTextAutofit()); - assertTrue(props.getAutoFit() instanceof XDDFNoAutoFit); - - assertEquals(5, shape.getShapeType()); - shape.setShapeType(23); - assertEquals(23, shape.getShapeType()); - - // TODO: should this be supported? - // shape.setShapeType(-1); - // assertEquals(-1, shape.getShapeType()); - // shape.setShapeType(-1); - // assertEquals(-1, shape.getShapeType()); - - assertNotNull(shape.getShapeProperties()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTable.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTable.java deleted file mode 100644 index 83763bec73..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTable.java +++ /dev/null @@ -1,625 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -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; -import org.junit.jupiter.api.Test; -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 - void bug56274() throws IOException { - // read sample file - try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("56274.xlsx")) { - - // read the original sheet header order - XSSFRow row = wb1.getSheetAt(0).getRow(0); - List<String> headers = new ArrayList<>(); - for (Cell cell : row) { - headers.add(cell.getStringCellValue()); - } - - // save the worksheet as-is using SXSSF - File outputFile = TempFile.createTempFile("poi-56274", ".xlsx"); - SXSSFWorkbook outputWorkbook = new SXSSFWorkbook(wb1); - FileOutputStream fos = new FileOutputStream(outputFile); - outputWorkbook.write(fos); - fos.close(); - outputWorkbook.close(); - - // re-read the saved file and make sure headers in the xml are in the original order - FileInputStream fis = new FileInputStream(outputFile); - XSSFWorkbook wb2 = new XSSFWorkbook(fis); - fis.close(); - CTTable ctTable = wb2.getSheetAt(0).getTables().get(0).getCTTable(); - CTTableColumn[] ctTableColumnArray = ctTable.getTableColumns().getTableColumnArray(); - - assertEquals(headers.size(), ctTableColumnArray.length, - "number of headers in xml table should match number of header cells in worksheet"); - for (int i = 0; i < headers.size(); i++) { - assertEquals(headers.get(i), ctTableColumnArray[i].getName(), - "header name in xml table should match number of header cells in worksheet"); - } - assertTrue(outputFile.delete()); - wb2.close(); - } - } - - @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(); - } - - @Test - void findColumnIndex() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - - XSSFTable table = wb.getTable("\\_Prime.1"); - assertNotNull(table); - assertEquals(0, table.findColumnIndex("calc='#*'#"), "column header has special escaped characters"); - assertEquals(1, table.findColumnIndex("Name")); - assertEquals(2, table.findColumnIndex("Number")); - - assertEquals(2, table.findColumnIndex("NuMbEr"), "case insensitive"); - - // findColumnIndex should return -1 if no column header name matches - assertEquals(-1, table.findColumnIndex(null)); - assertEquals(-1, table.findColumnIndex("")); - assertEquals(-1, table.findColumnIndex("one")); - } - } - - @Test - void findColumnIndexIsRelativeToTableNotSheet() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("DataTableCities.xlsx")) { - XSSFTable table = wb.getTable("SmallCity"); - - // Make sure that XSSFTable.findColumnIndex returns the column index relative to the first - // column in the table, not the column number in the sheet - assertEquals(0, table.findColumnIndex("City")); // column I in worksheet but 0th column in table - assertEquals(1, table.findColumnIndex("Latitude")); - assertEquals(2, table.findColumnIndex("Longitude")); - assertEquals(3, table.findColumnIndex("Population")); - } - } - - @Test - void getSheetName() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals("Table", table.getSheetName()); - } - } - - @Test - void isHasTotalsRow() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - XSSFTable table = wb.getTable("\\_Prime.1"); - assertFalse(table.getTotalsRowCount() > 0); - } - } - - @Test - void getStartColIndex() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(0, table.getStartColIndex()); - } - } - - @Test - void getEndColIndex() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(2, table.getEndColIndex()); - } - } - - @Test - void getStartRowIndex() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(0, table.getStartRowIndex()); - } - } - - @Test - void getEndRowIndex() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(6, table.getEndRowIndex()); - } - } - - @Test - void getStartCellReference() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(new CellReference("A1"), table.getStartCellReference()); - } - } - - @Test - void getEndCellReference() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(new CellReference("C7"), table.getEndCellReference()); - } - } - - @Test - void getEndCellReferenceFromSingleCellTable() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("SingleCellTable.xlsx")) { - XSSFTable table = wb.getTable("Table3"); - assertEquals(new CellReference("A2"), table.getEndCellReference()); - } - } - - @Test - void getColumnCount() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(3, table.getColumnCount()); - } - } - - @Test - void getAndSetDisplayName() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) { - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals("\\_Prime.1", table.getDisplayName()); - - table.setDisplayName("Display name"); - assertEquals("Display name", table.getDisplayName()); - assertEquals("\\_Prime.1", table.getName()); // name and display name are different - } - } - - @Test - void getCellReferences() throws IOException { - // make sure that cached start and end cell references - // can be synchronized with the underlying CTTable - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sh = wb.createSheet(); - XSSFTable table = sh.createTable(null); - assertNotNull(table.getDisplayName()); - assertNotNull(table.getCTTable().getDisplayName()); - CTTable ctTable = table.getCTTable(); - ctTable.setRef("B2:E8"); - - assertEquals(new CellReference("B2"), table.getStartCellReference()); - assertEquals(new CellReference("E8"), table.getEndCellReference()); - - // At this point start and end cell reference are cached - // and may not follow changes to the underlying CTTable - ctTable.setRef("C1:M3"); - - assertEquals(new CellReference("B2"), table.getStartCellReference()); - assertEquals(new CellReference("E8"), table.getEndCellReference()); - - // Force a synchronization between CTTable and XSSFTable - // start and end cell references - table.updateReferences(); - - assertEquals(new CellReference("C1"), table.getStartCellReference()); - assertEquals(new CellReference("M3"), table.getEndCellReference()); - - IOUtils.closeQuietly(wb); - } - } - - @Test - void getRowCount() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sh = wb.createSheet(); - XSSFTable table = sh.createTable(null); - CTTable ctTable = table.getCTTable(); - - assertEquals(0, table.getRowCount()); - - ctTable.setRef("B2:B2"); - // update cell references to clear the cache - table.updateReferences(); - assertEquals(1, table.getRowCount()); - - ctTable.setRef("B2:B12"); - // update cell references to clear the cache - table.updateReferences(); - assertEquals(11, table.getRowCount()); - - IOUtils.closeQuietly(wb); - } - } - - @Test - void testGetDataRowCount() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sh = wb.createSheet(); - AreaReference tableArea = new AreaReference("B2:B6", wb.getSpreadsheetVersion()); - XSSFTable table = sh.createTable(tableArea); - - assertEquals(5, table.getRowCount()); // includes column header - assertEquals(4, table.getDataRowCount()); - - table.setArea(new AreaReference("B2:B7", wb.getSpreadsheetVersion())); - - assertEquals(6, table.getRowCount()); - assertEquals(5, table.getDataRowCount()); - - IOUtils.closeQuietly(wb); - } - } - - @Test - void testSetDataRowCount() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sh = wb.createSheet(); - - // 1 header row + 1 data row - AreaReference tableArea = new AreaReference("C10:C11", wb.getSpreadsheetVersion()); - XSSFTable table = sh.createTable(tableArea); - - assertEquals(2, table.getRowCount()); // includes all data and header/footer rows - - assertEquals(1, table.getHeaderRowCount()); - assertEquals(1, table.getDataRowCount()); - assertEquals(0, table.getTotalsRowCount()); - - table.setDataRowCount(5); - - assertEquals(6, table.getRowCount()); - - assertEquals(1, table.getHeaderRowCount()); - assertEquals(5, table.getDataRowCount()); - assertEquals(0, table.getTotalsRowCount()); - - assertEquals("C10:C15", table.getArea().formatAsString()); - - IOUtils.closeQuietly(wb); - } - } - - @Test - void testCreateTableIds() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - AreaReference reference1 = wb.getCreationHelper().createAreaReference( - new CellReference(0, 0), new CellReference(2, 2)); - - XSSFTable table1 = sheet.createTable(reference1); - assertEquals("A1:C3", table1.getCTTable().getRef()); - assertNotNull(table1.getDisplayName()); - assertNotNull(table1.getCTTable().getDisplayName()); - - assertEquals(1, table1.getCTTable().getTableColumns().getTableColumnArray(0).getId()); - assertEquals(2, table1.getCTTable().getTableColumns().getTableColumnArray(1).getId()); - assertEquals(3, table1.getCTTable().getTableColumns().getTableColumnArray(2).getId()); - - assertEquals(1, table1.getCTTable().getId()); - - AreaReference reference2 = wb.getCreationHelper().createAreaReference( - new CellReference(10, 10), new CellReference(12, 12)); - - XSSFTable table2 = sheet.createTable(reference2); - assertEquals("K11:M13", table2.getCTTable().getRef()); - - // these IDs duplicate those from table1 and may be cause of https://bz.apache.org/bugzilla/show_bug.cgi?id=62906 - assertEquals(1, table2.getCTTable().getTableColumns().getTableColumnArray(0).getId()); - assertEquals(2, table2.getCTTable().getTableColumns().getTableColumnArray(1).getId()); - assertEquals(3, table2.getCTTable().getTableColumns().getTableColumnArray(2).getId()); - - assertEquals(2, table2.getCTTable().getId()); - } - } - - @Test - void testSetArea() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sh = wb.createSheet(); - - AreaReference tableArea = new AreaReference("B10:D12", wb.getSpreadsheetVersion()); - XSSFTable table = sh.createTable(tableArea); - - assertEquals(3, table.getColumnCount()); - assertEquals(3, table.getRowCount()); - - // move table without resizing, shouldn't change row or column count - AreaReference tableArea2 = new AreaReference("B11:D13", wb.getSpreadsheetVersion()); - table.setArea(tableArea2); - - assertEquals(3, table.getColumnCount()); - assertEquals(3, table.getRowCount()); - - // increase size by 1 row and 1 column - AreaReference tableArea3 = new AreaReference("B11:E14", wb.getSpreadsheetVersion()); - table.setArea(tableArea3); - - assertEquals(4, table.getColumnCount()); - assertEquals(4, table.getRowCount()); - - // reduce size by 2 rows and 2 columns - AreaReference tableArea4 = new AreaReference("C12:D13", wb.getSpreadsheetVersion()); - table.setArea(tableArea4); - - assertEquals(2, table.getColumnCount()); - assertEquals(2, table.getRowCount()); - } - } - - @Test - void testCreateColumn() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sh = wb.createSheet(); - - AreaReference tableArea = new AreaReference("A2:A3", wb.getSpreadsheetVersion()); - XSSFTable table = sh.createTable(tableArea); - - assertEquals(1, table.getColumnCount()); - assertEquals(2, table.getRowCount()); - - // add columns - XSSFTableColumn c1 = table.getColumns().get(0); - XSSFTableColumn cB = table.createColumn("Column B"); - XSSFTableColumn cD = table.createColumn("Column D"); - XSSFTableColumn cC = table.createColumn("Column C", 2); // add between B and D - table.updateReferences(); - table.updateHeaders(); - - assertEquals(4, table.getColumnCount()); - assertEquals(2, table.getRowCount()); - - // column IDs start at 1, and increase in the order columns are added (see bug #62740) - assertEquals(1, c1.getId(), "Column c ID"); - assertTrue (c1.getId() < cB.getId(), "Column B ID"); - 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"); - } - } - - @Test - void testCreateColumnInvalidIndex() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sh = wb.createSheet(); - AreaReference tableArea = new AreaReference("D2:D3", wb.getSpreadsheetVersion()); - XSSFTable table = sh.createTable(tableArea); - - // add columns - table.createColumn("Column 2", 1); - // out of bounds - assertThrows(IllegalArgumentException.class, () -> table.createColumn("Column 3", 3)); - } - } - - @Test - void testDifferentHeaderTypes() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("TablesWithDifferentHeaders.xlsx")) { - assertEquals(3, wb.getNumberOfSheets()); - XSSFSheet s; - XSSFTable t; - - // TODO Nicer column fetching - - s = wb.getSheet("IntHeaders"); - assertEquals(1, s.getTables().size()); - t = s.getTables().get(0); - assertEquals("A1:B2", t.getCellReferences().formatAsString()); - assertEquals("12", t.getCTTable().getTableColumns().getTableColumnArray(0).getName()); - assertEquals("34", t.getCTTable().getTableColumns().getTableColumnArray(1).getName()); - - s = wb.getSheet("FloatHeaders"); - assertEquals(1, s.getTables().size()); - t = s.getTables().get(0); - assertEquals("A1:B2", t.getCellReferences().formatAsString()); - assertEquals("12.34", t.getCTTable().getTableColumns().getTableColumnArray(0).getName()); - assertEquals("34.56", t.getCTTable().getTableColumns().getTableColumnArray(1).getName()); - - s = wb.getSheet("NoExplicitHeaders"); - assertEquals(1, s.getTables().size()); - t = s.getTables().get(0); - assertEquals("A1:B3", t.getCellReferences().formatAsString()); - assertEquals("Column1", t.getCTTable().getTableColumns().getTableColumnArray(0).getName()); - assertEquals("Column2", t.getCTTable().getTableColumns().getTableColumnArray(1).getName()); - } - } - - /** - * See https://stackoverflow.com/questions/44407111/apache-poi-cant-format-filled-cells-as-numeric - */ - @Test - void testNumericCellsInTable() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet s = wb.createSheet(); - - // Create some cells, some numeric, some not - Cell c1 = s.createRow(0).createCell(0); - Cell c2 = s.getRow(0).createCell(1); - Cell c3 = s.getRow(0).createCell(2); - Cell c4 = s.createRow(1).createCell(0); - Cell c5 = s.getRow(1).createCell(1); - Cell c6 = s.getRow(1).createCell(2); - c1.setCellValue(12); - c2.setCellValue(34.56); - c3.setCellValue("ABCD"); - c4.setCellValue("AB"); - c5.setCellValue("CD"); - c6.setCellValue("EF"); - - // Setting up the table - XSSFTable t = s.createTable(new AreaReference("A1:C3", wb.getSpreadsheetVersion())); - t.setName("TableTest"); - t.setDisplayName("CT_Table_Test"); - t.createColumn("Column 1"); - t.createColumn("Column 2"); - t.createColumn("Column 3"); - t.setCellReferences(wb.getCreationHelper().createAreaReference( - new CellReference(c1), new CellReference(c6) - )); - - // 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); - } - } - - @Test - void testSetDisplayName() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - AreaReference reference1 = wb.getCreationHelper().createAreaReference( - new CellReference(0, 0), new CellReference(2, 2)); - - XSSFTable table1 = sheet.createTable(reference1); - table1.setDisplayName("TableTest"); - assertEquals("TableTest", table1.getDisplayName()); - assertEquals("TableTest", table1.getCTTable().getDisplayName()); - } - } - - @Test - void testSetDisplayNameNull() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - AreaReference reference1 = wb.getCreationHelper().createAreaReference( - new CellReference(0, 0), new CellReference(2, 2)); - - XSSFTable table1 = sheet.createTable(reference1); - assertThrows(IllegalArgumentException.class, () -> table1.setDisplayName(null)); - } - } - - @Test - void testSetDisplayNameEmpty() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - - AreaReference reference1 = wb.getCreationHelper().createAreaReference( - new CellReference(0, 0), new CellReference(2, 2)); - - XSSFTable table1 = sheet.createTable(reference1); - assertThrows(IllegalArgumentException.class, () -> table1.setDisplayName("")); - } - } - - /** - * Delete table2, and create a named range in sheet0; it should automatically be assigned the name "Table4" - */ - @Test - void testBug63401And62906() throws IOException { - try (XSSFWorkbook workbook = new XSSFWorkbook()) { - XSSFSheet sheet0 = workbook.createSheet(); - XSSFTable table = addTable(sheet0, 3, 0, 2, 2); - assertNotNull(table); - - // final String procName = "testXSSFTableGetName"; - // final String name = table.getName(); - // System.out.printf(Locale.ROOT, "%s: table.getName=%s%n", procName, name); - } - } - - private static XSSFTable addTable(XSSFSheet sheet,int nRow, int nCol, int nNumRows, int nNumCols) { - for (int i = 0; i < nNumRows; i++) { - XSSFRow row = sheet.createRow(i + nRow); - for (int j = 0; j < nNumCols; j++) { - XSSFCell localXSSFCell = row.createCell(j + nCol); - if (i == 0) { - localXSSFCell.setCellValue(String.format(Locale.ROOT, "Col%d", j + 1)); - } else { - localXSSFCell.setCellValue(String.format(Locale.ROOT, "(%d,%d)", i + 1, j + 1)); - } - } - } - final CellReference upperLeft = new CellReference(nRow, nCol); - final CellReference lowerRight = new CellReference(nNumRows - 1, nNumCols - 1); - final AreaReference area = new AreaReference(upperLeft, lowerRight, SpreadsheetVersion.EXCEL2007); - return sheet.createTable(area); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTableColumn.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTableColumn.java deleted file mode 100644 index 8d641ca4dc..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTableColumn.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -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 java.io.IOException; -import java.util.List; - -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Test; - -public final class TestXSSFTableColumn { - - @Test - void testGetColumnName() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("CustomXMLMappings-complex-type.xlsx")) { - XSSFTable table = wb.getTable("Tabella2"); - - List<XSSFTableColumn> tableColumns = table.getColumns(); - - assertEquals("ID", tableColumns.get(0).getName()); - assertEquals("Unmapped Column", tableColumns.get(1).getName()); - assertEquals("SchemaRef", tableColumns.get(2).getName()); - assertEquals("Namespace", tableColumns.get(3).getName()); - - } - } - - @Test - void testGetColumnIndex() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("CustomXMLMappings-complex-type.xlsx")) { - XSSFTable table = wb.getTable("Tabella2"); - - List<XSSFTableColumn> tableColumns = table.getColumns(); - - assertEquals(0, tableColumns.get(0).getColumnIndex()); - assertEquals(1, tableColumns.get(1).getColumnIndex()); - assertEquals(2, tableColumns.get(2).getColumnIndex()); - assertEquals(3, tableColumns.get(3).getColumnIndex()); - - } - } - - @Test - void testGetXmlColumnPrs() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("CustomXMLMappings-complex-type.xlsx")) { - XSSFTable table = wb.getTable("Tabella2"); - - List<XSSFTableColumn> tableColumns = table.getColumns(); - - assertNotNull(tableColumns.get(0).getXmlColumnPr()); - assertNull(tableColumns.get(1).getXmlColumnPr()); // unmapped column - assertEquals(2, tableColumns.get(2).getColumnIndex()); - assertEquals(3, tableColumns.get(3).getColumnIndex()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java deleted file mode 100644 index ec13f604be..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java +++ /dev/null @@ -1,195 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import java.awt.Color; -import java.io.IOException; -import java.util.List; - -import org.junit.jupiter.api.Test; - -class TestXSSFTextParagraph { - @Test - void testXSSFTextParagraph() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - - XSSFFont font = wb.createFont(); - Color color = new Color(0, 255, 255); - font.setColor(new XSSFColor(color, wb.getStylesSource().getIndexedColors())); - font.setFontName("Arial"); - rt.applyFont(font); - - shape.setText(rt); - - List<XSSFTextParagraph> paras = shape.getTextParagraphs(); - assertEquals(1, paras.size()); - - XSSFTextParagraph text = paras.get(0); - assertEquals("Test String", text.getText()); - - assertFalse(text.isBullet()); - assertNotNull(text.getXmlObject()); - assertEquals(shape.getCTShape(), text.getParentShape()); - assertNotNull(text.iterator()); - assertNotNull(text.addLineBreak()); - - assertNotNull(text.getTextRuns()); - assertEquals(2, text.getTextRuns().size()); - text.addNewTextRun(); - assertEquals(3, text.getTextRuns().size()); - - assertEquals(TextAlign.LEFT, text.getTextAlign()); - text.setTextAlign(null); - assertEquals(TextAlign.LEFT, text.getTextAlign()); - text.setTextAlign(TextAlign.CENTER); - assertEquals(TextAlign.CENTER, text.getTextAlign()); - text.setTextAlign(TextAlign.RIGHT); - assertEquals(TextAlign.RIGHT, text.getTextAlign()); - text.setTextAlign(null); - assertEquals(TextAlign.LEFT, text.getTextAlign()); - - text.setTextFontAlign(TextFontAlign.BASELINE); - assertEquals(TextFontAlign.BASELINE, text.getTextFontAlign()); - text.setTextFontAlign(TextFontAlign.BOTTOM); - assertEquals(TextFontAlign.BOTTOM, text.getTextFontAlign()); - text.setTextFontAlign(null); - assertEquals(TextFontAlign.BASELINE, text.getTextFontAlign()); - text.setTextFontAlign(null); - assertEquals(TextFontAlign.BASELINE, text.getTextFontAlign()); - - assertNull(text.getBulletFont()); - text.setBulletFont("Arial"); - assertEquals("Arial", text.getBulletFont()); - - assertNull(text.getBulletCharacter()); - text.setBulletCharacter("."); - assertEquals(".", text.getBulletCharacter()); - - assertNull(text.getBulletFontColor()); - text.setBulletFontColor(color); - assertEquals(color, text.getBulletFontColor()); - - assertEquals(100.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(1.0); - assertEquals(1.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(1.0); - assertEquals(1.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(-9.0); - assertEquals(-9.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(-9.0); - assertEquals(-9.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(1.0); - assertEquals(1.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(-9.0); - assertEquals(-9.0, text.getBulletFontSize(), 0.01); - - assertEquals(0.0, text.getIndent(), 0.01); - text.setIndent(2.0); - assertEquals(2.0, text.getIndent(), 0.01); - text.setIndent(-1.0); - assertEquals(0.0, text.getIndent(), 0.01); - text.setIndent(-1.0); - assertEquals(0.0, text.getIndent(), 0.01); - - assertEquals(0.0, text.getLeftMargin(), 0.01); - text.setLeftMargin(3.0); - assertEquals(3.0, text.getLeftMargin(), 0.01); - text.setLeftMargin(-1.0); - assertEquals(0.0, text.getLeftMargin(), 0.01); - text.setLeftMargin(-1.0); - assertEquals(0.0, text.getLeftMargin(), 0.01); - - assertEquals(0.0, text.getRightMargin(), 0.01); - text.setRightMargin(4.5); - assertEquals(4.5, text.getRightMargin(), 0.01); - text.setRightMargin(-1.0); - assertEquals(0.0, text.getRightMargin(), 0.01); - text.setRightMargin(-1.0); - assertEquals(0.0, text.getRightMargin(), 0.01); - - assertEquals(0.0, text.getDefaultTabSize(), 0.01); - - assertEquals(0.0, text.getTabStop(0), 0.01); - text.addTabStop(3.14); - assertEquals(3.14, text.getTabStop(0), 0.01); - - assertEquals(100.0, text.getLineSpacing(), 0.01); - text.setLineSpacing(3.15); - assertEquals(3.15, text.getLineSpacing(), 0.01); - text.setLineSpacing(-2.13); - assertEquals(-2.13, text.getLineSpacing(), 0.01); - - assertEquals(0.0, text.getSpaceBefore(), 0.01); - text.setSpaceBefore(3.17); - assertEquals(3.17, text.getSpaceBefore(), 0.01); - text.setSpaceBefore(-4.7); - assertEquals(-4.7, text.getSpaceBefore(), 0.01); - - assertEquals(0.0, text.getSpaceAfter(), 0.01); - text.setSpaceAfter(6.17); - assertEquals(6.17, text.getSpaceAfter(), 0.01); - text.setSpaceAfter(-8.17); - assertEquals(-8.17, text.getSpaceAfter(), 0.01); - - assertEquals(0, text.getLevel()); - text.setLevel(1); - assertEquals(1, text.getLevel()); - text.setLevel(4); - assertEquals(4, text.getLevel()); - - assertTrue(text.isBullet()); - assertFalse(text.isBulletAutoNumber()); - text.setBullet(false); - text.setBullet(false); - assertFalse(text.isBullet()); - assertFalse(text.isBulletAutoNumber()); - text.setBullet(true); - assertTrue(text.isBullet()); - assertFalse(text.isBulletAutoNumber()); - assertEquals(0, text.getBulletAutoNumberStart()); - assertEquals(ListAutoNumber.ARABIC_PLAIN, text.getBulletAutoNumberScheme()); - - text.setBullet(false); - assertFalse(text.isBullet()); - text.setBullet(ListAutoNumber.CIRCLE_NUM_DB_PLAIN); - assertTrue(text.isBullet()); - assertTrue(text.isBulletAutoNumber()); - assertEquals(0, text.getBulletAutoNumberStart()); - assertEquals(ListAutoNumber.CIRCLE_NUM_DB_PLAIN, text.getBulletAutoNumberScheme()); - text.setBullet(false); - assertFalse(text.isBullet()); - assertFalse(text.isBulletAutoNumber()); - text.setBullet(ListAutoNumber.CIRCLE_NUM_WD_BLACK_PLAIN, 10); - assertTrue(text.isBullet()); - assertTrue(text.isBulletAutoNumber()); - assertEquals(10, text.getBulletAutoNumberStart()); - assertEquals(ListAutoNumber.CIRCLE_NUM_WD_BLACK_PLAIN, text.getBulletAutoNumberScheme()); - - - assertNotNull(text.toString()); - - new XSSFTextParagraph(text.getXmlObject(), shape.getCTShape()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java deleted file mode 100644 index 74434b164b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java +++ /dev/null @@ -1,135 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import java.awt.Color; -import java.io.IOException; -import java.util.List; - -import org.junit.jupiter.api.Test; - -class TestXSSFTextRun { - @Test - void testXSSFTextParagraph() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - - XSSFTextParagraph para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 1"); - - List<XSSFTextRun> runs = para.getTextRuns(); - assertEquals(1, runs.size()); - XSSFTextRun run = runs.get(0); - assertEquals("Line 1", run.getText()); - - assertNotNull(run.getParentParagraph()); - assertNotNull(run.getXmlObject()); - assertNotNull(run.getRPr()); - - assertEquals(new Color(0, 0, 0), run.getFontColor()); - - Color color = new Color(0, 255, 255); - run.setFontColor(color); - assertEquals(color, run.getFontColor()); - - assertEquals(11.0, run.getFontSize(), 0.01); - run.setFontSize(12.32); - assertEquals(12.32, run.getFontSize(), 0.01); - run.setFontSize(-1.0); - assertEquals(11.0, run.getFontSize(), 0.01); - run.setFontSize(-1.0); - assertEquals(11.0, run.getFontSize(), 0.01); - IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> run.setFontSize(0.9)); - assertTrue(e.getMessage().contains("0.9")); - assertEquals(11.0, run.getFontSize(), 0.01); - - assertEquals(0.0, run.getCharacterSpacing(), 0.01); - run.setCharacterSpacing(12.31); - assertEquals(12.31, run.getCharacterSpacing(), 0.01); - run.setCharacterSpacing(0.0); - assertEquals(0.0, run.getCharacterSpacing(), 0.01); - run.setCharacterSpacing(0.0); - assertEquals(0.0, run.getCharacterSpacing(), 0.01); - - assertEquals("Calibri", run.getFontFamily()); - run.setFontFamily("Arial", (byte) 1, (byte) 1, false); - assertEquals("Arial", run.getFontFamily()); - run.setFontFamily("Arial", (byte) -1, (byte) 1, false); - assertEquals("Arial", run.getFontFamily()); - run.setFontFamily("Arial", (byte) 1, (byte) -1, false); - assertEquals("Arial", run.getFontFamily()); - run.setFontFamily("Arial", (byte) 1, (byte) 1, true); - assertEquals("Arial", run.getFontFamily()); - run.setFontFamily(null, (byte) 1, (byte) 1, false); - assertEquals("Calibri", run.getFontFamily()); - run.setFontFamily(null, (byte) 1, (byte) 1, false); - assertEquals("Calibri", run.getFontFamily()); - - run.setFont("Arial"); - assertEquals("Arial", run.getFontFamily()); - - assertEquals((byte) 0, run.getPitchAndFamily()); - run.setFont(null); - assertEquals((byte) 0, run.getPitchAndFamily()); - - assertFalse(run.isStrikethrough()); - run.setStrikethrough(true); - assertTrue(run.isStrikethrough()); - run.setStrikethrough(false); - assertFalse(run.isStrikethrough()); - - assertFalse(run.isSuperscript()); - run.setSuperscript(true); - assertTrue(run.isSuperscript()); - run.setSuperscript(false); - assertFalse(run.isSuperscript()); - - assertFalse(run.isSubscript()); - run.setSubscript(true); - assertTrue(run.isSubscript()); - run.setSubscript(false); - assertFalse(run.isSubscript()); - - assertEquals(TextCap.NONE, run.getTextCap()); - - assertFalse(run.isBold()); - run.setBold(true); - assertTrue(run.isBold()); - run.setBold(false); - assertFalse(run.isBold()); - - assertFalse(run.isItalic()); - run.setItalic(true); - assertTrue(run.isItalic()); - run.setItalic(false); - assertFalse(run.isItalic()); - - assertFalse(run.isUnderline()); - run.setUnderline(true); - assertTrue(run.isUnderline()); - run.setUnderline(false); - assertFalse(run.isUnderline()); - - assertNotNull(run.toString()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFUnicodeSurrogates.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFUnicodeSurrogates.java deleted file mode 100644 index 506e0dead8..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFUnicodeSurrogates.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.TempFile; -import org.junit.jupiter.api.Test; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -class TestXSSFUnicodeSurrogates { - - // "𝝊𝝋𝝌𝝍𝝎𝝏𝝐𝝑𝝒𝝓𝝔𝝕𝝖𝝗𝝘𝝙𝝚𝝛𝝜𝝝𝝞𝝟𝝠𝝡𝝢𝝣𝝤𝝥𝝦𝝧𝝨𝝩𝝪𝝫𝝬𝝭𝝮𝝯𝝰𝝱𝝲𝝳𝝴𝝵𝝶𝝷𝝸𝝹𝝺"; - private static final String unicodeText = - "\uD835\uDF4A\uD835\uDF4B\uD835\uDF4C\uD835\uDF4D\uD835\uDF4E\uD835\uDF4F\uD835\uDF50\uD835" + - "\uDF51\uD835\uDF52\uD835\uDF53\uD835\uDF54\uD835\uDF55\uD835\uDF56\uD835\uDF57\uD835\uDF58" + - "\uD835\uDF59\uD835\uDF5A\uD835\uDF5B\uD835\uDF5C\uD835\uDF5D\uD835\uDF5E\uD835\uDF5F\uD835" + - "\uDF60\uD835\uDF61\uD835\uDF62\uD835\uDF63\uD835\uDF64\uD835\uDF65\uD835\uDF66\uD835\uDF67" + - "\uD835\uDF68\uD835\uDF69\uD835\uDF6A\uD835\uDF6B\uD835\uDF6C\uD835\uDF6D\uD835\uDF6E\uD835" + - "\uDF6F\uD835\uDF70\uD835\uDF71\uD835\uDF72\uD835\uDF73\uD835\uDF74\uD835\uDF75\uD835\uDF76" + - "\uD835\uDF77\uD835\uDF78\uD835\uDF79\uD835\uDF7A"; - - @Test - void testWriteUnicodeSurrogates() throws IOException { - String sheetName = "Sheet1"; - File tf = TempFile.createTempFile("poi-xmlbeans-test", ".xlsx"); - try (XSSFWorkbook wb = new XSSFWorkbook()) { - Sheet sheet = wb.createSheet(sheetName); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(unicodeText); - try (FileOutputStream os = new FileOutputStream(tf)) { - wb.write(os); - } - try (FileInputStream fis = new FileInputStream(tf); - XSSFWorkbook wb2 = new XSSFWorkbook(fis)) { - Sheet sheet2 = wb2.getSheet(sheetName); - Cell cell2 = sheet2.getRow(0).getCell(0); - assertEquals(unicodeText, cell2.getStringCellValue()); - } - } finally { - tf.delete(); - } - } -} - diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java deleted file mode 100644 index 3bd3012ef5..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java +++ /dev/null @@ -1,213 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; -import static org.apache.poi.xssf.usermodel.XSSFVMLDrawing.QNAME_VMLDRAWING; -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.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.List; -import java.util.regex.Pattern; - -import com.microsoft.schemas.office.excel.CTClientData; -import com.microsoft.schemas.office.excel.STObjectType; -import com.microsoft.schemas.office.office.CTShapeLayout; -import com.microsoft.schemas.office.office.STConnectType; -import com.microsoft.schemas.office.office.STInsetMode; -import com.microsoft.schemas.vml.CTShadow; -import com.microsoft.schemas.vml.CTShape; -import com.microsoft.schemas.vml.CTShapetype; -import com.microsoft.schemas.vml.STExt; -import com.microsoft.schemas.vml.STStrokeJoinStyle; -import com.microsoft.schemas.vml.impl.CTShapetypeImpl; -import org.apache.poi.POIDataSamples; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STTrueFalse; -import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STTrueFalseBlank; - -class TestXSSFVMLDrawing { - - @Test - void testNew() throws IOException, XmlException { - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - List<XmlObject> items = vml.getItems(); - assertEquals(2, items.size()); - assertTrue(items.get(0) instanceof CTShapeLayout); - CTShapeLayout layout = (CTShapeLayout)items.get(0); - assertEquals(STExt.EDIT, layout.getExt()); - assertEquals(STExt.EDIT, layout.getIdmap().getExt()); - assertEquals("1", layout.getIdmap().getData()); - - assertTrue(items.get(1) instanceof CTShapetype); - CTShapetype type = (CTShapetype)items.get(1); - assertEquals("21600,21600", type.getCoordsize()); - assertEquals(202.0f, type.getSpt(), 0); - assertEquals("m,l,21600r21600,l21600,xe", type.getPath2()); - assertEquals("_x0000_t202", type.getId()); - assertEquals(STTrueFalse.T, type.getPathArray(0).getGradientshapeok()); - assertEquals(STConnectType.RECT, type.getPathArray(0).getConnecttype()); - - CTShape shape = vml.newCommentShape(); - items = vml.getItems(); - assertEquals(3, items.size()); - assertSame(items.get(2), shape); - assertEquals("#_x0000_t202", shape.getType()); - assertEquals("position:absolute; visibility:hidden", shape.getStyle()); - assertEquals("#ffffe1", shape.getFillcolor()); - assertEquals(STInsetMode.AUTO, shape.getInsetmode()); - assertEquals("#ffffe1", shape.getFillArray(0).getColor()); - CTShadow shadow = shape.getShadowArray(0); - assertEquals(STTrueFalse.T, shadow.getOn()); - assertEquals("black", shadow.getColor()); - assertEquals(STTrueFalse.T, shadow.getObscured()); - assertEquals(STConnectType.NONE, shape.getPathArray(0).getConnecttype()); - assertEquals("mso-direction-alt:auto", shape.getTextboxArray(0).getStyle()); - CTClientData cldata = shape.getClientDataArray(0); - assertEquals(STObjectType.NOTE, cldata.getObjectType()); - assertEquals(1, cldata.sizeOfMoveWithCellsArray()); - assertEquals(1, cldata.sizeOfSizeWithCellsArray()); - assertEquals("1, 15, 0, 2, 3, 15, 3, 16", cldata.getAnchorArray(0)); - assertEquals("False", cldata.getAutoFillArray(0).toString()); - assertEquals(0, cldata.getRowArray(0).intValue()); - assertEquals(0, cldata.getColumnArray(0).intValue()); - assertEquals("[]", cldata.getVisibleList().toString()); - cldata.setVisibleArray(new STTrueFalseBlank.Enum[] { STTrueFalseBlank.Enum.forString("True") }); - assertEquals("[True]", cldata.getVisibleList().toString()); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - vml.write(out); - - XSSFVMLDrawing vml2 = new XSSFVMLDrawing(); - vml2.read(new ByteArrayInputStream(out.toByteArray())); - List<XmlObject> items2 = vml2.getItems(); - assertEquals(3, items2.size()); - assertTrue(items2.get(0) instanceof CTShapeLayout); - assertTrue(items2.get(1) instanceof CTShapetype); - assertTrue(items2.get(2) instanceof CTShape); - } - - @Test - void testFindCommentShape() throws IOException, XmlException { - - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - try (InputStream stream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml")) { - vml.read(stream); - } - - CTShape sh_a1 = vml.findCommentShape(0, 0); - assertNotNull(sh_a1); - assertEquals("_x0000_s1025", sh_a1.getId()); - - CTShape sh_b1 = vml.findCommentShape(0, 1); - assertNotNull(sh_b1); - assertEquals("_x0000_s1026", sh_b1.getId()); - - CTShape sh_c1 = vml.findCommentShape(0, 2); - assertNull(sh_c1); - - CTShape sh_d1 = vml.newCommentShape(); - assertEquals("_x0000_s1027", sh_d1.getId()); - sh_d1.getClientDataArray(0).setRowArray(0, new BigInteger("0")); - sh_d1.getClientDataArray(0).setColumnArray(0, new BigInteger("3")); - assertSame(sh_d1, vml.findCommentShape(0, 3)); - - //newly created drawing - XSSFVMLDrawing newVml = new XSSFVMLDrawing(); - assertNull(newVml.findCommentShape(0, 0)); - - sh_a1 = newVml.newCommentShape(); - assertEquals("_x0000_s1025", sh_a1.getId()); - sh_a1.getClientDataArray(0).setRowArray(0, new BigInteger("0")); - sh_a1.getClientDataArray(0).setColumnArray(0, new BigInteger("1")); - assertSame(sh_a1, newVml.findCommentShape(0, 1)); - } - - @Test - void testRemoveCommentShape() throws IOException, XmlException { - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - try (InputStream stream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml")) { - vml.read(stream); - } - - CTShape sh_a1 = vml.findCommentShape(0, 0); - assertNotNull(sh_a1); - - assertTrue(vml.removeCommentShape(0, 0)); - assertNull(vml.findCommentShape(0, 0)); - - } - - @Test - void testEvilUnclosedBRFixing() throws IOException, XmlException { - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - try (InputStream stream = POIDataSamples.getOpenXML4JInstance().openResourceAsStream("bug-60626.vml")) { - vml.read(stream); - } - - XmlOptions xopt = new XmlOptions(DEFAULT_XML_OPTIONS); - xopt.setSaveImplicitNamespaces(Collections.singletonMap("", QNAME_VMLDRAWING.getNamespaceURI())); - - Pattern p = Pattern.compile("<br/>"); - int count = 0; - for (XmlObject xo : vml.getItems()) { - String[] split = p.split(xo.xmlText(xopt)); - count += split.length-1; - } - assertEquals(16, count); - } - - @Test - void bug65061_InvalidXmlns() throws IOException, XmlException { - // input hasn't no <?xml... declaration - as in the sample file - String input = - "<xml xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\">\n" + - "<v:shapetype id=\"_x0000_t202\" coordsize=\"21600,21600\" path=\"m,l,21600r21600,l21600,xe\" o:spt=\"202\">\n" + - "<v:stroke joinstyle=\"miter\"/>\n" + - "<v:path o:connecttype=\"rect\" gradientshapeok=\"t\"/>\n" + - "</v:shapetype>\n" + - "</xml>"; - - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - vml.read(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8))); - - // check that the xml beans parsed correctly - assertNotNull(vml.getDocument().getXml()); - - // check the parsed child - List<XmlObject> objs = vml.getItems(); - assertEquals(1, objs.size()); - XmlObject xst = objs.get(0); - assertTrue(xst instanceof CTShapetypeImpl); - CTShapetype st = (CTShapetype)xst; - assertEquals(STStrokeJoinStyle.MITER, st.getStrokeArray(0).getJoinstyle()); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java deleted file mode 100644 index 78563bc32e..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java +++ /dev/null @@ -1,1163 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -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.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.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.zip.CRC32; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ooxml.POIXMLProperties; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.internal.FileHelper; -import org.apache.poi.openxml4j.opc.internal.MemoryPackagePart; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.ss.tests.usermodel.BaseTestXWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -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.CellReference; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.TempFile; -import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFChartData; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.StylesTable; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCache; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCalcMode; - -public final class TestXSSFWorkbook extends BaseTestXWorkbook { - - public TestXSSFWorkbook() { - super(XSSFITestDataProvider.instance); - } - - /** - * Tests that we can save, and then re-load a new document - */ - @Test - void saveLoadNew() throws IOException, InvalidFormatException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - - //check that the default date system is set to 1900 - CTWorkbookPr pr = wb1.getCTWorkbook().getWorkbookPr(); - assertNotNull(pr); - assertTrue(pr.isSetDate1904()); - assertFalse(pr.getDate1904(), "XSSF must use the 1900 date system"); - - Sheet sheet1 = wb1.createSheet("sheet1"); - Sheet sheet2 = wb1.createSheet("sheet2"); - wb1.createSheet("sheet3"); - - RichTextString rts = wb1.getCreationHelper().createRichTextString("hello world"); - - sheet1.createRow(0).createCell((short)0).setCellValue(1.2); - sheet1.createRow(1).createCell((short)0).setCellValue(rts); - sheet2.createRow(0); - - assertEquals(0, wb1.getSheetAt(0).getFirstRowNum()); - assertEquals(1, wb1.getSheetAt(0).getLastRowNum()); - assertEquals(0, wb1.getSheetAt(1).getFirstRowNum()); - assertEquals(0, wb1.getSheetAt(1).getLastRowNum()); - assertEquals(-1, wb1.getSheetAt(2).getFirstRowNum()); - assertEquals(-1, wb1.getSheetAt(2).getLastRowNum()); - - File file = TempFile.createTempFile("poi-", ".xlsx"); - OutputStream out = new FileOutputStream(file); - wb1.write(out); - out.close(); - - // Check the package contains what we'd expect it to - OPCPackage pkg = OPCPackage.open(file.toString()); - PackagePart wbRelPart = - pkg.getPart(PackagingURIHelper.createPartName("/xl/_rels/workbook.xml.rels")); - assertNotNull(wbRelPart); - assertTrue(wbRelPart.isRelationshipPart()); - assertEquals(ContentTypes.RELATIONSHIPS_PART, wbRelPart.getContentType()); - - PackagePart wbPart = - pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); - // Links to the three sheets, shared strings and styles - assertTrue(wbPart.hasRelationships()); - assertEquals(5, wbPart.getRelationships().size()); - wb1.close(); - - // Load back the XSSFWorkbook - @SuppressWarnings("resource") - XSSFWorkbook wb2 = new XSSFWorkbook(pkg); - assertEquals(3, wb2.getNumberOfSheets()); - assertNotNull(wb2.getSheetAt(0)); - assertNotNull(wb2.getSheetAt(1)); - assertNotNull(wb2.getSheetAt(2)); - - assertNotNull(wb2.getSharedStringSource()); - assertNotNull(wb2.getStylesSource()); - - assertEquals(0, wb2.getSheetAt(0).getFirstRowNum()); - assertEquals(1, wb2.getSheetAt(0).getLastRowNum()); - assertEquals(0, wb2.getSheetAt(1).getFirstRowNum()); - assertEquals(0, wb2.getSheetAt(1).getLastRowNum()); - assertEquals(-1, wb2.getSheetAt(2).getFirstRowNum()); - assertEquals(-1, wb2.getSheetAt(2).getLastRowNum()); - - sheet1 = wb2.getSheetAt(0); - assertEquals(1.2, sheet1.getRow(0).getCell(0).getNumericCellValue(), 0.0001); - assertEquals("hello world", sheet1.getRow(1).getCell(0).getRichStringCellValue().getString()); - - pkg.close(); - } - - @Test - void existing() throws Exception { - - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); - assertNotNull(workbook.getSharedStringSource()); - assertNotNull(workbook.getStylesSource()); - - // And check a few low level bits too - OPCPackage pkg = OPCPackage.open(HSSFTestDataSamples.openSampleFileStream("Formatting.xlsx")); - PackagePart wbPart = - pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); - - // Links to the three sheets, shared, styles and themes - assertTrue(wbPart.hasRelationships()); - assertEquals(6, wbPart.getRelationships().size()); - - pkg.close(); - workbook.close(); - } - - @Test - void getCellStyleAt() throws IOException{ - try (XSSFWorkbook workbook = new XSSFWorkbook()) { - short i = 0; - //get default style - CellStyle cellStyleAt = workbook.getCellStyleAt(i); - assertNotNull(cellStyleAt); - - //get custom style - StylesTable styleSource = workbook.getStylesSource(); - XSSFCellStyle customStyle = new XSSFCellStyle(styleSource); - XSSFFont font = new XSSFFont(); - font.setFontName("Verdana"); - customStyle.setFont(font); - int x = styleSource.putStyle(customStyle); - cellStyleAt = workbook.getCellStyleAt((short) x); - assertNotNull(cellStyleAt); - } - } - - @Test - void getFontAt() throws IOException{ - try (XSSFWorkbook workbook = new XSSFWorkbook()) { - StylesTable styleSource = workbook.getStylesSource(); - short i = 0; - //get default font - Font fontAt = workbook.getFontAt(i); - assertNotNull(fontAt); - - //get customized font - XSSFFont customFont = new XSSFFont(); - customFont.setItalic(true); - int x = styleSource.putFont(customFont); - fontAt = workbook.getFontAt((short) x); - assertNotNull(fontAt); - } - } - - @Test - void getNumCellStyles() throws IOException{ - try (XSSFWorkbook workbook = new XSSFWorkbook()) { - //get default cellStyles - assertEquals(1, workbook.getNumCellStyles()); - } - } - - @Test - void loadSave() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); - assertEquals(3, workbook.getNumberOfSheets()); - assertEquals("dd/mm/yyyy", workbook.getSheetAt(0).getRow(1).getCell(0).getRichStringCellValue().getString()); - assertNotNull(workbook.getSharedStringSource()); - assertNotNull(workbook.getStylesSource()); - - // Write out, and check - // Load up again, check all still there - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertEquals(3, wb2.getNumberOfSheets()); - assertNotNull(wb2.getSheetAt(0)); - assertNotNull(wb2.getSheetAt(1)); - assertNotNull(wb2.getSheetAt(2)); - - assertEquals("dd/mm/yyyy", wb2.getSheetAt(0).getRow(1).getCell(0).getRichStringCellValue().getString()); - assertEquals("yyyy/mm/dd", wb2.getSheetAt(0).getRow(2).getCell(0).getRichStringCellValue().getString()); - assertEquals("yyyy-mm-dd", wb2.getSheetAt(0).getRow(3).getCell(0).getRichStringCellValue().getString()); - assertEquals("yy/mm/dd", wb2.getSheetAt(0).getRow(4).getCell(0).getRichStringCellValue().getString()); - assertNotNull(wb2.getSharedStringSource()); - assertNotNull(wb2.getStylesSource()); - - workbook.close(); - wb2.close(); - } - - @Test - void styles() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); - - StylesTable ss = wb1.getStylesSource(); - assertNotNull(ss); - StylesTable st = ss; - - // Has 8 number formats - assertEquals(8, st.getNumDataFormats()); - // Has 2 fonts - assertEquals(2, st.getFonts().size()); - // Has 2 fills - assertEquals(2, st.getFills().size()); - // Has 1 border - assertEquals(1, st.getBorders().size()); - - // Add two more styles - assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8, - st.putNumberFormat("testFORMAT")); - assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8, - st.putNumberFormat("testFORMAT")); - assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 9, - st.putNumberFormat("testFORMAT2")); - assertEquals(10, st.getNumDataFormats()); - - - // Save, load back in again, and check - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - ss = wb2.getStylesSource(); - assertNotNull(ss); - - assertEquals(10, st.getNumDataFormats()); - assertEquals(2, st.getFonts().size()); - assertEquals(2, st.getFills().size()); - assertEquals(1, st.getBorders().size()); - wb2.close(); - } - - @Test - void incrementSheetId() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - int sheetId = (int) wb.createSheet().sheet.getSheetId(); - assertEquals(1, sheetId); - sheetId = (int) wb.createSheet().sheet.getSheetId(); - assertEquals(2, sheetId); - - //test file with gaps in the sheetId sequence - try (XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm")) { - int lastSheetId = (int) wbBack.getSheetAt(wbBack.getNumberOfSheets() - 1).sheet.getSheetId(); - sheetId = (int) wbBack.createSheet().sheet.getSheetId(); - assertEquals(lastSheetId + 1, sheetId); - } - } - } - - /** - * Test setting of core properties such as Title and Author - */ - @Test - void workbookProperties() throws IOException { - try (XSSFWorkbook workbook = new XSSFWorkbook()) { - POIXMLProperties props = workbook.getProperties(); - assertNotNull(props); - //the Application property must be set for new workbooks, see Bugzilla #47559 - assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication()); - - PackagePropertiesPart opcProps = props.getCoreProperties().getUnderlyingProperties(); - assertNotNull(opcProps); - - opcProps.setTitleProperty("Testing Bugzilla #47460"); - assertEquals("Apache POI", opcProps.getCreatorProperty().get()); - opcProps.setCreatorProperty("poi-dev@poi.apache.org"); - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertEquals("Apache POI", wbBack.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); - opcProps = wbBack.getProperties().getCoreProperties().getUnderlyingProperties(); - assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().get()); - assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().get()); - wbBack.close(); - } - } - - /** - * Verify that the attached test data was not modified. If this test method - * fails, the test data is not working properly. - */ - @Test - void bug47668() throws Exception { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("47668.xlsx"); - List<XSSFPictureData> allPictures = workbook.getAllPictures(); - assertEquals(1, allPictures.size()); - - PackagePartName imagePartName = PackagingURIHelper - .createPartName("/xl/media/image1.jpeg"); - PackagePart imagePart = workbook.getPackage().getPart(imagePartName); - assertNotNull(imagePart); - - for (XSSFPictureData pictureData : allPictures) { - PackagePart picturePart = pictureData.getPackagePart(); - assertSame(imagePart, picturePart); - } - - XSSFSheet sheet0 = workbook.getSheetAt(0); - XSSFDrawing drawing0 = sheet0.createDrawingPatriarch(); - XSSFPictureData pictureData0 = (XSSFPictureData) drawing0.getRelations().get(0); - byte[] data0 = pictureData0.getData(); - CRC32 crc0 = new CRC32(); - crc0.update(data0); - - XSSFSheet sheet1 = workbook.getSheetAt(1); - XSSFDrawing drawing1 = sheet1.createDrawingPatriarch(); - XSSFPictureData pictureData1 = (XSSFPictureData) drawing1.getRelations().get(0); - byte[] data1 = pictureData1.getData(); - CRC32 crc1 = new CRC32(); - crc1.update(data1); - - assertEquals(crc0.getValue(), crc1.getValue()); - workbook.close(); - } - - /** - * When deleting a sheet make sure that we adjust sheet indices of named ranges - */ - @SuppressWarnings("deprecation") - @Test - void bug47737() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx"); - assertEquals(2, wb.getNumberOfNames()); - assertNotNull(wb.getCalculationChain()); - - XSSFName nm0 = wb.getNameAt(0); - assertTrue(nm0.getCTName().isSetLocalSheetId()); - assertEquals(0, nm0.getCTName().getLocalSheetId()); - - XSSFName nm1 = wb.getNameAt(1); - assertTrue(nm1.getCTName().isSetLocalSheetId()); - assertEquals(1, nm1.getCTName().getLocalSheetId()); - - wb.removeSheetAt(0); - assertEquals(1, wb.getNumberOfNames()); - XSSFName nm2 = wb.getNameAt(0); - assertTrue(nm2.getCTName().isSetLocalSheetId()); - assertEquals(0, nm2.getCTName().getLocalSheetId()); - //calculation chain is removed as well - assertNull(wb.getCalculationChain()); - wb.close(); - - } - - /** - * Problems with XSSFWorkbook.removeSheetAt when workbook contains charts - */ - @Test - void bug47813() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47813.xlsx"); - assertEquals(3, wb1.getNumberOfSheets()); - assertNotNull(wb1.getCalculationChain()); - - assertEquals("Numbers", wb1.getSheetName(0)); - //the second sheet is of type 'chartsheet' - assertEquals("Chart", wb1.getSheetName(1)); - assertTrue(wb1.getSheetAt(1) instanceof XSSFChartSheet); - assertEquals("SomeJunk", wb1.getSheetName(2)); - - wb1.removeSheetAt(2); - assertEquals(2, wb1.getNumberOfSheets()); - assertNull(wb1.getCalculationChain()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals(2, wb2.getNumberOfSheets()); - assertNull(wb2.getCalculationChain()); - - assertEquals("Numbers", wb2.getSheetName(0)); - assertEquals("Chart", wb2.getSheetName(1)); - wb2.close(); - wb1.close(); - } - - /** - * Problems with the count of the number of styles - * coming out wrong - */ - @Test - void bug49702() throws IOException { - // First try with a new file - try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - - // Should have one style - assertEquals(1, wb1.getNumCellStyles()); - wb1.getCellStyleAt((short) 0); - assertNull(wb1.getCellStyleAt((short) 1), "Shouldn't be able to get style at 0 that doesn't exist"); - - // Add another one - CellStyle cs = wb1.createCellStyle(); - cs.setDataFormat((short) 11); - - // Re-check - assertEquals(2, wb1.getNumCellStyles()); - wb1.getCellStyleAt((short) 0); - wb1.getCellStyleAt((short) 1); - assertNull(wb1.getCellStyleAt((short) 2), "Shouldn't be able to get style at 2 that doesn't exist"); - - // Save and reload - try (XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { - assertEquals(2, nwb.getNumCellStyles()); - nwb.getCellStyleAt((short) 0); - nwb.getCellStyleAt((short) 1); - assertNull(nwb.getCellStyleAt((short) 2), "Shouldn't be able to get style at 2 that doesn't exist"); - - // Now with an existing file - try (XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) { - assertEquals(3, wb2.getNumCellStyles()); - wb2.getCellStyleAt((short) 0); - wb2.getCellStyleAt((short) 1); - wb2.getCellStyleAt((short) 2); - assertNull(wb2.getCellStyleAt((short) 3), "Shouldn't be able to get style at 3 that doesn't exist"); - } - } - } - } - - @Test - void recalcId() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - assertFalse(wb.getForceFormulaRecalculation()); - CTWorkbook ctWorkbook = wb.getCTWorkbook(); - assertFalse(ctWorkbook.isSetCalcPr()); - - wb.setForceFormulaRecalculation(true); - - CTCalcPr calcPr = ctWorkbook.getCalcPr(); - assertNotNull(calcPr); - assertEquals(0, (int) calcPr.getCalcId()); - - calcPr.setCalcId(100); - assertTrue(wb.getForceFormulaRecalculation()); - - wb.setForceFormulaRecalculation(false); - assertFalse(wb.getForceFormulaRecalculation()); - - // calcMode="manual" is unset when forceFormulaRecalculation=true - calcPr.setCalcMode(STCalcMode.MANUAL); - wb.setForceFormulaRecalculation(true); - assertEquals(STCalcMode.AUTO, calcPr.getCalcMode()); - assertTrue(wb.getForceFormulaRecalculation()); - - wb.setForceFormulaRecalculation(false); - assertFalse(wb.getForceFormulaRecalculation()); - - wb.setForceFormulaRecalculation(true); - assertTrue(wb.getForceFormulaRecalculation()); - } - } - - @Test - void columnWidthPOI52233() throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellValue("hello world"); - - sheet = workbook.createSheet(); - sheet.setColumnWidth(4, 5000); - sheet.setColumnWidth(5, 5000); - - sheet.groupColumn((short) 4, (short) 5); - - accessWorkbook(workbook); - - try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { - workbook.write(stream); - } - - accessWorkbook(workbook); - workbook.close(); - } - - private void accessWorkbook(XSSFWorkbook workbook) { - workbook.getSheetAt(1).setColumnGroupCollapsed(4, true); - workbook.getSheetAt(1).setColumnGroupCollapsed(4, false); - - assertEquals("hello world", workbook.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); - assertEquals(2048, workbook.getSheetAt(0).getColumnWidth(0)); // <-works - } - - @Test - void bug48495() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48495.xlsx"); - - assertSheetOrder(wb, "Sheet1"); - - Sheet sheet = wb.getSheetAt(0); - sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, false); - Row newRow = sheet.getRow(2); - if (newRow == null) { - newRow = sheet.createRow(2); - } - newRow.createCell(0).setCellValue(" Another Header"); - wb.cloneSheet(0); - - assertSheetOrder(wb, "Sheet1", "Sheet1 (2)"); - - // FileOutputStream fileOut = new FileOutputStream("/tmp/bug48495.xlsx"); -// try { -// wb.write(fileOut); -// } finally { -// fileOut.close(); -// } - - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(read); - assertSheetOrder(read, "Sheet1", "Sheet1 (2)"); - read.close(); - wb.close(); - } - - @Test - void bug47090a() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.removeSheetAt(0); - assertSheetOrder(workbook, "Sheet2"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet2", "Sheet1"); - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet2", "Sheet1"); - read.close(); - workbook.close(); - } - - @Test - void bug47090b() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.removeSheetAt(1); - assertSheetOrder(workbook, "Sheet1"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet1", "Sheet0"); // Sheet0 because it uses "Sheet" + sheets.size() as starting point! - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet1", "Sheet0"); - read.close(); - workbook.close(); - } - - @Test - void bug47090c() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.removeSheetAt(0); - assertSheetOrder(workbook, "Sheet2"); - workbook.cloneSheet(0); - assertSheetOrder(workbook, "Sheet2", "Sheet2 (2)"); - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet2", "Sheet2 (2)"); - read.close(); - workbook.close(); - } - - @Test - void bug47090d() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet1", "Sheet2", "Sheet0"); - workbook.removeSheetAt(0); - assertSheetOrder(workbook, "Sheet2", "Sheet0"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet2", "Sheet0", "Sheet1"); - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet2", "Sheet0", "Sheet1"); - read.close(); - workbook.close(); - } - - @Test - void bug51158() throws IOException { - // create a workbook - final XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("Test Sheet"); - XSSFRow row = sheet.createRow(2); - XSSFCell cell = row.createCell(3); - cell.setCellValue("test1"); - - //XSSFCreationHelper helper = workbook.getCreationHelper(); - //cell.setHyperlink(helper.createHyperlink(0)); - - XSSFComment comment = sheet.createDrawingPatriarch().createCellComment(new XSSFClientAnchor()); - assertNotNull(comment); - comment.setString("some comment"); - -// CellStyle cs = workbook.createCellStyle(); -// cs.setShrinkToFit(false); -// row.createCell(0).setCellStyle(cs); - - // write the first excel file - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertNotNull(wb2); - sheet = wb2.getSheetAt(0); - row = sheet.getRow(2); - assertEquals("test1", row.getCell(3).getStringCellValue()); - assertNull(row.getCell(4)); - - // add a new cell to the sheet - cell = row.createCell(4); - cell.setCellValue("test2"); - - // write the second excel file - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - assertNotNull(wb3); - sheet = wb3.getSheetAt(0); - row = sheet.getRow(2); - - assertEquals("test1", row.getCell(3).getStringCellValue()); - assertEquals("test2", row.getCell(4).getStringCellValue()); - wb3.close(); - wb2.close(); - wb1.close(); - } - - @Test - void bug51158a() throws IOException { - // create a workbook - try (XSSFWorkbook workbook = new XSSFWorkbook()) { - workbook.createSheet("Test Sheet"); - - XSSFSheet sheetBack = workbook.getSheetAt(0); - - // committing twice did add the XML twice without clearing the part in between - sheetBack.commit(); - - // ensure that a memory based package part does not have lingering data from previous commit() calls - if (sheetBack.getPackagePart() instanceof MemoryPackagePart) { - sheetBack.getPackagePart().clear(); - } - - sheetBack.commit(); - - String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream()), StandardCharsets.UTF_8); - - assertEquals(1, countMatches(str, "<worksheet")); - } - } - - @Test - void bug60509() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("60509.xlsx"); - assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3"); - int sheetIndex = wb.getSheetIndex("Sheet1"); - wb.setSheetName(sheetIndex, "Sheet1-Renamed"); - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(read); - assertSheetOrder(read, "Sheet1-Renamed", "Sheet2", "Sheet3"); - XSSFSheet sheet = (XSSFSheet) read.getSheet("Sheet1-Renamed"); - XDDFChartData.Series series = sheet.getDrawingPatriarch().getCharts().get(0).getChartSeries().get(0).getSeries(0); - assertTrue(series instanceof XDDFBarChartData.Series, "should be a bar chart data series"); - String formula = series.getCategoryData().getFormula(); - assertTrue(formula.startsWith("'Sheet1-Renamed'!"), "should contain new sheet name"); - read.close(); - wb.close(); - } - - private static final int INDEX_NOT_FOUND = -1; - - private static boolean isEmpty(CharSequence cs) { - return cs == null || cs.length() == 0; - } - - private static int countMatches(CharSequence str, CharSequence sub) { - if (isEmpty(str) || isEmpty(sub)) { - return 0; - } - int count = 0; - int idx = 0; - while ((idx = indexOf(str, sub, idx)) != INDEX_NOT_FOUND) { - count++; - idx += sub.length(); - } - return count; - } - - private static int indexOf(CharSequence cs, CharSequence searchChar, int start) { - return cs.toString().indexOf(searchChar.toString(), start); - } - - @Test - void testAddPivotCache() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - CTWorkbook ctWb = wb.getCTWorkbook(); - CTPivotCache pivotCache = wb.addPivotCache("0"); - //Ensures that pivotCaches is initiated - assertTrue(ctWb.isSetPivotCaches()); - assertSame(pivotCache, ctWb.getPivotCaches().getPivotCacheArray(0)); - assertEquals("0", pivotCache.getId()); - } - } - - private void setPivotData(XSSFWorkbook wb){ - XSSFSheet sheet = wb.createSheet(); - - Row row1 = sheet.createRow(0); - // Create a cell and put a value in it. - Cell cell = row1.createCell(0); - cell.setCellValue("Names"); - Cell cell2 = row1.createCell(1); - cell2.setCellValue("#"); - Cell cell7 = row1.createCell(2); - cell7.setCellValue("Data"); - - Row row2 = sheet.createRow(1); - Cell cell3 = row2.createCell(0); - cell3.setCellValue("Jan"); - Cell cell4 = row2.createCell(1); - cell4.setCellValue(10); - Cell cell8 = row2.createCell(2); - cell8.setCellValue("Apa"); - - Row row3 = sheet.createRow(2); - Cell cell5 = row3.createCell(0); - cell5.setCellValue("Ben"); - Cell cell6 = row3.createCell(1); - cell6.setCellValue(9); - Cell cell9 = row3.createCell(2); - cell9.setCellValue("Bepa"); - - AreaReference source = wb.getCreationHelper().createAreaReference("A1:B2"); - sheet.createPivotTable(source, new CellReference("H5")); - } - - @Test - void testLoadWorkbookWithPivotTable() throws Exception { - File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx"); - - try (XSSFWorkbook wb = new XSSFWorkbook()) { - setPivotData(wb); - - FileOutputStream fileOut = new FileOutputStream(file); - wb.write(fileOut); - fileOut.close(); - } - - try (XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file)) { - assertEquals(1, wb2.getPivotTables().size()); - } - - assertTrue(file.delete()); - } - - @Test - void testAddPivotTableToWorkbookWithLoadedPivotTable() throws Exception { - File file = TempFile.createTempFile("ooxml-pivottable", ".xlsx"); - - try (XSSFWorkbook wb = new XSSFWorkbook()) { - setPivotData(wb); - - try (FileOutputStream fileOut = new FileOutputStream(file)) { - wb.write(fileOut); - } - } - - try (XSSFWorkbook wb2 = (XSSFWorkbook) WorkbookFactory.create(file)) { - setPivotData(wb2); - assertEquals(2, wb2.getPivotTables().size()); - } - - assertTrue(file.delete()); - } - - @Test - void testSetFirstVisibleTab_57373() throws IOException { - - try (Workbook wb = new XSSFWorkbook()) { - /*Sheet sheet1 =*/ - wb.createSheet(); - Sheet sheet2 = wb.createSheet(); - int idx2 = wb.getSheetIndex(sheet2); - Sheet sheet3 = wb.createSheet(); - int idx3 = wb.getSheetIndex(sheet3); - - // add many sheets so "first visible" is relevant - for (int i = 0; i < 30; i++) { - wb.createSheet(); - } - - wb.setFirstVisibleTab(idx2); - wb.setActiveSheet(idx3); - - //wb.write(new FileOutputStream(new File("C:\\temp\\test.xlsx"))); - - assertEquals(idx2, wb.getFirstVisibleTab()); - assertEquals(idx3, wb.getActiveSheetIndex()); - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - - sheet2 = wbBack.getSheetAt(idx2); - assertNotNull(sheet2); - sheet3 = wbBack.getSheetAt(idx3); - assertNotNull(sheet3); - assertEquals(idx2, wb.getFirstVisibleTab()); - assertEquals(idx3, wb.getActiveSheetIndex()); - wbBack.close(); - } - } - - /** - * Tests that we can save a workbook with macros and reload it. - */ - @Test - void testSetVBAProject() throws Exception { - File file; - final byte[] allBytes = new byte[256]; - for (int i = 0; i < 256; i++) { - allBytes[i] = (byte) (i - 128); - } - - XSSFWorkbook wb1 = new XSSFWorkbook(); - wb1.createSheet(); - wb1.setVBAProject(new ByteArrayInputStream(allBytes)); - file = TempFile.createTempFile("poi-", ".xlsm"); - OutputStream out = new FileOutputStream(file); - wb1.write(out); - out.close(); - wb1.close(); - - // Check the package contains what we'd expect it to - OPCPackage pkg = OPCPackage.open(file.toString()); - PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); - assertTrue(wbPart.hasRelationships()); - final PackageRelationshipCollection relationships = wbPart.getRelationships().getRelationships(XSSFRelation.VBA_MACROS.getRelation()); - assertEquals(1, relationships.size()); - PackageRelationship relationship = relationships.getRelationship(0); - assertNotNull(relationship); - assertEquals(XSSFRelation.VBA_MACROS.getDefaultFileName(), relationship.getTargetURI().toString()); - PackagePart vbaPart = pkg.getPart(PackagingURIHelper.createPartName(XSSFRelation.VBA_MACROS.getDefaultFileName())); - assertNotNull(vbaPart); - assertFalse(vbaPart.isRelationshipPart()); - assertEquals(XSSFRelation.VBA_MACROS.getContentType(), vbaPart.getContentType()); - final byte[] fromFile = IOUtils.toByteArray(vbaPart.getInputStream()); - assertArrayEquals(allBytes, fromFile); - - // Load back the XSSFWorkbook just to check nothing explodes - @SuppressWarnings("resource") - XSSFWorkbook wb2 = new XSSFWorkbook(pkg); - assertEquals(1, wb2.getNumberOfSheets()); - assertEquals(XSSFWorkbookType.XLSM, wb2.getWorkbookType()); - pkg.close(); - } - - @Test - void testBug54399() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("54399.xlsx")) { - - for (int i = 0; i < workbook.getNumberOfSheets(); i++) { - String name = "SheetRenamed" + (i + 1); - workbook.setSheetName(i, name); - assertEquals(name, workbook.getSheetName(i)); - } - - } - } - - /** - * Iterator<XSSFSheet> XSSFWorkbook.iterator was committed in r700472 on 2008-09-30 - * and has been replaced with Iterator<Sheet> XSSFWorkbook.iterator - * - * In order to make code for looping over sheets in workbooks standard, regardless - * of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously - * available Iterator<XSSFSheet> iterator and Iterator<XSSFSheet> sheetIterator - * have been replaced with Iterator<Sheet> {@link Sheet#iterator} and - * Iterator<Sheet> {@link Workbook#sheetIterator}. This makes iterating over sheets in a workbook - * similar to iterating over rows in a sheet and cells in a row. - * - * Note: this breaks backwards compatibility! Existing codebases will need to - * upgrade their code with either of the following options presented in this test case. - * - */ - @SuppressWarnings("unchecked") - @Test - void bug58245_XSSFSheetIterator() throws IOException { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - wb.createSheet(); - - // ===================================================================== - // Case 1: Existing code uses XSSFSheet for-each loop - // ===================================================================== - - // Option A: - for (XSSFSheet sh : (Iterable<XSSFSheet>) (Iterable<? extends Sheet>) wb) { - sh.createRow(0); - } - - // Option B (preferred for new code): - for (Sheet sh : wb) { - sh.createRow(1); - } - - // ===================================================================== - // Case 2: Existing code creates an iterator variable - // ===================================================================== - - // Option A: - { - Iterator<XSSFSheet> it = (Iterator<XSSFSheet>) (Iterator<? extends Sheet>) wb.iterator(); - XSSFSheet sh = it.next(); - sh.createRow(2); - } - - // Option B (preferred for new code): - { - Iterator<Sheet> it = wb.iterator(); - Sheet sh = it.next(); - sh.createRow(3); - } - - assertEquals(4, wb.getSheetAt(0).getPhysicalNumberOfRows()); - - - } - } - - @Test - void testBug56957CloseWorkbook() throws Exception { - File file = TempFile.createTempFile("TestBug56957_", ".xlsx"); - final Date dateExp = LocaleUtil.getLocaleCalendar(2014, 10, 9).getTime(); - - try { - // as the file is written to, we make a copy before actually working on it - FileHelper.copyFile(HSSFTestDataSamples.getSampleFile("56957.xlsx"), file); - - assertTrue(file.exists()); - - // read-only mode works! - try (Workbook workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ))) { - Date dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - } - - try (Workbook workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ))) { - Date dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - } - - // now check read/write mode - try (Workbook workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ_WRITE))) { - Date dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - } - - try (Workbook workbook = XSSFWorkbookFactory.createWorkbook(OPCPackage.open(file, PackageAccess.READ_WRITE))) { - Date dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - } - } finally { - assertTrue(file.exists()); - assertTrue(file.delete()); - } - } - - @Test - void closeDoesNotModifyWorkbook() throws IOException { - final String filename = "SampleSS.xlsx"; - final File file = POIDataSamples.getSpreadSheetInstance().getFile(filename); - Workbook wb; - - // Some tests commented out because close() modifies the file - // See bug 58779 - - // String - //wb = new XSSFWorkbook(file.getPath()); - //assertCloseDoesNotModifyFile(filename, wb); - - // File - //wb = new XSSFWorkbook(file); - //assertCloseDoesNotModifyFile(filename, wb); - - // InputStream - try (FileInputStream is = new FileInputStream(file)) { - wb = new XSSFWorkbook(is); - assertCloseDoesNotModifyFile(filename, wb); - } - - // OPCPackage - //wb = new XSSFWorkbook(OPCPackage.open(file)); - //assertCloseDoesNotModifyFile(filename, wb); - } - - @Test - void testCloseBeforeWrite() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - wb.createSheet("somesheet"); - - // test what happens if we close the Workbook before we write it out - wb.close(); - - assertThrows(IOException.class, () -> { - try { - XSSFTestDataSamples.writeOutAndReadBack(wb); - } catch (RuntimeException e) { - throw e.getCause(); - } - }); - } - } - - /** - * See bug #57840 test data tables - */ - @Test - void getTable() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTable.xlsx"); - XSSFTable table1 = wb.getTable("Tabella1"); - assertNotNull(table1, "Tabella1 was not found in workbook"); - assertEquals("Tabella1", table1.getName(), "Table name"); - assertEquals("Foglio1", table1.getSheetName(), "Sheet name"); - - // Table lookup should be case-insensitive - assertSame(table1, wb.getTable("TABELLA1"), "Case insensitive table name lookup"); - - // If workbook does not contain any data tables matching the provided name, getTable should return null - assertNull(wb.getTable(null), "Null table name should not throw NPE"); - assertNull(wb.getTable("Foglio1"), "Should not be able to find non-existent table"); - - // If a table is added after getTable is called it should still be reachable by XSSFWorkbook.getTable - // This test makes sure that if any caching is done that getTable never uses a stale cache - XSSFTable table2 = wb.getSheet("Foglio2").createTable(null); - table2.setName("Table2"); - assertSame(table2, wb.getTable("Table2"), "Did not find Table2"); - - // If table name is modified after getTable is called, the table can only be found by its new name - // This test makes sure that if any caching is done that getTable never uses a stale cache - table1.setName("Table1"); - assertSame(table1, wb.getTable("TABLE1"), "Did not find Tabella1 renamed to Table1"); - - wb.close(); - } - - @SuppressWarnings("deprecation") - @Test - void testRemoveSheet() throws IOException { - // Test removing a sheet maintains the named ranges correctly - XSSFWorkbook wb = new XSSFWorkbook(); - wb.createSheet("Sheet1"); - wb.createSheet("Sheet2"); - - XSSFName sheet1Name = wb.createName(); - sheet1Name.setNameName("name1"); - sheet1Name.setSheetIndex(0); - sheet1Name.setRefersToFormula("Sheet1!$A$1"); - - XSSFName sheet2Name = wb.createName(); - sheet2Name.setNameName("name1"); - sheet2Name.setSheetIndex(1); - sheet2Name.setRefersToFormula("Sheet2!$A$1"); - - assertTrue(wb.getAllNames().contains(sheet1Name)); - assertTrue(wb.getAllNames().contains(sheet2Name)); - - assertEquals(2, wb.getNames("name1").size()); - assertEquals(sheet1Name, wb.getNames("name1").get(0)); - assertEquals(sheet2Name, wb.getNames("name1").get(1)); - - // Remove sheet1, we should only have sheet2Name now - wb.removeSheetAt(0); - - assertFalse(wb.getAllNames().contains(sheet1Name)); - assertTrue(wb.getAllNames().contains(sheet2Name)); - assertEquals(1, wb.getNames("name1").size()); - assertEquals(sheet2Name, wb.getNames("name1").get(0)); - - // Check by index as well for sanity - assertEquals(1, wb.getNumberOfNames()); - assertEquals(0, wb.getNameIndex("name1")); - assertEquals(sheet2Name, wb.getNameAt(0)); - - wb.close(); - } - - /** - * See bug #61700 - */ - @Test - void testWorkbookForceFormulaRecalculation() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - workbook.createSheet().createRow(0).createCell(0).setCellFormula("B1+C1"); - workbook.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - assertFalse(workbook.getForceFormulaRecalculation()); - workbook.setForceFormulaRecalculation(true); - assertTrue(workbook.getForceFormulaRecalculation()); - - Workbook wbBack = _testDataProvider.writeOutAndReadBack(workbook); - assertTrue(wbBack.getForceFormulaRecalculation()); - wbBack.setForceFormulaRecalculation(false); - assertFalse(wbBack.getForceFormulaRecalculation()); - - Workbook wbBack2 = _testDataProvider.writeOutAndReadBack(wbBack); - assertFalse(wbBack2.getForceFormulaRecalculation()); - - workbook.close(); - wbBack.close(); - wbBack2.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFChartLegend.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFChartLegend.java deleted file mode 100644 index bbd1ee0981..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFChartLegend.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.xddf.usermodel.chart.LegendPosition; -import org.apache.poi.xddf.usermodel.chart.XDDFChartLegend; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests ChartLegend - */ -public final class TestXDDFChartLegend { - @Test - void testLegendPositionAccessMethods() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFChartLegend legend = chart.getOrAddLegend(); - - legend.setPosition(LegendPosition.TOP_RIGHT); - assertEquals(LegendPosition.TOP_RIGHT, legend.getPosition()); - - wb.close(); - } - - @Test - void test_setOverlay_defaultChartLegend_expectOverlayInitialValueSetToFalse() throws IOException { - // Arrange - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFChartLegend legend = chart.getOrAddLegend(); - - // Act - - // Assert - assertFalse(legend.isOverlay()); - - wb.close(); - } - - @Test - void test_setOverlay_chartLegendSetToTrue_expectOverlayInitialValueSetToTrue() throws IOException { - // Arrange - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFChartLegend legend = chart.getOrAddLegend(); - - // Act - legend.setOverlay(true); - - // Assert - assertTrue(legend.isOverlay()); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFManualLayout.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFManualLayout.java deleted file mode 100644 index 5954ffe7b3..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXDDFManualLayout.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.jupiter.api.Assertions.*; - -import java.io.IOException; - -import org.apache.poi.xddf.usermodel.chart.LayoutMode; -import org.apache.poi.xddf.usermodel.chart.LayoutTarget; -import org.apache.poi.xddf.usermodel.chart.XDDFChartLegend; -import org.apache.poi.xddf.usermodel.chart.XDDFManualLayout; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public final class TestXDDFManualLayout { - - private XSSFWorkbook wb; - private XDDFManualLayout layout; - - @BeforeEach - void createEmptyLayout() { - wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFChartLegend legend = chart.getOrAddLegend(); - layout = legend.getOrAddManualLayout(); - } - - @AfterEach - void closeWB() throws IOException { - wb.close(); - } - - /* - * Accessor methods are not trivial. They use lazy underlying bean - * initialization so there can be some errors (NPE, for example). - */ - @Test - void testAccessorMethods() { - final double newRatio = 1.1; - final double newCoordinate = 0.3; - final LayoutMode nonDefaultMode = LayoutMode.FACTOR; - final LayoutTarget nonDefaultTarget = LayoutTarget.OUTER; - - layout.setWidthRatio(newRatio); - assertEquals(layout.getWidthRatio(), newRatio, 0.0); - - layout.setHeightRatio(newRatio); - assertEquals(layout.getHeightRatio(), newRatio, 0.0); - - layout.setX(newCoordinate); - assertEquals(layout.getX(), newCoordinate, 0.0); - - layout.setY(newCoordinate); - assertEquals(layout.getY(), newCoordinate, 0.0); - - layout.setXMode(nonDefaultMode); - assertSame(layout.getXMode(), nonDefaultMode); - - layout.setYMode(nonDefaultMode); - assertSame(layout.getYMode(), nonDefaultMode); - - layout.setWidthMode(nonDefaultMode); - assertSame(layout.getWidthMode(), nonDefaultMode); - - layout.setHeightMode(nonDefaultMode); - assertSame(layout.getHeightMode(), nonDefaultMode); - - layout.setTarget(nonDefaultTarget); - assertSame(layout.getTarget(), nonDefaultTarget); - - } - - /* - * Layout must have reasonable default values and must not throw - * any exceptions. - */ - @Test - void testDefaultValues() { - assertNotNull(layout.getTarget()); - assertNotNull(layout.getXMode()); - assertNotNull(layout.getYMode()); - assertNotNull(layout.getHeightMode()); - assertNotNull(layout.getWidthMode()); - /* - * According to interface, 0.0 should be returned for - * uninitialized double properties. - */ - assertEquals(0.0, layout.getX(), 0.0); - assertEquals(0.0, layout.getY(), 0.0); - assertEquals(0.0, layout.getWidthRatio(), 0.0); - assertEquals(0.0, layout.getHeightRatio(), 0.0); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSF3DChartData.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSF3DChartData.java deleted file mode 100644 index 9a4bcf5c1e..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSF3DChartData.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Consumer; - -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetBuilder; -import org.apache.poi.xddf.usermodel.chart.AxisPosition; -import org.apache.poi.xddf.usermodel.chart.ChartTypes; -import org.apache.poi.xddf.usermodel.chart.XDDFArea3DChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFBar3DChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFCategoryAxis; -import org.apache.poi.xddf.usermodel.chart.XDDFChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFDataSource; -import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory; -import org.apache.poi.xddf.usermodel.chart.XDDFLine3DChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource; -import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for XSSF Area3d Charts - */ -class TestXSSF3DChartData { - - private static final Object[][] plotData = { - {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"}, - {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - }; - - @Test - void testArea3D() throws IOException { - // This test currently doesn't produce a valid area 3d chart and is only used to test accessors - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, plotData).build(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - - Map<ChartTypes, Consumer<XDDFChartData>> map = new HashMap<>(); - map.put(ChartTypes.AREA3D, this::handleArea3D); - map.put(ChartTypes.BAR3D, this::handleBar3D); - map.put(ChartTypes.LINE3D, this::handleLine3D); - - for (Map.Entry<ChartTypes, Consumer<XDDFChartData>> me : map.entrySet()) { - - XSSFChart chart = drawing.createChart(anchor); - - XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); - XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); - - XDDFDataSource<String> xs = XDDFDataSourcesFactory.fromStringCellRange(sheet, CellRangeAddress.valueOf("A1:J1")); - XDDFNumericalDataSource<Double> ys = XDDFDataSourcesFactory.fromNumericCellRange(sheet, CellRangeAddress.valueOf("A2:J2")); - - XDDFChartData data = chart.createData(me.getKey(), bottomAxis, leftAxis); - XDDFChartData.Series series = data.addSeries(xs, ys); - - assertNotNull(series); - assertEquals(1, data.getSeriesCount()); - assertEquals(series, data.getSeries(0)); - chart.plot(data); - - me.getValue().accept(data); - } - } - } - - private void handleArea3D(XDDFChartData data) { - XDDFArea3DChartData xArea3d = (XDDFArea3DChartData)data; - xArea3d.setGapDepth(10); - assertEquals(10, (int)xArea3d.getGapDepth()); - } - - private void handleBar3D(XDDFChartData data) { - XDDFBar3DChartData xBar3d = (XDDFBar3DChartData) data; - xBar3d.setGapDepth(10); - assertEquals(10, (int)xBar3d.getGapDepth()); - xBar3d.setGapWidth(10); - assertEquals(10, (int)xBar3d.getGapWidth()); - } - - private void handleLine3D(XDDFChartData data) { - XDDFLine3DChartData xLine3d = (XDDFLine3DChartData) data; - xLine3d.setGapDepth(10); - assertEquals(10, (int)xLine3d.getGapDepth()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java deleted file mode 100644 index 87d793958e..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.xddf.usermodel.chart.AxisCrosses; -import org.apache.poi.xddf.usermodel.chart.AxisPosition; -import org.apache.poi.xddf.usermodel.chart.XDDFCategoryAxis; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -public final class TestXSSFCategoryAxis { - @Test - void testAccessMethods() throws Exception { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFCategoryAxis axis = chart.createCategoryAxis(AxisPosition.BOTTOM); - - axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); - - assertEquals(chart.getAxes().size(), 1); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java deleted file mode 100644 index e98bfc1296..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java +++ /dev/null @@ -1,163 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -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.assertTrue; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.xddf.usermodel.chart.AxisPosition; -import org.apache.poi.xddf.usermodel.chart.AxisTickMark; -import org.apache.poi.xddf.usermodel.chart.XDDFChartAxis; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public final class TestXSSFChartAxis { - - private static final double EPSILON = 1E-7; - private XSSFWorkbook wb; - private XDDFChartAxis axis; - - @BeforeEach - void setup() { - wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - axis = chart.createValueAxis(AxisPosition.BOTTOM); - } - - @AfterEach - void teardown() throws IOException { - wb.close(); - wb = null; - axis = null; - } - - @Test - void testLogBaseIllegalArgument() { - IllegalArgumentException iae = null; - try { - axis.setLogBase(0.0); - } catch (IllegalArgumentException e) { - iae = e; - } - assertNotNull(iae); - - iae = null; - try { - axis.setLogBase(30000.0); - } catch (IllegalArgumentException e) { - iae = e; - } - assertNotNull(iae); - } - - @Test - void testLogBaseLegalArgument() { - axis.setLogBase(Math.E); - assertTrue(Math.abs(axis.getLogBase() - Math.E) < EPSILON); - } - - @Test - void testNumberFormat() { - final String numberFormat = "General"; - axis.setNumberFormat(numberFormat); - assertEquals(numberFormat, axis.getNumberFormat()); - } - - @Test - void testMaxAndMinAccessMethods() { - final double newValue = 10.0; - - axis.setMinimum(newValue); - assertTrue(Math.abs(axis.getMinimum() - newValue) < EPSILON); - - axis.setMaximum(newValue); - assertTrue(Math.abs(axis.getMaximum() - newValue) < EPSILON); - } - - @Test - void testVisibleAccessMethods() { - axis.setVisible(true); - assertTrue(axis.isVisible()); - - axis.setVisible(false); - assertFalse(axis.isVisible()); - } - - @Test - void testMajorTickMarkAccessMethods() { - axis.setMajorTickMark(AxisTickMark.NONE); - assertEquals(AxisTickMark.NONE, axis.getMajorTickMark()); - - axis.setMajorTickMark(AxisTickMark.IN); - assertEquals(AxisTickMark.IN, axis.getMajorTickMark()); - - axis.setMajorTickMark(AxisTickMark.OUT); - assertEquals(AxisTickMark.OUT, axis.getMajorTickMark()); - - axis.setMajorTickMark(AxisTickMark.CROSS); - assertEquals(AxisTickMark.CROSS, axis.getMajorTickMark()); - } - - @Test - void testMinorTickMarkAccessMethods() { - axis.setMinorTickMark(AxisTickMark.NONE); - assertEquals(AxisTickMark.NONE, axis.getMinorTickMark()); - - axis.setMinorTickMark(AxisTickMark.IN); - assertEquals(AxisTickMark.IN, axis.getMinorTickMark()); - - axis.setMinorTickMark(AxisTickMark.OUT); - assertEquals(AxisTickMark.OUT, axis.getMinorTickMark()); - - axis.setMinorTickMark(AxisTickMark.CROSS); - assertEquals(AxisTickMark.CROSS, axis.getMinorTickMark()); - } - - @Test - void testGetChartAxisBug57362() throws IOException { - //Load existing excel with some chart on it having primary and secondary axis. - try (final XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57362.xlsx")) { - final XSSFSheet sh = workbook.getSheetAt(0); - final XSSFDrawing drawing = sh.createDrawingPatriarch(); - final XSSFChart chart = drawing.getCharts().get(0); - - final List<? extends XDDFChartAxis> axisList = chart.getAxes(); - - assertEquals(4, axisList.size()); - assertNotNull(axisList.get(0)); - assertNotNull(axisList.get(1)); - assertNotNull(axisList.get(2)); - assertNotNull(axisList.get(3)); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java deleted file mode 100644 index c69af22ce4..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java +++ /dev/null @@ -1,207 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xddf.usermodel.chart.AxisCrosses; -import org.apache.poi.xddf.usermodel.chart.AxisPosition; -import org.apache.poi.xddf.usermodel.chart.ChartTypes; -import org.apache.poi.xddf.usermodel.chart.LegendPosition; -import org.apache.poi.xddf.usermodel.chart.XDDFChartAxis; -import org.apache.poi.xddf.usermodel.chart.XDDFChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFChartLegend; -import org.apache.poi.xddf.usermodel.chart.XDDFDataSource; -import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory; -import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource; -import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Test get/set chart title. - */ -class TestXSSFChartTitle { - private XSSFWorkbook createWorkbookWithChart() { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("linechart"); - final int NUM_OF_ROWS = 3; - final int NUM_OF_COLUMNS = 10; - - // Create a row and put some cells in it. Rows are 0 based. - Row row; - Cell cell; - for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { - row = sheet.createRow((short) rowIndex); - for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { - cell = row.createCell((short) colIndex); - cell.setCellValue(colIndex * (rowIndex + 1L)); - } - } - - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); - - XSSFChart chart = drawing.createChart(anchor); - XDDFChartLegend legend = chart.getOrAddLegend(); - legend.setPosition(LegendPosition.TOP_RIGHT); - - // Use a category axis for the bottom axis. - XDDFChartAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); - XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); - leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); - - XDDFDataSource<Double> xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); - XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); - XDDFNumericalDataSource<Double> ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); - - XDDFChartData data = chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); - data.addSeries(xs, ys1); - data.addSeries(xs, ys2); - chart.plot(data); - - return wb; - } - - /** - * Gets the first chart from the named sheet in the workbook. - */ - private XSSFChart getChartFromWorkbook(XSSFWorkbook wb, String sheetName) { - XSSFSheet sheet = wb.getSheet(sheetName); - XSSFSheet xsheet = sheet; - XSSFDrawing drawing = xsheet.getDrawingPatriarch(); - if (drawing != null) { - List<XSSFChart> charts = drawing.getCharts(); - if (charts != null && charts.size() > 0) { - return charts.get(0); - } - } - return null; - } - - @Test - void testNewChart() throws IOException { - XSSFWorkbook wb = createWorkbookWithChart(); - XSSFChart chart = getChartFromWorkbook(wb, "linechart"); - assertNotNull(chart); - assertNull(chart.getTitleText()); - final String myTitle = "My chart title"; - chart.setTitleText(myTitle); - XSSFRichTextString queryTitle = chart.getTitleText(); - assertNotNull(queryTitle); - assertEquals(myTitle, queryTitle.toString()); - - final String myTitleFormula = "1 & \" and \" & 2"; - chart.setTitleFormula(myTitleFormula); - // setting formula should unset text, but since there is a formula, returns an empty string - assertEquals("", chart.getTitleText().toString()); - String titleFormula = chart.getTitleFormula(); - assertNotNull(titleFormula); - assertEquals(myTitleFormula, titleFormula); - wb.close(); - } - - @Test - void testExistingChartWithTitle() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_withTitle.xlsx"); - XSSFChart chart = getChartFromWorkbook(wb, "Sheet1"); - assertNotNull(chart); - assertNotNull(chart.getTitle()); - XSSFRichTextString originalTitle = chart.getTitleText(); - assertNotNull(originalTitle); - final String myTitle = "My chart title"; - assertNotEquals(myTitle, originalTitle.toString()); - chart.setTitleText(myTitle); - XSSFRichTextString queryTitle = chart.getTitleText(); - assertNotNull(queryTitle); - assertEquals(myTitle, queryTitle.toString()); - wb.close(); - } - - @Test - void testExistingChartNoTitle() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_noTitle.xlsx"); - XSSFChart chart = getChartFromWorkbook(wb, "Sheet1"); - assertNotNull(chart); - assertNull(chart.getTitleText()); - assertNull(chart.getTitle()); - final String myTitle = "My chart title"; - chart.setTitleText(myTitle); - XSSFRichTextString queryTitle = chart.getTitleText(); - assertNotNull(queryTitle); - assertEquals(myTitle, queryTitle.toString()); - wb.close(); - } - - @Test - void testExistingChartWithFormulaTitle() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_withTitleFormula.xlsx"); - XSSFChart chart = getChartFromWorkbook(wb, "Sheet1"); - assertNotNull(chart); - XSSFRichTextString originalTitle = chart.getTitleText(); - assertNotNull(originalTitle); - assertEquals("", originalTitle.toString()); - String formula = chart.getTitleFormula(); - assertNotNull(formula); - assertEquals("Sheet1!$E$1", formula); - wb.close(); - } - - @Test - void testRemovingFromExistingChartNoTitle() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_noTitle.xlsx"); - XSSFChart chart = getChartFromWorkbook(wb, "Sheet1"); - assertNotNull(chart); - assertNull(chart.getTitleText()); - assertNull(chart.getTitle()); - chart.removeTitle(); - assertNull(chart.getTitleText()); - assertNull(chart.getTitle()); - wb.close(); - } - - @Test - void testRemovingFromExistingChartWithTitle() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_withTitle.xlsx"); - XSSFChart chart = getChartFromWorkbook(wb, "Sheet1"); - assertNotNull(chart); - assertNotNull(chart.getTitleText()); - assertNotNull(chart.getTitle()); - chart.removeTitle(); - assertNull(chart.getTitleText()); - assertNull(chart.getTitle()); - wb.close(); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java deleted file mode 100644 index 34acba6286..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.xddf.usermodel.chart.AxisCrosses; -import org.apache.poi.xddf.usermodel.chart.AxisPosition; -import org.apache.poi.xddf.usermodel.chart.XDDFDateAxis; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -public final class TestXSSFDateAxis { - - @Test - void testAccessMethods() throws Exception { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFDateAxis axis = chart.createDateAxis(AxisPosition.BOTTOM); - - axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); - - assertEquals(chart.getAxes().size(), 1); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFLineChartData.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFLineChartData.java deleted file mode 100644 index 71ff251ede..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFLineChartData.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetBuilder; -import org.apache.poi.xddf.usermodel.chart.AxisPosition; -import org.apache.poi.xddf.usermodel.chart.ChartTypes; -import org.apache.poi.xddf.usermodel.chart.XDDFCategoryAxis; -import org.apache.poi.xddf.usermodel.chart.XDDFChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFDataSource; -import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory; -import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource; -import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for XSSF Line Charts - */ -class TestXSSFLineChartData { - - private static final Object[][] plotData = { - {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"}, - {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - }; - - @Test - void testOneSeriePlot() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, plotData).build(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - - XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); - XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); - - XDDFDataSource<String> xs = XDDFDataSourcesFactory.fromStringCellRange(sheet, CellRangeAddress.valueOf("A1:J1")); - XDDFNumericalDataSource<Double> ys = XDDFDataSourcesFactory.fromNumericCellRange(sheet, CellRangeAddress.valueOf("A2:J2")); - - XDDFChartData lineChartData = chart.createData(ChartTypes.LINE, bottomAxis, leftAxis); - XDDFChartData.Series series = lineChartData.addSeries(xs, ys); - - assertNotNull(series); - assertEquals(1, lineChartData.getSeriesCount()); - assertTrue(lineChartData.getSeries(0) == series); - - chart.plot(lineChartData); - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java deleted file mode 100644 index 16f0fa68fe..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetBuilder; -import org.apache.poi.xddf.usermodel.chart.AxisPosition; -import org.apache.poi.xddf.usermodel.chart.ChartTypes; -import org.apache.poi.xddf.usermodel.chart.ScatterStyle; -import org.apache.poi.xddf.usermodel.chart.XDDFChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFDataSource; -import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory; -import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource; -import org.apache.poi.xddf.usermodel.chart.XDDFScatterChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * Tests for XSSFScatterChartData. - */ -public final class TestXSSFScatterChartData { - - private static final Object[][] plotData = { - {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"}, - { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - }; - - @Test - void testOneSeriePlot() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = (XSSFSheet) new SheetBuilder(wb, plotData).build(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - - XDDFValueAxis bottomAxis = chart.createValueAxis(AxisPosition.BOTTOM); - XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); - - XDDFDataSource<String> xs = XDDFDataSourcesFactory.fromStringCellRange(sheet, CellRangeAddress.valueOf("A1:J1")); - XDDFNumericalDataSource<Double> ys = XDDFDataSourcesFactory.fromNumericCellRange(sheet, CellRangeAddress.valueOf("A2:J2")); - - XDDFScatterChartData scatterChartData = (XDDFScatterChartData) chart.createData(ChartTypes.SCATTER, bottomAxis, leftAxis); - XDDFChartData.Series series = scatterChartData.addSeries(xs, ys); - - assertEquals(ScatterStyle.LINE_MARKER, scatterChartData.getStyle()); - assertNotNull(series); - assertEquals(1, scatterChartData.getSeriesCount()); - assertTrue(scatterChartData.getSeries(0) == series); - - chart.plot(scatterChartData); - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java deleted file mode 100644 index bc1d6f2c50..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.xddf.usermodel.chart.AxisCrossBetween; -import org.apache.poi.xddf.usermodel.chart.AxisCrosses; -import org.apache.poi.xddf.usermodel.chart.AxisPosition; -import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -public final class TestXSSFValueAxis { - - @Test - void testAccessMethods() throws Exception { - try (XSSFWorkbook wb = new XSSFWorkbook()) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XDDFValueAxis axis = chart.createValueAxis(AxisPosition.BOTTOM); - - axis.setCrossBetween(AxisCrossBetween.MIDPOINT_CATEGORY); - assertEquals(axis.getCrossBetween(), AxisCrossBetween.MIDPOINT_CATEGORY); - - axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); - - assertEquals(chart.getAxes().size(), 1); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java deleted file mode 100644 index 5f905d8e7d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.extensions; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorderPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTStylesheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle; - - -class TestXSSFBorder { - - @Test - void testGetBorderStyle() { - CTStylesheet stylesheet = CTStylesheet.Factory.newInstance(); - CTBorder border = stylesheet.addNewBorders().addNewBorder(); - CTBorderPr top = border.addNewTop(); - CTBorderPr right = border.addNewRight(); - CTBorderPr bottom = border.addNewBottom(); - - top.setStyle(STBorderStyle.DASH_DOT); - right.setStyle(STBorderStyle.NONE); - bottom.setStyle(STBorderStyle.THIN); - - XSSFCellBorder cellBorderStyle = new XSSFCellBorder(border); - assertEquals("DASH_DOT", cellBorderStyle.getBorderStyle(BorderSide.TOP).toString()); - - assertEquals("NONE", cellBorderStyle.getBorderStyle(BorderSide.RIGHT).toString()); - assertEquals(BorderStyle.NONE.ordinal(), cellBorderStyle.getBorderStyle(BorderSide.RIGHT).ordinal()); - - assertEquals("THIN", cellBorderStyle.getBorderStyle(BorderSide.BOTTOM).toString()); - - assertEquals(BorderStyle.THIN.ordinal(), cellBorderStyle.getBorderStyle(BorderSide.BOTTOM).ordinal()); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java deleted file mode 100644 index 735b0d5413..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.extensions; - - -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 java.io.IOException; - -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPatternFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType; - - -class TestXSSFCellFill { - - @Test - void testGetFillBackgroundColor() { - CTFill ctFill = CTFill.Factory.newInstance(); - XSSFCellFill cellFill = new XSSFCellFill(ctFill, null); - CTPatternFill ctPatternFill = ctFill.addNewPatternFill(); - CTColor bgColor = ctPatternFill.addNewBgColor(); - assertNotNull(cellFill.getFillBackgroundColor()); - bgColor.setIndexed(2); - assertEquals(2, cellFill.getFillBackgroundColor().getIndexed()); - } - - @Test - void testGetFillForegroundColor() { - CTFill ctFill = CTFill.Factory.newInstance(); - XSSFCellFill cellFill = new XSSFCellFill(ctFill, null); - CTPatternFill ctPatternFill = ctFill.addNewPatternFill(); - CTColor fgColor = ctPatternFill.addNewFgColor(); - assertNotNull(cellFill.getFillForegroundColor()); - fgColor.setIndexed(8); - assertEquals(8, cellFill.getFillForegroundColor().getIndexed()); - } - - @Test - void testGetSetPatternType() { - CTFill ctFill = CTFill.Factory.newInstance(); - XSSFCellFill cellFill = new XSSFCellFill(ctFill, null); - CTPatternFill ctPatternFill = ctFill.addNewPatternFill(); - ctPatternFill.setPatternType(STPatternType.SOLID); - STPatternType.Enum patternType = cellFill.getPatternType(); - assertNotNull(patternType); - assertEquals(FillPatternType.SOLID_FOREGROUND.ordinal(), patternType.intValue()-1); - } - - @Test - void testGetNotModifies() { - CTFill ctFill = CTFill.Factory.newInstance(); - XSSFCellFill cellFill = new XSSFCellFill(ctFill, null); - CTPatternFill ctPatternFill = ctFill.addNewPatternFill(); - ctPatternFill.setPatternType(STPatternType.DARK_DOWN); - STPatternType.Enum patternType = cellFill.getPatternType(); - assertNotNull(patternType); - assertEquals(8, patternType.intValue()); - } - - @Test - void testColorFromTheme() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx")) { - 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); - // 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); - } - } - - @Test - void testFillWithoutColors() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("FillWithoutColor.xlsx")) { - XSSFCell cellWithFill = wb.getSheetAt(0).getRow(5).getCell(1); - XSSFCellStyle style = cellWithFill.getCellStyle(); - assertNotNull(style); - assertNull(style.getFillBackgroundColorColor(), "had an empty background color"); - assertNull(style.getFillBackgroundXSSFColor(), "had an empty background color"); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFHeaderFooter.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFHeaderFooter.java deleted file mode 100644 index 6238a41713..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFHeaderFooter.java +++ /dev/null @@ -1,315 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.extensions; - -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.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import org.apache.poi.xssf.usermodel.XSSFOddHeader; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; - -class TestXSSFHeaderFooter { - - private XSSFWorkbook wb; - private XSSFSheet sheet; - private XSSFHeaderFooter hO; - private XSSFHeaderFooter hE; - private XSSFHeaderFooter hF; - private XSSFHeaderFooter fO; - private XSSFHeaderFooter fE; - private XSSFHeaderFooter fF; - - @BeforeEach - void before() { - wb = new XSSFWorkbook(); - sheet = wb.createSheet(); - hO = (XSSFHeaderFooter) sheet.getOddHeader(); - hE = (XSSFHeaderFooter) sheet.getEvenHeader(); - hF = (XSSFHeaderFooter) sheet.getFirstHeader(); - fO = (XSSFHeaderFooter) sheet.getOddFooter(); - fE = (XSSFHeaderFooter) sheet.getEvenFooter(); - fF = (XSSFHeaderFooter) sheet.getFirstFooter(); - } - - @AfterEach - void after() throws Exception { - wb.close(); - } - - @Test - void testGetHeaderFooter() { - CTHeaderFooter ctHf; - ctHf = hO.getHeaderFooter(); - assertNotNull(ctHf); - ctHf = hE.getHeaderFooter(); - assertNotNull(ctHf); - ctHf = hF.getHeaderFooter(); - assertNotNull(ctHf); - ctHf = fO.getHeaderFooter(); - assertNotNull(ctHf); - ctHf = fE.getHeaderFooter(); - assertNotNull(ctHf); - ctHf = fF.getHeaderFooter(); - assertNotNull(ctHf); - } - - @Test - void testGetValue() { - assertEquals("", hO.getValue()); - assertEquals("", hE.getValue()); - assertEquals("", hF.getValue()); - assertEquals("", fO.getValue()); - assertEquals("", fE.getValue()); - assertEquals("", fF.getValue()); - hO.setLeft("Left value"); - hO.setCenter("Center value"); - hO.setRight("Right value"); - hE.setLeft("LeftEvalue"); - hE.setCenter("CenterEvalue"); - hE.setRight("RightEvalue"); - hF.setLeft("LeftFvalue"); - hF.setCenter("CenterFvalue"); - hF.setRight("RightFvalue"); - assertEquals("&CCenter value&LLeft value&RRight value", hO.getValue()); - assertEquals("&CCenterEvalue&LLeftEvalue&RRightEvalue", hE.getValue()); - assertEquals("&CCenterFvalue&LLeftFvalue&RRightFvalue", hF.getValue()); - fO.setLeft("Left value1"); - fO.setCenter("Center value1"); - fO.setRight("Right value1"); - fE.setLeft("LeftEvalue1"); - fE.setCenter("CenterEvalue1"); - fE.setRight("RightEvalue1"); - fF.setLeft("LeftFvalue1"); - fF.setCenter("CenterFvalue1"); - fF.setRight("RightFvalue1"); - assertEquals("&CCenter value1&LLeft value1&RRight value1", fO.getValue()); - assertEquals("&CCenterEvalue1&LLeftEvalue1&RRightEvalue1", fE.getValue()); - assertEquals("&CCenterFvalue1&LLeftFvalue1&RRightFvalue1", fF.getValue()); - } - - @Disabled("Test not yet created") - void testAreFieldsStripped() { - } - - @Disabled("Test not yet created") - void testSetAreFieldsStripped() { - } - - @Test - void testStripFields() { - String simple = "I am a test header"; - String withPage = "I am a&P test header"; - String withLots = "I&A am&N a&P test&T header&U"; - String withFont = "I&22 am a&\"Arial,bold\" test header"; - String withOtherAnds = "I am a&P test header&&"; - String withOtherAnds2 = "I am a&P test header&a&b"; - - assertEquals(simple, XSSFOddHeader.stripFields(simple)); - assertEquals(simple, XSSFOddHeader.stripFields(withPage)); - assertEquals(simple, XSSFOddHeader.stripFields(withLots)); - assertEquals(simple, XSSFOddHeader.stripFields(withFont)); - assertEquals(simple + "&&", XSSFOddHeader.stripFields(withOtherAnds)); - assertEquals(simple + "&a&b", XSSFOddHeader.stripFields(withOtherAnds2)); - - // Now test the default strip flag - hE.setCenter("Center"); - hE.setLeft("In the left"); - - assertEquals("In the left", hE.getLeft()); - assertEquals("Center", hE.getCenter()); - assertEquals("", hE.getRight()); - - hE.setLeft("Top &P&F&D Left"); - assertEquals("Top &P&F&D Left", hE.getLeft()); - assertFalse(hE.areFieldsStripped()); - - hE.setAreFieldsStripped(true); - assertEquals("Top Left", hE.getLeft()); - assertTrue(hE.areFieldsStripped()); - - // Now even more complex - hE.setCenter("HEADER TEXT &P&N&D&T&Z&F&F&A&V"); - assertEquals("HEADER TEXT &V", hE.getCenter()); - } - - @Test - void testGetCenter() { - assertEquals("", hO.getCenter()); - assertEquals("", hE.getCenter()); - assertEquals("", hF.getCenter()); - assertEquals("", fO.getCenter()); - assertEquals("", fE.getCenter()); - assertEquals("", fF.getCenter()); - hO.setCenter("Center value"); - hE.setCenter("CenterEvalue"); - hF.setCenter("CenterFvalue"); - assertEquals("Center value", hO.getCenter()); - assertEquals("CenterEvalue", hE.getCenter()); - assertEquals("CenterFvalue", hF.getCenter()); - fO.setCenter("Center value1"); - fE.setCenter("CenterEvalue1"); - fF.setCenter("CenterFvalue1"); - assertEquals("Center value1", fO.getCenter()); - assertEquals("CenterEvalue1", fE.getCenter()); - assertEquals("CenterFvalue1", fF.getCenter()); - } - - @Test - void testGetLeft() { - assertEquals("", hO.getLeft()); - assertEquals("", hE.getLeft()); - assertEquals("", hF.getLeft()); - assertEquals("", fO.getLeft()); - assertEquals("", fE.getLeft()); - assertEquals("", fF.getLeft()); - hO.setLeft("Left value"); - hE.setLeft("LeftEvalue"); - hF.setLeft("LeftFvalue"); - assertEquals("Left value", hO.getLeft()); - assertEquals("LeftEvalue", hE.getLeft()); - assertEquals("LeftFvalue", hF.getLeft()); - fO.setLeft("Left value1"); - fE.setLeft("LeftEvalue1"); - fF.setLeft("LeftFvalue1"); - assertEquals("Left value1", fO.getLeft()); - assertEquals("LeftEvalue1", fE.getLeft()); - assertEquals("LeftFvalue1", fF.getLeft()); - } - - @Test - void testGetRight() { - assertEquals("", hO.getValue()); - assertEquals("", hE.getValue()); - assertEquals("", hF.getValue()); - assertEquals("", fO.getValue()); - assertEquals("", fE.getValue()); - assertEquals("", fF.getValue()); - hO.setRight("Right value"); - hE.setRight("RightEvalue"); - hF.setRight("RightFvalue"); - assertEquals("Right value", hO.getRight()); - assertEquals("RightEvalue", hE.getRight()); - assertEquals("RightFvalue", hF.getRight()); - fO.setRight("Right value1"); - fE.setRight("RightEvalue1"); - fF.setRight("RightFvalue1"); - assertEquals("Right value1", fO.getRight()); - assertEquals("RightEvalue1", fE.getRight()); - assertEquals("RightFvalue1", fF.getRight()); - } - - @Test - void testSetCenter() { - assertEquals("", hO.getValue()); - assertEquals("", hE.getValue()); - assertEquals("", hF.getValue()); - assertEquals("", fO.getValue()); - assertEquals("", fE.getValue()); - assertEquals("", fF.getValue()); - hO.setCenter("Center value"); - hE.setCenter("CenterEvalue"); - hF.setCenter("CenterFvalue"); - assertEquals("&CCenter value", hO.getValue()); - assertEquals("&CCenterEvalue", hE.getValue()); - assertEquals("&CCenterFvalue", hF.getValue()); - fO.setCenter("Center value1"); - fE.setCenter("CenterEvalue1"); - fF.setCenter("CenterFvalue1"); - assertEquals("&CCenter value1", fO.getValue()); - assertEquals("&CCenterEvalue1", fE.getValue()); - assertEquals("&CCenterFvalue1", fF.getValue()); - } - - @Test - void testSetLeft() { - assertEquals("", hO.getValue()); - assertEquals("", hE.getValue()); - assertEquals("", hF.getValue()); - assertEquals("", fO.getValue()); - assertEquals("", fE.getValue()); - assertEquals("", fF.getValue()); - hO.setLeft("Left value"); - hE.setLeft("LeftEvalue"); - hF.setLeft("LeftFvalue"); - assertEquals("&LLeft value", hO.getValue()); - assertEquals("&LLeftEvalue", hE.getValue()); - assertEquals("&LLeftFvalue", hF.getValue()); - fO.setLeft("Left value1"); - fE.setLeft("LeftEvalue1"); - fF.setLeft("LeftFvalue1"); - assertEquals("&LLeft value1", fO.getValue()); - assertEquals("&LLeftEvalue1", fE.getValue()); - assertEquals("&LLeftFvalue1", fF.getValue()); - } - - @Test - void testSetRight() { - assertEquals("", hO.getValue()); - assertEquals("", hE.getValue()); - assertEquals("", hF.getValue()); - assertEquals("", fO.getValue()); - assertEquals("", fE.getValue()); - assertEquals("", fF.getValue()); - hO.setRight("Right value"); - hE.setRight("RightEvalue"); - hF.setRight("RightFvalue"); - assertEquals("&RRight value", hO.getValue()); - assertEquals("&RRightEvalue", hE.getValue()); - assertEquals("&RRightFvalue", hF.getValue()); - fO.setRight("Right value1"); - fE.setRight("RightEvalue1"); - fF.setRight("RightFvalue1"); - assertEquals("&RRight value1", fO.getValue()); - assertEquals("&RRightEvalue1", fE.getValue()); - assertEquals("&RRightFvalue1", fF.getValue()); - } - - - - @Test - void testGetSetCenterLeftRight() { - - assertEquals("", fO.getCenter()); - fO.setCenter("My first center section"); - assertEquals("My first center section", fO.getCenter()); - fO.setCenter("No, let's update the center section"); - assertEquals("No, let's update the center section", fO.getCenter()); - fO.setLeft("And add a left one"); - fO.setRight("Finally the right section is added"); - assertEquals("And add a left one", fO.getLeft()); - assertEquals("Finally the right section is added", fO.getRight()); - - // Test changing the three sections value - fO.setCenter("Second center version"); - fO.setLeft("Second left version"); - fO.setRight("Second right version"); - assertEquals("Second center version", fO.getCenter()); - assertEquals("Second left version", fO.getLeft()); - assertEquals("Second right version", fO.getRight()); - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/XSSFCellBorderTest.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/XSSFCellBorderTest.java deleted file mode 100644 index d3d875fc25..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/XSSFCellBorderTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.extensions; - -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.model.ThemesTable; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorderPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle; - -import static org.junit.jupiter.api.Assertions.*; - -public class XSSFCellBorderTest { - private final XSSFWorkbook wb = new XSSFWorkbook(); - private final StylesTable stylesSource = wb.getStylesSource(); - private final XSSFCellBorder empty = new XSSFCellBorder(); - - @BeforeEach - void setUp() { - assertNotNull(stylesSource); - assertEquals(1, stylesSource.getBorders().size()); - } - - @Test - void testEquals() { - for (XSSFCellBorder.BorderSide side : XSSFCellBorder.BorderSide.values()) { - XSSFCellBorder border = new XSSFCellBorder(); - assertEquals(empty, border); - assertEquals(empty.hashCode(), border.hashCode()); - - border.setBorderStyle(side, BorderStyle.THICK); - assertNotEquals(empty, border); - - border = new XSSFCellBorder(); - assertEquals(empty, border); - assertEquals(empty.hashCode(), border.hashCode()); - - border.setBorderColor(side, new XSSFColor(stylesSource.getIndexedColors())); - assertNotEquals(empty, border); - } - - // also verify diagonal_up, diagonal_down and outline - XSSFCellBorder border = new XSSFCellBorder(); - border.getCTBorder().setDiagonalUp(true); - assertNotEquals(empty, border); - - border = new XSSFCellBorder(); - border.getCTBorder().setDiagonalDown(true); - assertNotEquals(empty, border); - - border = new XSSFCellBorder(); - border.getCTBorder().setOutline(true); - assertNotEquals(empty, border); - } - - @Test - void testConstruct() { - XSSFCellBorder border = new XSSFCellBorder((CTBorder) empty.getCTBorder().copy()); - assertEquals(empty, border); - border.getCTBorder().setOutline(true); - assertNotEquals(empty, border); - - border = new XSSFCellBorder((CTBorder) empty.getCTBorder().copy(), stylesSource.getIndexedColors()); - assertEquals(empty, border); - border.getCTBorder().setOutline(true); - assertNotEquals(empty, border); - - border = new XSSFCellBorder((CTBorder) empty.getCTBorder().copy(), stylesSource.getTheme(), - stylesSource.getIndexedColors()); - assertEquals(empty, border); - border.getCTBorder().setOutline(true); - assertNotEquals(empty, border); - } - - @Test - void testGettersSetters() { - assertNotNull(empty.getCTBorder()); - - XSSFCellBorder border = new XSSFCellBorder((CTBorder) empty.getCTBorder().copy()); - border.setThemesTable(stylesSource.getTheme()); - assertNotNull(border.getCTBorder()); - } - - @Test - void testSetBorderStyle() { - XSSFCellBorder border = new XSSFCellBorder(); - for (XSSFCellBorder.BorderSide side : XSSFCellBorder.BorderSide.values()) { - assertEquals(BorderStyle.NONE, border.getBorderStyle(side)); - - border.setBorderStyle(side, BorderStyle.THIN); - assertEquals(BorderStyle.THIN, border.getBorderStyle(side)); - } - } - - @Test - void testSetBorderColor() { - XSSFCellBorder border = new XSSFCellBorder(); - XSSFColor color = new XSSFColor(stylesSource.getIndexedColors()); - - for (XSSFCellBorder.BorderSide side : XSSFCellBorder.BorderSide.values()) { - assertNull(border.getBorderColor(side)); - - border.setBorderColor(side, color); - assertEquals(color, border.getBorderColor(side)); - } - } - - @Test - void testRegression() throws Exception { - XSSFCellStyle style = wb.createCellStyle(); - style.setBorderTop(BorderStyle.THICK); - style.setBorderBottom(BorderStyle.THICK); - - assertEquals(3, stylesSource.getBorders().size()); - - ThemesTable _theme = stylesSource.getTheme(); - CTXf _cellXf = style.getCoreXf(); - assertTrue(_cellXf.getApplyBorder()); - - int idx = (int) _cellXf.getBorderId(); - XSSFCellBorder cf = stylesSource.getBorderAt(idx); - CTBorder ct = (CTBorder) cf.getCTBorder().copy(); - - assertFalse(ct.isSetDiagonal()); - CTBorderPr pr = ct.addNewDiagonal(); - ct.setDiagonalUp(true); - pr.setStyle(STBorderStyle.Enum.forInt(BorderStyle.THICK.getCode() + 1)); - idx = stylesSource.putBorder(new XSSFCellBorder(ct, _theme, - stylesSource.getIndexedColors())); - _cellXf.setBorderId(idx); - _cellXf.setApplyBorder(true); - - assertEquals(4, stylesSource.getBorders().size()); - - style.setBorderLeft(BorderStyle.THICK); - style.setBorderRight(BorderStyle.THICK); - - Sheet sheet = wb.createSheet("Sheet1"); - - assertEquals(6, stylesSource.getBorders().size()); - - Cell cell = sheet.createRow(1).createCell(2); - cell.setCellStyle(style); - - assertEquals(6, stylesSource.getBorders().size()); - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - - assertEquals(6, wbBack.getStylesSource().getBorders().size()); - - wb.close(); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java deleted file mode 100644 index e3c15ed123..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java +++ /dev/null @@ -1,440 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.helpers; - -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -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.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf; - -/** - * Tests for {@link ColumnHelper} - * - */ -public final class TestColumnHelper { - - @Test - void testCleanColumns() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - - CTCols cols1 = worksheet.addNewCols(); - CTCol col1 = cols1.addNewCol(); - col1.setMin(1); - col1.setMax(1); - col1.setWidth(88); - col1.setHidden(true); - CTCol col2 = cols1.addNewCol(); - col2.setMin(2); - col2.setMax(3); - CTCols cols2 = worksheet.addNewCols(); - CTCol col4 = cols2.addNewCol(); - col4.setMin(13); - col4.setMax(16384); - - // Test cleaning cols - assertEquals(2, worksheet.sizeOfColsArray()); - int count = countColumns(worksheet); - assertEquals(16375, count); - // Clean columns and test a clean worksheet - ColumnHelper helper = new ColumnHelper(worksheet); - assertEquals(1, worksheet.sizeOfColsArray()); - count = countColumns(worksheet); - assertEquals(16375, count); - // Remember - POI column 0 == OOXML column 1 - assertEquals(88.0, helper.getColumn(0, false).getWidth(), 0.0); - assertTrue(helper.getColumn(0, false).getHidden()); - assertEquals(0.0, helper.getColumn(1, false).getWidth(), 0.0); - assertFalse(helper.getColumn(1, false).getHidden()); - } - - @Test - void testSortColumns() { - CTCols cols1 = CTCols.Factory.newInstance(); - CTCol col1 = cols1.addNewCol(); - col1.setMin(1); - col1.setMax(1); - col1.setWidth(88); - col1.setHidden(true); - CTCol col2 = cols1.addNewCol(); - col2.setMin(2); - col2.setMax(3); - CTCol col3 = cols1.addNewCol(); - col3.setMin(13); - col3.setMax(16750); - assertEquals(3, cols1.sizeOfColArray()); - CTCol col4 = cols1.addNewCol(); - col4.setMin(8); - col4.setMax(11); - assertEquals(4, cols1.sizeOfColArray()); - CTCol col5 = cols1.addNewCol(); - col5.setMin(4); - col5.setMax(5); - assertEquals(5, cols1.sizeOfColArray()); - CTCol col6 = cols1.addNewCol(); - col6.setMin(8); - col6.setMax(9); - col6.setHidden(true); - CTCol col7 = cols1.addNewCol(); - col7.setMin(6); - col7.setMax(8); - col7.setWidth(17.0); - CTCol col8 = cols1.addNewCol(); - col8.setMin(25); - col8.setMax(27); - CTCol col9 = cols1.addNewCol(); - col9.setMin(20); - col9.setMax(30); - assertEquals(9, cols1.sizeOfColArray()); - assertEquals(20, cols1.getColArray(8).getMin()); - assertEquals(30, cols1.getColArray(8).getMax()); - ColumnHelper.sortColumns(cols1); - assertEquals(9, cols1.sizeOfColArray()); - assertEquals(25, cols1.getColArray(8).getMin()); - assertEquals(27, cols1.getColArray(8).getMax()); - } - - @Test - void testCloneCol() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - ColumnHelper helper = new ColumnHelper(worksheet); - - CTCols cols = CTCols.Factory.newInstance(); - CTCol col = CTCol.Factory.newInstance(); - col.setMin(2); - col.setMax(8); - col.setHidden(true); - col.setWidth(13.4); - CTCol newCol = helper.cloneCol(cols, col); - assertEquals(2, newCol.getMin()); - assertEquals(8, newCol.getMax()); - assertTrue(newCol.getHidden()); - assertEquals(13.4, newCol.getWidth(), 0.0); - } - - @Test - void testAddCleanColIntoCols() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - ColumnHelper helper = new ColumnHelper(worksheet); - - CTCols cols1 = CTCols.Factory.newInstance(); - CTCol col1 = cols1.addNewCol(); - col1.setMin(1); - col1.setMax(1); - col1.setWidth(88); - col1.setHidden(true); - CTCol col2 = cols1.addNewCol(); - col2.setMin(2); - col2.setMax(3); - CTCol col3 = cols1.addNewCol(); - col3.setMin(13); - col3.setMax(16750); - assertEquals(3, cols1.sizeOfColArray()); - CTCol col4 = cols1.addNewCol(); - col4.setMin(8); - col4.setMax(9); - assertEquals(4, cols1.sizeOfColArray()); - - // No overlap - helper.addCleanColIntoCols(cols1, createCol(4, 5)); - assertEquals(5, cols1.sizeOfColArray()); - - // Overlaps with 8 - 9 (overlap and after replacements required) - CTCol col6 = createCol(8, 11); - col6.setHidden(true); - helper.addCleanColIntoCols(cols1, col6); - assertEquals(6, cols1.sizeOfColArray()); - - // Overlaps with 8 - 9 (before and overlap replacements required) - CTCol col7 = createCol(6, 8); - col7.setWidth(17.0); - helper.addCleanColIntoCols(cols1, col7); - assertEquals(8, cols1.sizeOfColArray()); - - // Overlaps with 13 - 16750 (before, overlap and after replacements required) - helper.addCleanColIntoCols(cols1, createCol(20, 30)); - assertEquals(10, cols1.sizeOfColArray()); - - // Overlaps with 20 - 30 (before, overlap and after replacements required) - helper.addCleanColIntoCols(cols1, createCol(25, 27)); - - // TODO - assert something interesting - assertEquals(12, cols1.sizeOfColArray()); - assertEquals(1, cols1.getColArray(0).getMin()); - assertEquals(16750, cols1.getColArray(11).getMax()); - } - - @Test - void testAddCleanColIntoColsExactOverlap() { - CTCols cols = createHiddenAndBestFitColsWithHelper(1, 1, 1, 1); - assertEquals(1, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, true, true); - } - - @Test - void testAddCleanColIntoColsOverlapsOverhangingBothSides() { - CTCols cols = createHiddenAndBestFitColsWithHelper(2, 2, 1, 3); - assertEquals(3, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, false, true); - assertMinMaxHiddenBestFit(cols, 1, 2, 2, true, true); - assertMinMaxHiddenBestFit(cols, 2, 3, 3, false, true); - } - - @Test - void testAddCleanColIntoColsOverlapsCompletelyNested() { - CTCols cols = createHiddenAndBestFitColsWithHelper(1, 3, 2, 2); - assertEquals(3, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, true, false); - assertMinMaxHiddenBestFit(cols, 1, 2, 2, true, true); - assertMinMaxHiddenBestFit(cols, 2, 3, 3, true, false); - } - - @Test - void testAddCleanColIntoColsNewOverlapsOverhangingLeftNotRightExactRight() { - CTCols cols = createHiddenAndBestFitColsWithHelper(2, 3, 1, 3); - assertEquals(2, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, false, true); - assertMinMaxHiddenBestFit(cols, 1, 2, 3, true, true); - } - - @Test - void testAddCleanColIntoColsNewOverlapsOverhangingRightNotLeftExactLeft() { - CTCols cols = createHiddenAndBestFitColsWithHelper(1, 2, 1, 3); - assertEquals(2, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 2, true, true); - assertMinMaxHiddenBestFit(cols, 1, 3, 3, false, true); - } - - @Test - void testAddCleanColIntoColsNewOverlapsOverhangingLeftNotRight() { - CTCols cols = createHiddenAndBestFitColsWithHelper(2, 3, 1, 2); - assertEquals(3, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, false, true); - assertMinMaxHiddenBestFit(cols, 1, 2, 2, true, true); - assertMinMaxHiddenBestFit(cols, 2, 3, 3, true, false); - } - - @Test - void testAddCleanColIntoColsNewOverlapsOverhangingRightNotLeft() { - CTCols cols = createHiddenAndBestFitColsWithHelper(1, 2, 2, 3); - assertEquals(3, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, true, false); - assertMinMaxHiddenBestFit(cols, 1, 2, 2, true, true); - assertMinMaxHiddenBestFit(cols, 2, 3, 3, false, true); - } - - /** - * Creates and adds a hidden column and then a best fit column with the given min/max pairs. - * Suitable for testing handling of overlap. - */ - private static CTCols createHiddenAndBestFitColsWithHelper(int hiddenMin, int hiddenMax, int bestFitMin, int bestFitMax) { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - ColumnHelper helper = new ColumnHelper(worksheet); - CTCols cols = worksheet.getColsArray(0); - - CTCol hidden = createCol(hiddenMin, hiddenMax); - hidden.setHidden(true); - helper.addCleanColIntoCols(cols, hidden); - - CTCol bestFit = createCol(bestFitMin, bestFitMax); - bestFit.setBestFit(true); - helper.addCleanColIntoCols(cols, bestFit); - return cols; - } - - private static void assertMinMaxHiddenBestFit(CTCols cols, int index, int min, int max, boolean hidden, boolean bestFit) { - CTCol col = cols.getColArray(index); - assertEquals(min, col.getMin()); - assertEquals(max, col.getMax()); - assertEquals(hidden, col.getHidden()); - assertEquals(bestFit, col.getBestFit()); - } - - private static CTCol createCol(int min, int max) { - CTCol col = CTCol.Factory.newInstance(); - col.setMin(min); - col.setMax(max); - return col; - } - - @Test - void testGetColumn() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - - CTCols cols1 = worksheet.addNewCols(); - CTCol col1 = cols1.addNewCol(); - col1.setMin(1); - col1.setMax(1); - col1.setWidth(88); - col1.setHidden(true); - CTCol col2 = cols1.addNewCol(); - col2.setMin(2); - col2.setMax(3); - CTCols cols2 = worksheet.addNewCols(); - CTCol col4 = cols2.addNewCol(); - col4.setMin(3); - col4.setMax(6); - - // Remember - POI column 0 == OOXML column 1 - ColumnHelper helper = new ColumnHelper(worksheet); - assertNotNull(helper.getColumn(0, false)); - assertNotNull(helper.getColumn(1, false)); - assertEquals(88.0, helper.getColumn(0, false).getWidth(), 0.0); - assertEquals(0.0, helper.getColumn(1, false).getWidth(), 0.0); - assertTrue(helper.getColumn(0, false).getHidden()); - assertFalse(helper.getColumn(1, false).getHidden()); - assertNull(helper.getColumn(99, false)); - assertNotNull(helper.getColumn(5, false)); - } - - @Test - void testSetColumnAttributes() { - CTCol col = CTCol.Factory.newInstance(); - col.setWidth(12); - col.setHidden(true); - CTCol newCol = CTCol.Factory.newInstance(); - assertEquals(0.0, newCol.getWidth(), 0.0); - assertFalse(newCol.getHidden()); - ColumnHelper helper = new ColumnHelper(CTWorksheet.Factory - .newInstance()); - helper.setColumnAttributes(col, newCol); - assertEquals(12.0, newCol.getWidth(), 0.0); - assertTrue(newCol.getHidden()); - } - - @Test - void testGetOrCreateColumn() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet("Sheet 1"); - ColumnHelper columnHelper = sheet.getColumnHelper(); - - // Check POI 0 based, OOXML 1 based - CTCol col = columnHelper.getOrCreateColumn1Based(3, false); - assertNotNull(col); - assertNull(columnHelper.getColumn(1, false)); - assertNotNull(columnHelper.getColumn(2, false)); - assertNotNull(columnHelper.getColumn1Based(3, false)); - assertNull(columnHelper.getColumn(3, false)); - - CTCol col2 = columnHelper.getOrCreateColumn1Based(30, false); - assertNotNull(col2); - assertNull(columnHelper.getColumn(28, false)); - assertNotNull(columnHelper.getColumn(29, false)); - assertNotNull(columnHelper.getColumn1Based(30, false)); - assertNull(columnHelper.getColumn(30, false)); - - workbook.close(); - } - - @Test - void testGetSetColDefaultStyle() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CTWorksheet ctWorksheet = sheet.getCTWorksheet(); - ColumnHelper columnHelper = sheet.getColumnHelper(); - - // POI column 3, OOXML column 4 - CTCol col = columnHelper.getOrCreateColumn1Based(4, false); - - assertNotNull(col); - assertNotNull(columnHelper.getColumn(3, false)); - columnHelper.setColDefaultStyle(3, 2); - assertEquals(2, columnHelper.getColDefaultStyle(3)); - assertEquals(-1, columnHelper.getColDefaultStyle(4)); - StylesTable stylesTable = workbook.getStylesSource(); - CTXf cellXf = CTXf.Factory.newInstance(); - cellXf.setFontId(0); - cellXf.setFillId(0); - cellXf.setBorderId(0); - cellXf.setNumFmtId(0); - cellXf.setXfId(0); - stylesTable.putCellXf(cellXf); - CTCol col_2 = ctWorksheet.getColsArray(0).addNewCol(); - col_2.setMin(10); - col_2.setMax(12); - col_2.setStyle(1); - assertEquals(1, columnHelper.getColDefaultStyle(11)); - XSSFCellStyle cellStyle = new XSSFCellStyle(0, 0, stylesTable, null); - columnHelper.setColDefaultStyle(11, cellStyle); - assertEquals(0, col_2.getStyle()); - assertEquals(1, columnHelper.getColDefaultStyle(10)); - - workbook.close(); - } - - private static int countColumns(CTWorksheet worksheet) { - int count; - count = 0; - for (int i = 0; i < worksheet.sizeOfColsArray(); i++) { - for (int y = 0; y < worksheet.getColsArray(i).sizeOfColArray(); y++) { - for (long k = worksheet.getColsArray(i).getColArray(y).getMin(); k <= worksheet - .getColsArray(i).getColArray(y).getMax(); k++) { - count++; - } - } - } - return count; - } - - @SuppressWarnings("deprecation") - @Test - void testColumnsCollapsed() { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - row.createCell(0); - row.createCell(1); - row.createCell(2); - - sheet.setColumnWidth(0, 10); - sheet.setColumnWidth(1, 10); - sheet.setColumnWidth(2, 10); - - sheet.groupColumn(0, 1); - sheet.setColumnGroupCollapsed(0, true); - - CTCols ctCols = ((XSSFSheet) sheet).getCTWorksheet().getColsArray()[0]; - assertEquals(3, ctCols.sizeOfColArray()); - assertTrue(ctCols.getColArray(0).isSetCollapsed()); - assertTrue(ctCols.getColArray(1).isSetCollapsed()); - assertTrue(ctCols.getColArray(2).isSetCollapsed()); - - ColumnHelper helper = new ColumnHelper(CTWorksheet.Factory.newInstance()); - helper.setColumnAttributes(ctCols.getColArray(1), ctCols.getColArray(2)); - - ctCols = ((XSSFSheet) sheet).getCTWorksheet().getColsArray()[0]; - assertTrue(ctCols.getColArray(0).isSetCollapsed()); - assertTrue(ctCols.getColArray(1).isSetCollapsed()); - assertTrue(ctCols.getColArray(2).isSetCollapsed()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestHeaderFooterHelper.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestHeaderFooterHelper.java deleted file mode 100644 index c8011af886..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestHeaderFooterHelper.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.helpers; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -/** - * Test the header and footer helper. - * As we go through XmlBeans, should always use &, - * and not & - */ -class TestHeaderFooterHelper { - - @Test - void testGetCenterLeftRightSection() { - HeaderFooterHelper helper = new HeaderFooterHelper(); - - String headerFooter = "&CTest the center section"; - assertEquals("Test the center section", helper.getCenterSection(headerFooter)); - - headerFooter = "&CTest the center section<he left one&RAnd the right one"; - assertEquals("Test the center section", helper.getCenterSection(headerFooter)); - assertEquals("The left one", helper.getLeftSection(headerFooter)); - assertEquals("And the right one", helper.getRightSection(headerFooter)); - } - - @Test - void testSetCenterLeftRightSection() { - HeaderFooterHelper helper = new HeaderFooterHelper(); - String headerFooter = ""; - headerFooter = helper.setCenterSection(headerFooter, "First added center section"); - assertEquals("First added center section", helper.getCenterSection(headerFooter)); - headerFooter = helper.setLeftSection(headerFooter, "First left"); - assertEquals("First left", helper.getLeftSection(headerFooter)); - - headerFooter = helper.setRightSection(headerFooter, "First right"); - assertEquals("First right", helper.getRightSection(headerFooter)); - assertEquals("&CFirst added center section&LFirst left&RFirst right", headerFooter); - - headerFooter = helper.setRightSection(headerFooter, "First right&F"); - assertEquals("First right&F", helper.getRightSection(headerFooter)); - assertEquals("&CFirst added center section&LFirst left&RFirst right&F", headerFooter); - - headerFooter = helper.setRightSection(headerFooter, "First right&"); - assertEquals("First right&", helper.getRightSection(headerFooter)); - assertEquals("&CFirst added center section&LFirst left&RFirst right&", headerFooter); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestXSSFColumnShifting.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestXSSFColumnShifting.java deleted file mode 100644 index 57591916d4..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestXSSFColumnShifting.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel.helpers; - -import org.apache.poi.ss.usermodel.BaseTestColumnShifting; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -class TestXSSFColumnShifting extends BaseTestColumnShifting { - public TestXSSFColumnShifting() { - super(); - wb = new XSSFWorkbook(); - } - @Override - protected void initColumnShifter(){ - columnShifter = new XSSFColumnShifter((XSSFSheet)sheet1); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/MemoryUsage.java b/src/ooxml/testcases/org/apache/poi/xssf/util/MemoryUsage.java deleted file mode 100644 index e7ba523ded..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/MemoryUsage.java +++ /dev/null @@ -1,203 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.util; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType; - -/** - * Mixed utilities for testing memory usage in XSSF - */ -@Disabled("only for manual tests") -@SuppressWarnings("InfiniteLoopStatement") -public class MemoryUsage { - private static final int NUM_COLUMNS = 255; - - private static void printMemoryUsage(String msg) { - System.out.println(" Memory (" + msg + "): " + Runtime.getRuntime().totalMemory()/(1024*1024) + "MB"); - } - - /** - * Generate a spreadsheet until OutOfMemoryError using low-level OOXML XmlBeans. - * Similar to {@link #numberSpreadsheet(org.apache.poi.ss.usermodel.Workbook, int)} - * - * <p> - * - * @param numCols the number of columns in a row - */ - public static void xmlBeans(int numCols) { - int i = 0, cnt = 0; - printMemoryUsage("before"); - - CTWorksheet sh = CTWorksheet.Factory.newInstance(); - CTSheetData data = sh.addNewSheetData(); - try { - for (i = 0; ; i++) { - CTRow row = data.addNewRow(); - row.setR(i); - for (int j = 0; j < numCols; j++) { - CTCell cell = row.addNewC(); - cell.setT(STCellType.N); - cell.setV(String.valueOf(j)); - cnt++; - } - } - } catch (OutOfMemoryError er) { - System.out.println("Failed at row=" + i + ", objects: " + cnt); - } finally { - printMemoryUsage("after"); - } - } - - /** - * Generate detached (parentless) Xml beans until OutOfMemoryError - * - * @see #testXmlAttached() - */ - @Test - void testXmlDetached() { - List<CTRow> rows = new ArrayList<>(); - int i = 0; - try { - for(;;) { - //create a standalone CTRow bean - CTRow r = CTRow.Factory.newInstance(); - assertNotNull(r); - r.setR(++i); - rows.add(r); - } - } catch (OutOfMemoryError er) { - System.out.println("Failed at row=" + i + " from " + rows.size() + " kept."); - } finally { - printMemoryUsage("after"); - } - } - - /** - * Generate attached (having a parent bean) Xml beans until OutOfMemoryError. - * This is MUCH more memory-efficient than {@link #testXmlDetached()} - * - * @see #testXmlAttached() - */ - @Test - void testXmlAttached() { - printMemoryUsage("before"); - List<CTRow> rows = new ArrayList<>(); - int i = 0; - //top-level element in sheet.xml - CTWorksheet sh = CTWorksheet.Factory.newInstance(); - CTSheetData data = sh.addNewSheetData(); - try { - for(;;) { - //create CTRow attached to the parent object - CTRow r = data.addNewRow(); - assertNotNull(r); - r.setR(++i); - rows.add(r); - } - } catch (OutOfMemoryError er) { - System.out.println("Failed at row=" + i + " from " + rows.size() + " kept."); - } finally { - printMemoryUsage("after"); - } - } - - /** - * Generate a spreadsheet until OutOfMemoryError - * cells in even columns are numbers, cells in odd columns are strings - */ - @ParameterizedTest - @ValueSource(booleans = {false, true}) - void testMixed(boolean useXSSF) throws IOException { - int i=0, cnt=0; - try (Workbook wb = WorkbookFactory.create(useXSSF)) { - printMemoryUsage("before"); - Sheet sh = wb.createSheet(); - for(i=0; ; i++) { - Row row = sh.createRow(i); - for(int j=0; j < NUM_COLUMNS; j++) { - Cell cell = row.createCell(j); - assertNotNull(cell); - if(j % 2 == 0) { - cell.setCellValue(j); - } else { - cell.setCellValue(new CellReference(j, i).formatAsString()); - } - cnt++; - } - } - } catch (OutOfMemoryError er) { - System.out.println("Failed at row=" + i + ", objects : " + cnt); - } finally { - printMemoryUsage("after"); - } - } - - /** - * Generate a spreadsheet who's all cell values are numbers. - * The data is generated until OutOfMemoryError. - * <p> - * as compared to {@link #mixedSpreadsheet(org.apache.poi.ss.usermodel.Workbook, int)}, - * this method does not set string values and, hence, does not involve the Shared Strings Table. - * </p> - * - * @param wb the workbook to write to - * @param numCols the number of columns in a row - */ - @ParameterizedTest - @ValueSource(booleans = {false, true}) - void testNumberHSSF(boolean useXSSF) throws IOException { - int i=0, cnt=0; - try (Workbook wb = WorkbookFactory.create(useXSSF)) { - printMemoryUsage("before"); - Sheet sh = wb.createSheet(); - for(i=0; ; i++) { - Row row = sh.createRow(i); - assertNotNull(row); - for(int j=0; j < NUM_COLUMNS; j++) { - Cell cell = row.createCell(j); - cell.setCellValue(j); - cnt++; - } - } - } catch (OutOfMemoryError er) { - System.out.println("Failed at row=" + i + ", objects : " + cnt); - } finally { - printMemoryUsage("after"); - } - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/TestCTColComparator.java b/src/ooxml/testcases/org/apache/poi/xssf/util/TestCTColComparator.java deleted file mode 100644 index 2d64973ad5..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/TestCTColComparator.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.Arrays; - -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; - - -public final class TestCTColComparator { - - @Test - void testCompare() { - CTCol o1 = CTCol.Factory.newInstance(); - o1.setMin(1); - o1.setMax(10); - CTCol o2 = CTCol.Factory.newInstance(); - o2.setMin(11); - o2.setMax(12); - assertEquals(-1, CTColComparator.BY_MIN_MAX.compare(o1, o2)); - CTCol o3 = CTCol.Factory.newInstance(); - o3.setMin(5); - o3.setMax(8); - CTCol o4 = CTCol.Factory.newInstance(); - o4.setMin(5); - o4.setMax(80); - assertEquals(-1, CTColComparator.BY_MIN_MAX.compare(o3, o4)); - } - - @Test - void testArraysSort() { - CTCol o1 = CTCol.Factory.newInstance(); - o1.setMin(1); - o1.setMax(10); - CTCol o2 = CTCol.Factory.newInstance(); - o2.setMin(11); - o2.setMax(12); - assertEquals(-1, CTColComparator.BY_MIN_MAX.compare(o1, o2)); - CTCol o3 = CTCol.Factory.newInstance(); - o3.setMin(5); - o3.setMax(80); - CTCol o4 = CTCol.Factory.newInstance(); - o4.setMin(5); - o4.setMax(8); - assertEquals(1, CTColComparator.BY_MIN_MAX.compare(o3, o4)); - CTCol[] cols = new CTCol[4]; - cols[0] = o1; - cols[1] = o2; - cols[2] = o3; - cols[3] = o4; - assertEquals(80, cols[2].getMax()); - assertEquals(8, cols[3].getMax()); - Arrays.sort(cols, CTColComparator.BY_MIN_MAX); - assertEquals(12, cols[3].getMax()); - assertEquals(8, cols[1].getMax()); - assertEquals(80, cols[2].getMax()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java b/src/ooxml/testcases/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java deleted file mode 100644 index 77a7e8be08..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.util; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.ReplacingInputStream; -import org.junit.jupiter.api.Test; - -public final class TestEvilUnclosedBRFixingInputStream { - - static class EvilUnclosedBRFixingInputStream extends ReplacingInputStream { - public EvilUnclosedBRFixingInputStream(byte[] source) { - super(new ByteArrayInputStream(source), "<br>", "<br/>"); - } - } - - @Test - void testOK() throws IOException { - byte[] ok = getBytes("<p><div>Hello There!</div> <div>Tags!</div></p>"); - - EvilUnclosedBRFixingInputStream inp = new EvilUnclosedBRFixingInputStream(ok); - - assertArrayEquals(ok, IOUtils.toByteArray(inp)); - inp.close(); - } - - @Test - void testProblem() throws IOException { - byte[] orig = getBytes("<p><div>Hello<br>There!</div> <div>Tags!</div></p>"); - byte[] fixed = getBytes("<p><div>Hello<br/>There!</div> <div>Tags!</div></p>"); - - EvilUnclosedBRFixingInputStream inp = new EvilUnclosedBRFixingInputStream(orig); - - assertArrayEquals(fixed, IOUtils.toByteArray(inp)); - inp.close(); - } - - /** - * Checks that we can copy with br tags around the buffer boundaries - */ - @Test - void testBufferSize() throws IOException { - byte[] orig = getBytes("<p><div>Hello<br> <br>There!</div> <div>Tags!<br><br></div></p>"); - byte[] fixed = getBytes("<p><div>Hello<br/> <br/>There!</div> <div>Tags!<br/><br/></div></p>"); - - // Vary the buffer size, so that we can end up with the br in the - // overflow or only part in the buffer - for(int i=5; i<orig.length; i++) { - EvilUnclosedBRFixingInputStream inp = new EvilUnclosedBRFixingInputStream(orig); - - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - boolean going = true; - while(going) { - byte[] b = new byte[i]; - int r = inp.read(b); - if(r > 0) { - bout.write(b, 0, r); - } else { - going = false; - } - } - - byte[] result = bout.toByteArray(); - assertArrayEquals(fixed, result); - inp.close(); - } - } - - private static byte[] getBytes(String str) { - return str.getBytes(StandardCharsets.UTF_8); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/TestNumericRanges.java b/src/ooxml/testcases/org/apache/poi/xssf/util/TestNumericRanges.java deleted file mode 100644 index 856ea584bc..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/TestNumericRanges.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.util; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - - -class TestNumericRanges { - - @Test - void testGetOverlappingType() { - long[] r1 = {3, 8}; - long[] r2 = {6, 11}; - long[] r3 = {1, 5}; - long[] r4 = {2, 20}; - long[] r5 = {5, 6}; - long[] r6 = {20, 23}; - assertEquals(NumericRanges.OVERLAPS_1_MINOR, NumericRanges.getOverlappingType(r1, r2)); - assertEquals(NumericRanges.OVERLAPS_2_MINOR, NumericRanges.getOverlappingType(r1, r3)); - assertEquals(NumericRanges.OVERLAPS_2_WRAPS, NumericRanges.getOverlappingType(r1, r4)); - assertEquals(NumericRanges.OVERLAPS_1_WRAPS, NumericRanges.getOverlappingType(r1, r5)); - assertEquals(NumericRanges.NO_OVERLAPS, NumericRanges.getOverlappingType(r1, r6)); - } - - @Test - void testGetOverlappingRange() { - long[] r1 = {3, 8}; - long[] r2 = {6, 11}; - long[] r3 = {1, 5}; - long[] r4 = {2, 20}; - long[] r5 = {5, 6}; - long[] r6 = {20, 23}; - assertEquals(6, NumericRanges.getOverlappingRange(r1, r2)[0]); - assertEquals(8, NumericRanges.getOverlappingRange(r1, r2)[1]); - assertEquals(3, NumericRanges.getOverlappingRange(r1, r3)[0]); - assertEquals(5, NumericRanges.getOverlappingRange(r1, r3)[1]); - assertEquals(3, NumericRanges.getOverlappingRange(r1, r4)[0]); - assertEquals(8, NumericRanges.getOverlappingRange(r1, r4)[1]); - assertEquals(5, NumericRanges.getOverlappingRange(r1, r5)[0]); - assertEquals(6, NumericRanges.getOverlappingRange(r1, r5)[1]); - assertEquals(-1, NumericRanges.getOverlappingRange(r1, r6)[0]); - assertEquals(-1, NumericRanges.getOverlappingRange(r1, r6)[1]); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java deleted file mode 100644 index 09355e810d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java +++ /dev/null @@ -1,113 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf; - -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ooxml.POIXMLProperties.CoreProperties; -import org.apache.poi.openxml4j.opc.PackageProperties; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTDigSigBlob; -import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties; -import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVectorLpstr; -import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVectorVariant; - -/** - * Tests if the {@link CoreProperties#getKeywords()} method. This test has been - * submitted because even though the - * {@link PackageProperties#getKeywordsProperty()} had been present before, the - * {@link CoreProperties#getKeywords()} had been missing. - * <p> - * The author of this has added {@link CoreProperties#getKeywords()} and - * {@link CoreProperties#setKeywords(String)} and this test is supposed to test - * them. - * - * @author Antoni Mylka - */ -public final class TestAllExtendedProperties { - @Test - void testGetAllExtendedProperties() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx")) { - CTProperties ctProps = doc.getProperties().getExtendedProperties().getUnderlyingProperties(); - assertEquals("Microsoft Office Word", ctProps.getApplication()); - assertEquals("14.0000", ctProps.getAppVersion()); - assertEquals(57, ctProps.getCharacters()); - assertEquals(66, ctProps.getCharactersWithSpaces()); - assertEquals("", ctProps.getCompany()); - assertNull(ctProps.getDigSig()); - assertEquals(0, ctProps.getDocSecurity()); - assertNotNull(ctProps.getDomNode()); - - CTVectorVariant vec = ctProps.getHeadingPairs(); - assertEquals(2, vec.getVector().sizeOfVariantArray()); - assertEquals("Title", vec.getVector().getVariantArray(0).getLpstr()); - assertEquals(1, vec.getVector().getVariantArray(1).getI4()); - - assertFalse(ctProps.isSetHiddenSlides()); - assertEquals(0, ctProps.getHiddenSlides()); - assertFalse(ctProps.isSetHLinks()); - assertNull(ctProps.getHLinks()); - assertNull(ctProps.getHyperlinkBase()); - assertTrue(ctProps.isSetHyperlinksChanged()); - assertFalse(ctProps.getHyperlinksChanged()); - assertEquals(1, ctProps.getLines()); - assertTrue(ctProps.isSetLinksUpToDate()); - assertFalse(ctProps.getLinksUpToDate()); - assertNull(ctProps.getManager()); - assertFalse(ctProps.isSetMMClips()); - assertEquals(0, ctProps.getMMClips()); - assertFalse(ctProps.isSetNotes()); - assertEquals(0, ctProps.getNotes()); - assertEquals(1, ctProps.getPages()); - assertEquals(1, ctProps.getParagraphs()); - assertNull(ctProps.getPresentationFormat()); - assertTrue(ctProps.isSetScaleCrop()); - assertFalse(ctProps.getScaleCrop()); - assertTrue(ctProps.isSetSharedDoc()); - assertFalse(ctProps.getSharedDoc()); - assertFalse(ctProps.isSetSlides()); - assertEquals(0, ctProps.getSlides()); - assertEquals("Normal.dotm", ctProps.getTemplate()); - - CTVectorLpstr vec2 = ctProps.getTitlesOfParts(); - assertEquals(1, vec2.getVector().sizeOfLpstrArray()); - assertEquals("Example Word 2010 Document", vec2.getVector().getLpstrArray(0)); - - assertEquals(3, ctProps.getTotalTime()); - assertEquals(10, ctProps.getWords()); - - // Check the digital signature part - // Won't be there in this file, but we - // need to do this check so that the - // appropriate parts end up in the - // smaller ooxml schemas file - CTDigSigBlob blob = ctProps.getDigSig(); - assertNull(blob); - - blob = CTDigSigBlob.Factory.newInstance(); - blob.setBlob(new byte[]{2, 6, 7, 2, 3, 4, 5, 1, 2, 3}); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestDocumentProtection.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestDocumentProtection.java deleted file mode 100644 index 4aac209eb9..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestDocumentProtection.java +++ /dev/null @@ -1,199 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -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 org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.util.TempFile; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; -import org.junit.jupiter.api.Test; - -class TestDocumentProtection { - - @Test - void testShouldReadEnforcementProperties() throws IOException { - - XWPFDocument documentWithoutDocumentProtectionTag = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); - assertFalse(documentWithoutDocumentProtectionTag.isEnforcedReadonlyProtection()); - assertFalse(documentWithoutDocumentProtectionTag.isEnforcedFillingFormsProtection()); - assertFalse(documentWithoutDocumentProtectionTag.isEnforcedCommentsProtection()); - assertFalse(documentWithoutDocumentProtectionTag.isEnforcedTrackedChangesProtection()); - documentWithoutDocumentProtectionTag.close(); - - XWPFDocument documentWithoutEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection_tag_existing.docx"); - assertFalse(documentWithoutEnforcement.isEnforcedReadonlyProtection()); - assertFalse(documentWithoutEnforcement.isEnforcedFillingFormsProtection()); - assertFalse(documentWithoutEnforcement.isEnforcedCommentsProtection()); - assertFalse(documentWithoutEnforcement.isEnforcedTrackedChangesProtection()); - documentWithoutEnforcement.close(); - - XWPFDocument documentWithReadonlyEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_readonly_no_password.docx"); - assertTrue(documentWithReadonlyEnforcement.isEnforcedReadonlyProtection()); - assertFalse(documentWithReadonlyEnforcement.isEnforcedFillingFormsProtection()); - assertFalse(documentWithReadonlyEnforcement.isEnforcedCommentsProtection()); - assertFalse(documentWithReadonlyEnforcement.isEnforcedTrackedChangesProtection()); - documentWithReadonlyEnforcement.close(); - - XWPFDocument documentWithFillingFormsEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_forms_no_password.docx"); - assertTrue(documentWithFillingFormsEnforcement.isEnforcedFillingFormsProtection()); - assertFalse(documentWithFillingFormsEnforcement.isEnforcedReadonlyProtection()); - assertFalse(documentWithFillingFormsEnforcement.isEnforcedCommentsProtection()); - assertFalse(documentWithFillingFormsEnforcement.isEnforcedTrackedChangesProtection()); - documentWithFillingFormsEnforcement.close(); - - XWPFDocument documentWithCommentsEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_comments_no_password.docx"); - assertFalse(documentWithCommentsEnforcement.isEnforcedFillingFormsProtection()); - assertFalse(documentWithCommentsEnforcement.isEnforcedReadonlyProtection()); - assertTrue(documentWithCommentsEnforcement.isEnforcedCommentsProtection()); - assertFalse(documentWithCommentsEnforcement.isEnforcedTrackedChangesProtection()); - documentWithCommentsEnforcement.close(); - - XWPFDocument documentWithTrackedChangesEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_trackedChanges_no_password.docx"); - assertFalse(documentWithTrackedChangesEnforcement.isEnforcedFillingFormsProtection()); - assertFalse(documentWithTrackedChangesEnforcement.isEnforcedReadonlyProtection()); - assertFalse(documentWithTrackedChangesEnforcement.isEnforcedCommentsProtection()); - assertTrue(documentWithTrackedChangesEnforcement.isEnforcedTrackedChangesProtection()); - documentWithTrackedChangesEnforcement.close(); - } - - @Test - void testShouldEnforceForReadOnly() throws IOException { - // XWPFDocument document = createDocumentFromSampleFile("test-data/document/documentProtection_no_protection.docx"); - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); - assertFalse(document.isEnforcedReadonlyProtection()); - - document.enforceReadonlyProtection(); - - assertTrue(document.isEnforcedReadonlyProtection()); - document.close(); - } - - @Test - void testShouldEnforceForFillingForms() throws IOException { - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); - assertFalse(document.isEnforcedFillingFormsProtection()); - - document.enforceFillingFormsProtection(); - - assertTrue(document.isEnforcedFillingFormsProtection()); - document.close(); - } - - @Test - void testShouldEnforceForComments() throws IOException { - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); - assertFalse(document.isEnforcedCommentsProtection()); - - document.enforceCommentsProtection(); - - assertTrue(document.isEnforcedCommentsProtection()); - document.close(); - } - - @Test - void testShouldEnforceForTrackedChanges() throws IOException { - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); - assertFalse(document.isEnforcedTrackedChangesProtection()); - - document.enforceTrackedChangesProtection(); - - assertTrue(document.isEnforcedTrackedChangesProtection()); - document.close(); - } - - @Test - void testShouldUnsetEnforcement() throws IOException { - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_readonly_no_password.docx"); - assertTrue(document.isEnforcedReadonlyProtection()); - - document.removeProtectionEnforcement(); - - assertFalse(document.isEnforcedReadonlyProtection()); - document.close(); - } - - @Test - void testIntegration() throws IOException { - XWPFDocument doc1 = new XWPFDocument(); - - XWPFParagraph p1 = doc1.createParagraph(); - - XWPFRun r1 = p1.createRun(); - r1.setText("Lorem ipsum dolor sit amet."); - doc1.enforceCommentsProtection(); - - File tempFile = TempFile.createTempFile("documentProtectionFile", ".docx"); - FileOutputStream out = new FileOutputStream(tempFile); - - doc1.write(out); - out.close(); - - FileInputStream inputStream = new FileInputStream(tempFile); - XWPFDocument doc2 = new XWPFDocument(inputStream); - inputStream.close(); - - assertTrue(doc2.isEnforcedCommentsProtection()); - doc2.close(); - doc1.close(); - } - - @Test - void testUpdateFields() throws IOException { - XWPFDocument doc = new XWPFDocument(); - assertFalse(doc.isEnforcedUpdateFields()); - doc.enforceUpdateFields(); - assertTrue(doc.isEnforcedUpdateFields()); - doc.close(); - } - - @Test - void bug56076_read() throws IOException { - // test legacy xored-hashed password - assertEquals("64CEED7E", CryptoFunctions.xorHashPassword("Example")); - // check leading 0 - assertEquals("0005CB00", CryptoFunctions.xorHashPassword("34579")); - - // test document write protection with password - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("bug56076.docx"); - boolean isValid = document.validateProtectionPassword("Example"); - assertTrue(isValid); - document.close(); - } - - @Test - void bug56076_write() throws IOException { - // test document write protection with password - XWPFDocument doc1 = new XWPFDocument(); - doc1.enforceCommentsProtection("Example", HashAlgorithm.sha512); - XWPFDocument doc2 = XWPFTestDataSamples.writeOutAndReadBack(doc1); - doc1.close(); - boolean isValid = doc2.validateProtectionPassword("Example"); - assertTrue(isValid); - doc2.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestNecessaryOOXMLClasses.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestNecessaryOOXMLClasses.java deleted file mode 100644 index 6840722c5d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestNecessaryOOXMLClasses.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; - -// aim is to get these classes loaded and included in poi-ooxml-lite.jar -class TestNecessaryOOXMLClasses { - - @Test - void testProblemClasses() { - CTTblLayoutType ctTblLayoutType = CTTblLayoutType.Factory.newInstance(); - assertNotNull(ctTblLayoutType); - STTblLayoutType stTblLayoutType = STTblLayoutType.Factory.newInstance(); - assertNotNull(stTblLayoutType); - CTEm ctEm = CTEm.Factory.newInstance(); - assertNotNull(ctEm); - STEm stEm = STEm.Factory.newInstance(); - assertNotNull(stEm); - assertEquals(STEm.CIRCLE, STEm.Enum.forString("circle")); - STHexColorAuto stHexColorAuto = STHexColorAuto.Factory.newInstance(); - assertNotNull(stHexColorAuto); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java deleted file mode 100644 index 033c466cc6..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; - -import org.apache.poi.ooxml.POIXMLProperties.CoreProperties; -import org.apache.poi.openxml4j.opc.PackageProperties; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.jupiter.api.Test; - -/** - * Tests if the {@link CoreProperties#getKeywords()} method. This test has been - * submitted because even though the - * {@link PackageProperties#getKeywordsProperty()} had been present before, the - * {@link CoreProperties#getKeywords()} had been missing. - * <p> - * The author of this has added {@link CoreProperties#getKeywords()} and - * {@link CoreProperties#setKeywords(String)} and this test is supposed to test - * them. - */ -public final class TestPackageCorePropertiesGetKeywords { - @Test - void testGetSetKeywords() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx")) { - String keywords = doc.getProperties().getCoreProperties().getKeywords(); - assertEquals("extractor, test, rdf", keywords); - - doc.getProperties().getCoreProperties().setKeywords("test, keywords"); - XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc); - keywords = docBack.getProperties().getCoreProperties().getKeywords(); - assertEquals("test, keywords", keywords); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java deleted file mode 100644 index 48b8d093da..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java +++ /dev/null @@ -1,138 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import javax.crypto.Cipher; - -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipFile; -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.crypt.CipherAlgorithm; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.xwpf.extractor.XWPFWordExtractor; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.xmlbeans.XmlException; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.DocumentDocument; - -class TestXWPFBugs { - private static final POIDataSamples samples = POIDataSamples.getDocumentInstance(); - - @Test - void truncatedDocx() throws Exception { - try (InputStream fis = samples.openResourceAsStream("truncated62886.docx"); - OPCPackage opc = OPCPackage.open(fis); - XWPFWordExtractor ext = new XWPFWordExtractor(opc)) { - assertNotNull(ext.getText()); - } - } - - /** - * A word document that's encrypted with non-standard - * Encryption options, and no cspname section. See bug 53475 - */ - @Test - void bug53475NoCSPName() throws Exception { - File file = samples.getFile("bug53475-password-is-solrcell.docx"); - POIFSFileSystem filesystem = new POIFSFileSystem(file, true); - - // Check the encryption details - EncryptionInfo info = new EncryptionInfo(filesystem); - assertEquals(128, info.getHeader().getKeySize()); - assertEquals(CipherAlgorithm.aes128, info.getHeader().getCipherAlgorithm()); - assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithm()); - - // Check it can be decoded - Decryptor d = Decryptor.getInstance(info); - assertTrue(d.verifyPassword("solrcell"), "Unable to process: document is encrypted"); - - // Check we can read the word document in that - InputStream dataStream = d.getDataStream(filesystem); - OPCPackage opc = OPCPackage.open(dataStream); - XWPFDocument doc = new XWPFDocument(opc); - XWPFWordExtractor ex = new XWPFWordExtractor(doc); - String text = ex.getText(); - assertNotNull(text); - assertEquals("This is password protected Word document.", text.trim()); - ex.close(); - - filesystem.close(); - } - - /** - * A word document with aes-256, i.e. aes is always 128 bit (= 128 bit block size), - * but the key can be 128/192/256 bits - */ - @Test - void bug53475_aes256() throws Exception { - int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - assumeTrue(maxKeyLen == 0x7FFFFFFF, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256"); - - File file = samples.getFile("bug53475-password-is-pass.docx"); - POIFSFileSystem filesystem = new POIFSFileSystem(file, true); - - // Check the encryption details - EncryptionInfo info = new EncryptionInfo(filesystem); - assertEquals(16, info.getHeader().getBlockSize()); - assertEquals(256, info.getHeader().getKeySize()); - assertEquals(CipherAlgorithm.aes256, info.getHeader().getCipherAlgorithm()); - assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithm()); - - // Check it can be decoded - Decryptor d = Decryptor.getInstance(info); - assertTrue(d.verifyPassword("pass"), "Unable to process: document is encrypted"); - - // Check we can read the word document in that - InputStream dataStream = d.getDataStream(filesystem); - OPCPackage opc = OPCPackage.open(dataStream); - XWPFDocument doc = new XWPFDocument(opc); - XWPFWordExtractor ex = new XWPFWordExtractor(doc); - String text = ex.getText(); - assertNotNull(text); - // I know ... a stupid typo, maybe next time ... - assertEquals("The is a password protected document.", text.trim()); - ex.close(); - - filesystem.close(); - } - - - @Test - void bug59058() throws IOException, XmlException { - String[] files = {"bug57031.docx", "bug59058.docx"}; - for (String f : files) { - ZipFile zf = new ZipFile(samples.getFile(f)); - ZipArchiveEntry entry = zf.getEntry("word/document.xml"); - DocumentDocument document = DocumentDocument.Factory.parse(zf.getInputStream(entry)); - assertNotNull(document); - zf.close(); - } - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/XWPFTestDataSamples.java b/src/ooxml/testcases/org/apache/poi/xwpf/XWPFTestDataSamples.java deleted file mode 100644 index d7cb2c23ad..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/XWPFTestDataSamples.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xwpf.usermodel.XWPFDocument; - -/** - * @author Yegor Kozlov - */ -public class XWPFTestDataSamples { - - public static XWPFDocument openSampleDocument(String sampleName) throws IOException { - InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(sampleName); - return new XWPFDocument(is); - } - - public static XWPFDocument writeOutAndReadBack(XWPFDocument doc) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - doc.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new XWPFDocument(bais); - } - - public static byte[] getImage(String filename) throws IOException { - try (InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(filename)) { - return IOUtils.toByteArray(is); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java deleted file mode 100644 index d7c5f1e4b3..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.extractor; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.jupiter.api.Test; - -class TestExternalEntities { - - /** - * Get text out of the simple file - */ - @Test - void testFile() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ExternalEntityInText.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - String text = extractor.getText(); - - assertTrue(text.length() > 0); - - // Check contents, they should not contain the text from POI web site after colon! - assertEquals("Here should not be the POI web site: \"\"", text.trim()); - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java deleted file mode 100644 index 6e5716549b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java +++ /dev/null @@ -1,481 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.POITestCase.assertEndsWith; -import static org.apache.poi.POITestCase.assertNotContained; -import static org.apache.poi.POITestCase.assertStartsWith; -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.assertTrue; - -import java.io.IOException; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.util.StringUtil; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.jupiter.api.Test; - -/** - * Tests for HXFWordExtractor - */ -class TestXWPFWordExtractor { - - /** - * Get text out of the simple file - */ - @Test - void testGetSimpleText() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check contents - assertStartsWith(text, - "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nunc at risus vel erat tempus posuere. Aenean non ante. Suspendisse vehicula dolor sit amet odio." - ); - assertEndsWith(text, - "Phasellus ultricies mi nec leo. Sed tempus. In sit amet lorem at velit faucibus vestibulum.\n" - ); - - // Check number of paragraphs by counting number of newlines - int numberOfParagraphs = StringUtil.countMatches(text, '\n'); - assertEquals(3, numberOfParagraphs); - } - } - - /** - * Tests getting the text out of a complex file - */ - @Test - void testGetComplexText() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - char euro = '\u20ac'; - - // Check contents - assertStartsWith(text, - " \n(V) ILLUSTRATIVE CASES\n\n" - ); - assertContains(text, - "As well as gaining " + euro + "90 from child benefit increases, he will also receive the early childhood supplement of " + euro + "250 per quarter for Vincent for the full four quarters of the year.\n\n\n\n"// \n\n\n" - ); - assertEndsWith(text, - "11.4%\t\t90\t\t\t\t\t250\t\t1,310\t\n\n \n\n\n" - ); - - // Check number of paragraphs by counting number of newlines - int numberOfParagraphs = StringUtil.countMatches(text, '\n'); - assertEquals(134, numberOfParagraphs); - } - } - - @Test - void testGetWithHyperlinks() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - // Now check contents - extractor.setFetchHyperlinks(false); - assertEquals( - "This is a test document.\nThis bit is in bold and italic\n" + - "Back to normal\n" + - "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" + - "We have a hyperlink here, and another.\n", - extractor.getText() - ); - - // One hyperlink is a real one, one is just to the top of page - extractor.setFetchHyperlinks(true); - assertEquals( - "This is a test document.\nThis bit is in bold and italic\n" + - "Back to normal\n" + - "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" + - "We have a hyperlink <http://poi.apache.org/> here, and another.\n", - extractor.getText() - ); - } - } - - @Test - void testHeadersFooters() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ThreeColHeadFoot.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - assertEquals( - "First header column!\tMid header\tRight header!\n" + - "This is a sample word document. It has two pages. It has a three column heading, and a three column footer\n" + - "\n" + - "HEADING TEXT\n" + - "\n" + - "More on page one\n" + - "\n\n" + - "End of page 1\n\n\n" + - "This is page two. It also has a three column heading, and a three column footer.\n" + - "Footer Left\tFooter Middle\tFooter Right\n", - extractor.getText() - ); - } - - // Now another file, expect multiple headers - // and multiple footers - try (XWPFDocument doc2 = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx")) { - - new XWPFWordExtractor(doc2).close(); - - try (XWPFWordExtractor extractor = new XWPFWordExtractor(doc2)) { - extractor.getText(); - - assertEquals( - "I am the header on the first page, and I" + '\u2019' + "m nice and simple\n" + - "First header column!\tMid header\tRight header!\n" + - "This is a sample word document. It has two pages. It has a simple header and footer, which is different to all the other pages.\n" + - "\n" + - "HEADING TEXT\n" + - "\n" + - "More on page one\n" + - "\n\n" + - "End of page 1\n\n\n" + - "This is page two. It also has a three column heading, and a three column footer.\n" + - "The footer of the first page\n" + - "Footer Left\tFooter Middle\tFooter Right\n", - extractor.getText() - ); - - } - } - } - - @Test - void testFootnotes() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("footnotes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - String text = extractor.getText(); - assertContains(text, "snoska"); - assertContains(text, "Eto ochen prostoy[footnoteRef:1] text so snoskoy"); - } - } - - - @Test - void testTableFootnotes() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("table_footnotes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - assertContains(extractor.getText(), "snoska"); - } - } - - @Test - void testFormFootnotes() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("form_footnotes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - String text = extractor.getText(); - assertContains(text, "testdoc"); - assertContains(text, "test phrase"); - } - } - - @Test - void testEndnotes() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("endnotes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - String text = extractor.getText(); - assertContains(text, "XXX"); - assertContains(text, "tilaka [endnoteRef:2]or 'tika'"); - } - } - - @Test - void testInsertedDeletedText() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("delins.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - assertContains(extractor.getText(), "pendant worn"); - assertContains(extractor.getText(), "extremely well"); - } - } - - @Test - void testParagraphHeader() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Headers.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - assertContains(extractor.getText(), "Section 1"); - assertContains(extractor.getText(), "Section 2"); - assertContains(extractor.getText(), "Section 3"); - } - } - - /** - * Test that we can open and process .docm - * (macro enabled) docx files (bug #45690) - */ - @Test - void testDOCMFiles() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("45690.docm"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - assertContains(extractor.getText(), "2004"); - assertContains(extractor.getText(), "2008"); - assertContains(extractor.getText(), "(120 "); - } - } - - /** - * Test that we handle things like tabs and - * carriage returns properly in the text that - * we're extracting (bug #49189) - */ - @Test - void testDocTabs() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - // Check bits - assertContains(extractor.getText(), "a"); - assertContains(extractor.getText(), "\t"); - assertContains(extractor.getText(), "b"); - - // Now check the first paragraph in total - assertContains(extractor.getText(), "a\tb\n"); - } - } - - /** - * The output should not contain field codes, e.g. those specified in the - * w:instrText tag (spec sec. 17.16.23) - */ - @Test - void testNoFieldCodes() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FieldCodes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - String text = extractor.getText(); - assertTrue(text.length() > 0); - assertFalse(text.contains("AUTHOR")); - assertFalse(text.contains("CREATEDATE")); - } - } - - /** - * The output should contain the values of simple fields, those specified - * with the fldSimple element (spec sec. 17.16.19) - */ - @Test - void testFldSimpleContent() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - String text = extractor.getText(); - assertTrue(text.length() > 0); - assertContains(text, "FldSimple.docx"); - } - } - - /** - * Test for parsing document with drawings to prevent - * NoClassDefFoundError for CTAnchor in XWPFRun - */ - @Test - void testDrawings() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("drawing.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - String text = extractor.getText(); - assertTrue(text.length() > 0); - } - } - - /** - * Test for basic extraction of SDT content - */ - @Test - void testSimpleControlContent() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); - XWPFWordExtractor ex = new XWPFWordExtractor(doc)) { - String[] targs = new String[]{ - "header_rich_text", - "rich_text", - "rich_text_pre_table\nrich_text_cell1\t\t\t\n\t\t\t\n\t\t\t\n\nrich_text_post_table", - "plain_text_no_newlines", - "plain_text_with_newlines1\nplain_text_with_newlines2\n", - "watermelon\n", - "dirt\n", - "4/16/2013\n", - "rich_text_in_cell", - "abc", - "rich_text_in_paragraph_in_cell", - "footer_rich_text", - "footnote_sdt", - "endnote_sdt" - }; - String s = ex.getText().toLowerCase(Locale.ROOT); - int hits = 0; - - for (String targ : targs) { - boolean hit = false; - if (s.contains(targ)) { - hit = true; - hits++; - } - assertTrue(hit, "controlled content loading-" + targ); - } - assertEquals(targs.length, hits, "controlled content loading hit count"); - } - - try (XWPFDocument doc2 = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx"); - XWPFWordExtractor ex = new XWPFWordExtractor(doc2)) { - String s = ex.getText().toLowerCase(Locale.ROOT); - - String[] targs = { - "bb", - "test subtitle\n", - "test user\n", - }; - - //At one point in development there were three copies of the text. - //This ensures that there is only one copy. - for (String targ : targs) { - Matcher m = Pattern.compile(targ).matcher(s); - int hit = 0; - while (m.find()) { - hit++; - } - assertEquals(1, hit, "controlled content loading-" + targ); - } - //"test\n" appears twice: once as the "title" and once in the text. - //This also happens when you save this document as text from MSWord. - Matcher m = Pattern.compile("test\n").matcher(s); - int hit = 0; - while (m.find()) { - hit++; - } - assertEquals(2, hit, "test<N>"); - } - } - - /** - * No Header or Footer in document - */ - @Test - void testBug55733() throws Exception { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("55733.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - // Check it gives text without error - assertNotNull(extractor.getText()); - } - } - - @Test - void testCheckboxes() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("checkboxes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - - assertEquals("This is a small test for checkboxes \nunchecked: |_| \n" + - "Or checked: |X|\n\n\n\n\n" + - "Test a checkbox within a textbox: |_| -> |X|\n\n\n" + - "In Table:\n|_|\t|X|\n\n\n" + - "In Sequence:\n|X||_||X|\n", extractor.getText()); - } - } - - @Test - void testMultipleBodyBug() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("MultipleBodyBug.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - assertEquals("START BODY 1 The quick, brown fox jumps over a lazy dog. END BODY 1.\n" - + "START BODY 2 The quick, brown fox jumps over a lazy dog. END BODY 2.\n" - + "START BODY 3 The quick, brown fox jumps over a lazy dog. END BODY 3.\n", - extractor.getText()); - } - } - - @Test - void testPhonetic() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61470.docx")) { - try (XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - //expect: baseText (phoneticText) - assertEquals("\u6771\u4EAC (\u3068\u3046\u304D\u3087\u3046)", extractor.getText().trim()); - } - try (XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - extractor.setConcatenatePhoneticRuns(false); - assertEquals("\u6771\u4EAC", extractor.getText().trim()); - } - } - } - - @Test - void testCTPictureBase() throws IOException { - //This forces ctpicturebase to be included in the poi-ooxml-lite jar - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61991.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc)) { - String txt = extractor.getText(); - assertContains(txt, "Sequencing data"); - } - } - - @Test - void testGlossary() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("60316.dotx")) { - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - String txt = extractor.getText(); - assertContains(txt, "Getting the perfect"); - //this content appears only in the glossary document - //once we add processing for this, we can change this to contains - assertNotContained(txt, "table rows"); - } - } - - @Test - void testPartsInTemplate() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("60316b.dotx")) { - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - String txt = extractor.getText(); - assertContains(txt, "header 2"); - assertContains(txt, "footer 1"); - } - } - - @Test - void bug55966() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("55966.docx")) { - String expected = "Content control within a paragraph is here text content from within a paragraph second control with a new\n" + - "line\n" + - "\n" + - "Content control that is the entire paragraph\n"; - - XWPFWordExtractor extractedDoc = new XWPFWordExtractor(doc); - - String actual = extractedDoc.getText(); - - extractedDoc.close(); - assertEquals(expected, actual); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java deleted file mode 100644 index d908d2c565..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.model; - -import java.io.IOException; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Tests for the various XWPF decorators - */ -class TestXWPFDecorators { - private XWPFDocument simple; - private XWPFDocument hyperlink; - private XWPFDocument comments; - - @BeforeEach - void setUp() throws IOException { - simple = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - hyperlink = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - comments = XWPFTestDataSamples.openSampleDocument("WordWithAttachments.docx"); - } - - @AfterEach - void tearDown() throws IOException { - simple.close(); - hyperlink.close(); - comments.close(); - } - - @Test - void testHyperlink() { - XWPFParagraph ps; - XWPFParagraph ph; - assertEquals(7, simple.getParagraphs().size()); - assertEquals(5, hyperlink.getParagraphs().size()); - - // Simple text - ps = simple.getParagraphs().get(0); - assertEquals("I am a test document", ps.getParagraphText()); - assertEquals(1, ps.getRuns().size()); - - ph = hyperlink.getParagraphs().get(4); - assertEquals("We have a hyperlink here, and another.", ph.getParagraphText()); - assertEquals(3, ph.getRuns().size()); - - - // The proper way to do hyperlinks(!) - assertFalse(ps.getRuns().get(0) instanceof XWPFHyperlinkRun); - assertFalse(ph.getRuns().get(0) instanceof XWPFHyperlinkRun); - assertTrue(ph.getRuns().get(1) instanceof XWPFHyperlinkRun); - assertFalse(ph.getRuns().get(2) instanceof XWPFHyperlinkRun); - - XWPFHyperlinkRun link = (XWPFHyperlinkRun) ph.getRuns().get(1); - assertEquals("http://poi.apache.org/", link.getHyperlink(hyperlink).getURL()); - } - - @Test - void testComments() { - int numComments = 0; - for (XWPFParagraph p : comments.getParagraphs()) { - XWPFCommentsDecorator d = new XWPFCommentsDecorator(p, null); - if (d.getCommentText().length() > 0) { - numComments++; - assertEquals("\tComment by", d.getCommentText().substring(0, 11)); - } - } - assertEquals(3, numComments); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java deleted file mode 100644 index d47d5ae944..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java +++ /dev/null @@ -1,207 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.model; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFFooter; -import org.apache.poi.xwpf.usermodel.XWPFHeader; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -/** - * Tests for XWPF Header Footer Stuff - */ -class TestXWPFHeaderFooterPolicy { - private XWPFDocument noHeader; - private XWPFDocument header; - private XWPFDocument headerFooter; - private XWPFDocument footer; - private XWPFDocument oddEven; - private XWPFDocument diffFirst; - - @BeforeEach - void setUp() throws IOException { - noHeader = XWPFTestDataSamples.openSampleDocument("NoHeadFoot.docx"); - header = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx"); - headerFooter = XWPFTestDataSamples.openSampleDocument("SimpleHeadThreeColFoot.docx"); - footer = XWPFTestDataSamples.openSampleDocument("FancyFoot.docx"); - oddEven = XWPFTestDataSamples.openSampleDocument("PageSpecificHeadFoot.docx"); - diffFirst = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx"); - } - - @AfterEach - void tearDown() throws IOException { - noHeader.close(); - header.close(); - headerFooter.close(); - footer.close(); - oddEven.close(); - diffFirst.close(); - } - - @Test - void testPolicy() { - XWPFHeaderFooterPolicy policy; - - policy = noHeader.getHeaderFooterPolicy(); - assertNull(policy.getDefaultHeader()); - assertNull(policy.getDefaultFooter()); - - assertNull(policy.getHeader(1)); - assertNull(policy.getHeader(2)); - assertNull(policy.getHeader(3)); - assertNull(policy.getFooter(1)); - assertNull(policy.getFooter(2)); - assertNull(policy.getFooter(3)); - - - policy = header.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNull(policy.getDefaultFooter()); - - assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertNull(policy.getFooter(1)); - assertNull(policy.getFooter(2)); - assertNull(policy.getFooter(3)); - - - policy = footer.getHeaderFooterPolicy(); - assertNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - - assertNull(policy.getHeader(1)); - assertNull(policy.getHeader(2)); - assertNull(policy.getHeader(3)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - - - policy = headerFooter.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - - assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - - - policy = oddEven.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - assertNotNull(policy.getEvenPageHeader()); - assertNotNull(policy.getEvenPageFooter()); - - assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); - assertEquals(policy.getEvenPageHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); - assertEquals(policy.getEvenPageFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - - - policy = diffFirst.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getFirstPageFooter()); - assertNull(policy.getEvenPageHeader()); - assertNull(policy.getEvenPageFooter()); - - assertEquals(policy.getFirstPageHeader(), policy.getHeader(1)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertEquals(policy.getFirstPageFooter(), policy.getFooter(1)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - } - - @Test - void testCreate() throws Exception { - try (XWPFDocument doc = new XWPFDocument()) { - assertNull(doc.getHeaderFooterPolicy()); - assertEquals(0, doc.getHeaderList().size()); - assertEquals(0, doc.getFooterList().size()); - - XWPFHeaderFooterPolicy policy = doc.createHeaderFooterPolicy(); - assertNotNull(doc.getHeaderFooterPolicy()); - assertEquals(0, doc.getHeaderList().size()); - assertEquals(0, doc.getFooterList().size()); - - // Create a header and a footer - XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT); - XWPFFooter footer = policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT); - header.createParagraph().createRun().setText("Header Hello"); - footer.createParagraph().createRun().setText("Footer Bye"); - - - // Save, re-load, and check - try (XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc)) { - assertNotNull(docBack.getHeaderFooterPolicy()); - assertEquals(1, docBack.getHeaderList().size()); - assertEquals(1, docBack.getFooterList().size()); - - assertEquals("Header Hello\n", docBack.getHeaderList().get(0).getText()); - assertEquals("Footer Bye\n", docBack.getFooterList().get(0).getText()); - } - } - } - - @Test - void testContents() { - XWPFHeaderFooterPolicy policy; - - // Test a few simple bits off a simple header - policy = diffFirst.getHeaderFooterPolicy(); - - assertEquals( - "I am the header on the first page, and I" + '\u2019' + "m nice and simple\n", - policy.getFirstPageHeader().getText() - ); - assertEquals( - "First header column!\tMid header\tRight header!\n", - policy.getDefaultHeader().getText() - ); - - - // And a few bits off a more complex header - policy = oddEven.getHeaderFooterPolicy(); - - assertEquals( - "[ODD Page Header text]\n\n", - policy.getDefaultHeader().getText() - ); - assertEquals( - "[This is an Even Page, with a Header]\n\n", - policy.getEvenPageHeader().getText() - ); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java deleted file mode 100644 index 39673c3bba..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; - -class TestChangeTracking { - @Test - void detection() throws Exception { - try (XWPFDocument documentWithoutChangeTracking = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_off.docx")) { - assertFalse(documentWithoutChangeTracking.isTrackRevisions()); - - try (XWPFDocument documentWithChangeTracking = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_on.docx")) { - assertTrue(documentWithChangeTracking.isTrackRevisions()); - } - } - } - - @Test - void activateChangeTracking() throws Exception { - try (XWPFDocument document = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_off.docx")) { - assertFalse(document.isTrackRevisions()); - - document.setTrackRevisions(true); - - assertTrue(document.isTrackRevisions()); - } - } - - @Test - void integration() throws Exception { - try (XWPFDocument doc = new XWPFDocument()) { - - XWPFParagraph p1 = doc.createParagraph(); - - XWPFRun r1 = p1.createRun(); - r1.setText("Lorem ipsum dolor sit amet."); - doc.setTrackRevisions(true); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - doc.write(out); - - ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toByteArray()); - XWPFDocument document = new XWPFDocument(inputStream); - inputStream.close(); - - assertTrue(document.isTrackRevisions()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestColumn.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestColumn.java deleted file mode 100644 index de8d9541b9..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestColumn.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; -import java.io.IOException; -import static org.junit.jupiter.api.Assertions.assertEquals; - -class TestColumn { - @Test - void testAddNewColWithCorrectAmountOfColumns() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFTable table = doc.createTable(2, 4); - table.addNewCol(); - - int expectedNumberOfColumns = 5; - for (int i = 0; i < table.tableRows.size(); i++) { - assertEquals(expectedNumberOfColumns, table.tableRows.get(i).getTableCells().size()); - } - doc.close(); - } - - @Test - void testAddNewColWithEmptyTable() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFTable table = doc.createTable(0, 0); - table.removeRow(0); - table.addNewCol(); - - int expectedNumberOfColumnsInRow1 = 1; - int actualNumberOfColumnsInRow1 = table.tableRows.get(0).getTableCells().size(); - assertEquals(expectedNumberOfColumnsInRow1, actualNumberOfColumnsInRow1); - doc.close(); - } - - @Test - void testAddNewColWithDocx() throws Exception { - try (XWPFDocument doc = XWPFTestDataSamples - .openSampleDocument("TestTableColumns.docx")) { - XWPFTable table = doc.getTables().get(0); - table.addNewCol(); - - int expectedNumberOfColumns = 5; - for (int i = 0; i < table.tableRows.size(); i++) { - assertEquals(expectedNumberOfColumns, table.tableRows.get(i).getTableCells().size()); - } - } - } - - @Test - void testAddNewColWhenRowsHaveDifferentNumbersOfColumnsWithDocx() throws Exception { - try (XWPFDocument doc = XWPFTestDataSamples - .openSampleDocument("TestTableColumns.docx")) { - XWPFTable table = doc.getTables().get(1); - table.addNewCol(); - - int expectedNumberOfColumnsInRow1 = 5; - int actualNumberOfColumnsInRow1 = table.tableRows.get(0).getTableCells().size(); - assertEquals(expectedNumberOfColumnsInRow1, actualNumberOfColumnsInRow1); - - int expectedNumberOfColumnsInRow2 = 4; - int actualNumberOfColumnsInRow2 = table.tableRows.get(1).getTableCells().size(); - assertEquals(expectedNumberOfColumnsInRow2, actualNumberOfColumnsInRow2); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFAbstractNum.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFAbstractNum.java deleted file mode 100644 index e71c3a2413..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFAbstractNum.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertNull; - -import org.junit.jupiter.api.Test; - -public class TestXWPFAbstractNum { - - @Test - void getXmlObject() { - // minimal test to include generated classes in poi-ooxml-lite - XWPFAbstractNum num = new XWPFAbstractNum(); - assertNull(num.getCTAbstractNum()); - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java deleted file mode 100644 index 2974c879dc..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java +++ /dev/null @@ -1,264 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.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.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.util.List; - -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFRun.FontCharRange; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; - -class TestXWPFBugs { - @Test - void bug55802() throws Exception { - String blabla = - "Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n" + - "\nalt\u0131, yedi, sekiz, dokuz, on.\n" + - "\nK\u0131rm\u0131z\u0131 don,\n" + - "\ngel bizim bah\u00e7eye kon,\n" + - "\nsar\u0131 limon"; - try (XWPFDocument doc = new XWPFDocument()) { - XWPFRun run = doc.createParagraph().createRun(); - - for (String str : blabla.split("\n")) { - run.setText(str); - run.addBreak(); - } - - 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"); - run.setFontFamily("Arial", FontCharRange.hAnsi); - assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Arial"); - } - } - - @Test - void bug57312_NullPointException() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("57312.docx")) { - assertNotNull(doc); - - for (IBodyElement bodyElement : doc.getBodyElements()) { - BodyElementType elementType = bodyElement.getElementType(); - - if (elementType == BodyElementType.PARAGRAPH) { - XWPFParagraph paragraph = (XWPFParagraph) bodyElement; - - for (IRunElement iRunElem : paragraph.getIRuns()) { - - if (iRunElem instanceof XWPFRun) { - XWPFRun runElement = (XWPFRun) iRunElem; - - UnderlinePatterns underline = runElement.getUnderline(); - assertNotNull(underline); - - //System.out.println("Found: " + underline + ": " + runElement.getText(0)); - } - } - } - } - } - } - - @Test - void bug57495_getTableArrayInDoc() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - //let's create a few tables for the test - for (int i = 0; i < 3; i++) { - doc.createTable(2, 2); - } - XWPFTable table = doc.getTableArray(0); - assertNotNull(table); - //let's check also that returns the correct table - XWPFTable same = doc.getTables().get(0); - assertEquals(table, same); - } - } - - @Test - void bug57495_getParagraphArrayInTableCell() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - //let's create a table for the test - XWPFTable table = doc.createTable(2, 2); - assertNotNull(table); - XWPFParagraph p = table.getRow(0).getCell(0).getParagraphArray(0); - assertNotNull(p); - //let's check also that returns the correct paragraph - XWPFParagraph same = table.getRow(0).getCell(0).getParagraphs().get(0); - assertEquals(p, same); - } - } - - @Test - void bug57495_convertPixelsToEMUs() { - int pixels = 100; - int expectedEMU = 952500; - int result = Units.pixelToEMU(pixels); - assertEquals(expectedEMU, result); - } - - @Test - void test56392() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("56392.docx")) { - assertNotNull(doc); - } - } - - /** - * Removing a run needs to remove it from both Runs and IRuns - */ - @Test - void test57829() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) { - assertNotNull(doc); - assertEquals(3, doc.getParagraphs().size()); - - for (XWPFParagraph paragraph : doc.getParagraphs()) { - paragraph.removeRun(0); - assertNotNull(paragraph.getText()); - } - } - } - - /** - * Removing a run needs to take into account position of run if paragraph contains hyperlink runs - */ - @Test - void test58618() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("58618.docx")) { - XWPFParagraph para = (XWPFParagraph) doc.getBodyElements().get(0); - assertNotNull(para); - assertEquals("Some text some hyper links link link and some text.....", para.getText()); - XWPFRun run = para.insertNewRun(para.getRuns().size()); - run.setText("New Text"); - assertEquals("Some text some hyper links link link and some text.....New Text", para.getText()); - para.removeRun(para.getRuns().size() - 2); - assertEquals("Some text some hyper links link linkNew Text", para.getText()); - } - } - - @Test - void test59378() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("59378.docx")) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - doc.write(out); - out.close(); - - try (XWPFDocument doc2 = new XWPFDocument(new ByteArrayInputStream(out.toByteArray()))) { - assertNotNull(doc2); - } - - try (XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc)) { - assertNotNull(docBack); - } - } - } - - @Test - void test63788() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - - XWPFNumbering numbering = doc.createNumbering(); - - for (int i = 10; i >= 0; i--) { - addNumberingWithAbstractId(numbering, i); //add numbers in reverse order - } - - for (int i = 0; i <= 10; i++) { - assertEquals(i, numbering.getAbstractNum(BigInteger.valueOf(i)).getAbstractNum().getAbstractNumId().longValue()); - } - - //attempt to remove item with numId 2 - assertTrue(numbering.removeAbstractNum(BigInteger.valueOf(2))); - - for (int i = 0; i <= 10; i++) { - XWPFAbstractNum abstractNum = numbering.getAbstractNum(BigInteger.valueOf(i)); - - // we removed id "2", so this one should be empty, all others not - if (i == 2) { - assertNull(abstractNum, "Failed for " + i); - } else { - assertNotNull(abstractNum, "Failed for " + i); - assertEquals(i, abstractNum.getAbstractNum().getAbstractNumId().longValue()); - } - } - - // removing the same again fails - assertFalse(numbering.removeAbstractNum(BigInteger.valueOf(2))); - - // removing another one works - assertTrue(numbering.removeAbstractNum(BigInteger.valueOf(4))); - } - } - - private static void addNumberingWithAbstractId(XWPFNumbering documentNumbering, int id){ - // create a numbering scheme - CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance(); - // give the scheme an ID - cTAbstractNum.setAbstractNumId(BigInteger.valueOf(id)); - - XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum); - BigInteger abstractNumID = documentNumbering.addAbstractNum(abstractNum); - - documentNumbering.addNum(abstractNumID); - } - - @Test - public void test65099() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("65099.docx")) { - XWPFStyles styles = doc.getStyles(); - assertNotNull(styles); - - XWPFStyle normal = styles.getStyle("Normal"); - assertNotNull(normal); - - XWPFStyle style1 = styles.getStyle("EdfTitre3Car"); - assertNotNull(style1); - - List<XWPFStyle> list = styles.getUsedStyleList(normal); - assertNotNull(list); - assertEquals(1, list.size()); - - list = styles.getUsedStyleList(style1); - assertNotNull(list); - assertEquals(7, list.size()); - - assertThrows(NullPointerException.class, - () -> styles.getUsedStyleList(null), - "Pasisng in 'null' triggers an exception"); - - XWPFStyle style = doc.getStyles().getStyle("TableauGrille41"); - doc.getStyles().getUsedStyleList(style); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFChart.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFChart.java deleted file mode 100644 index eca90582e9..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFChart.java +++ /dev/null @@ -1,124 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData; -import org.apache.poi.xddf.usermodel.chart.XDDFChartData; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTTitle; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTTx; -import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -class TestXWPFChart { - - /** - * test method to check charts are not null - */ - @Test - void testRead() throws IOException { - try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("61745.docx")) { - List<XWPFChart> charts = sampleDoc.getCharts(); - assertNotNull(charts); - assertEquals(2, charts.size()); - checkData(charts.get(0)); - checkData(charts.get(1)); - } - } - - private void checkData(XWPFChart chart) { - assertNotNull(chart); - assertEquals(1, chart.getChartSeries().size()); - XDDFChartData data = chart.getChartSeries().get(0); - assertEquals(XDDFBarChartData.class, data.getClass()); - assertEquals(3, data.getSeriesCount()); - } - - /** - * test method to add chart title and check whether it's set - */ - @Test - void testChartTitle() throws IOException { - try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("61745.docx")) { - List<XWPFChart> charts = sampleDoc.getCharts(); - XWPFChart chart = charts.get(0); - CTChart ctChart = chart.getCTChart(); - CTTitle title = ctChart.getTitle(); - CTTx tx = title.addNewTx(); - CTTextBody rich = tx.addNewRich(); - rich.addNewBodyPr(); - rich.addNewLstStyle(); - CTTextParagraph p = rich.addNewP(); - CTRegularTextRun r = p.addNewR(); - r.addNewRPr(); - r.setT("XWPF CHART"); - assertEquals("XWPF CHART", chart.getCTChart().getTitle().getTx().getRich().getPArray(0).getRArray(0).getT()); - } - } - - /** - * test method to check relationship - */ - @Test - void testChartRelation() throws IOException { - try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("61745.docx")) { - List<XWPFChart> charts = sampleDoc.getCharts(); - XWPFChart chart = charts.get(0); - assertEquals(XWPFRelation.CHART.getContentType(), chart.getPackagePart().getContentType()); - assertEquals("/word/document.xml", chart.getParent().getPackagePart().getPartName().getName()); - assertEquals("/word/charts/chart1.xml", chart.getPackagePart().getPartName().getName()); - } - } - - /** - * test method to check adding chart in document - */ - @Test - void testAddChartsToNewDocument() throws InvalidFormatException, IOException { - try (XWPFDocument document = new XWPFDocument()) { - - XWPFChart chart = document.createChart(); - assertEquals(1, document.getCharts().size()); - assertNotNull(chart); - assertNotNull(chart.getCTChartSpace()); - assertNotNull(chart.getCTChart()); - assertEquals(XWPFChart.DEFAULT_HEIGHT, chart.getChartHeight()); - assertEquals(XWPFChart.DEFAULT_WIDTH, chart.getChartWidth()); - - XWPFChart chart2 = document.createChart(); - assertEquals(2, document.getCharts().size()); - assertNotNull(chart2); - assertNotNull(chart2.getCTChartSpace()); - assertNotNull(chart2.getCTChart()); - chart.setChartHeight(500500); - assertEquals(500500, chart.getChartHeight()); - - assertNotNull(XWPFTestDataSamples.writeOutAndReadBack(document)); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFComment.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFComment.java deleted file mode 100644 index 79ffa2d701..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFComment.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.util.Calendar; - -import static org.junit.jupiter.api.Assertions.*; - -class TestXWPFComment { - - @Test - void testText() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("comment.docx")) { - assertEquals(1, doc.getComments().length); - XWPFComment comment = doc.getComments()[0]; - assertEquals("Unbekannter Autor", comment.getAuthor()); - assertEquals("0", comment.getId()); - assertEquals("This is the first line\n\nThis is the second line", comment.getText()); - } - } - - @Test - public void testAddComment() throws IOException { - BigInteger cId = BigInteger.valueOf(0); - Calendar date = LocaleUtil.getLocaleCalendar(); - try (XWPFDocument docOut = new XWPFDocument()) { - assertNull(docOut.getDocComments()); - - XWPFComments comments = docOut.createComments(); - XWPFComment comment = comments.createComment(cId); - comment.setAuthor("Author"); - comment.setInitials("s"); - comment.setDate(date); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - assertEquals(1, docIn.getComments().length); - comment = docIn.getCommentByID(cId.toString()); - assertNotNull(comment); - assertEquals("Author", comment.getAuthor()); - assertEquals("s", comment.getInitials()); - assertEquals(date.getTimeInMillis(), comment.getDate().getTimeInMillis()); - } - } - - @Test - void testRemoveComment() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("comment.docx")) { - assertEquals(1, doc.getComments().length); - - doc.getDocComments().removeComment(0); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(doc); - assertEquals(0, docIn.getComments().length); - } - } - - @Test - void testCreateParagraph() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFComments comments = doc.createComments(); - XWPFComment comment = comments.createComment(BigInteger.ONE); - XWPFParagraph paragraph = comment.createParagraph(); - paragraph.createRun().setText("comment paragraph text"); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(doc); - XWPFComment xwpfComment = docIn.getCommentByID("1"); - assertEquals(1, xwpfComment.getParagraphs().size()); - String text = xwpfComment.getParagraphArray(0).getText(); - assertEquals("comment paragraph text", text); - } - } - - @Test - void testAddPicture() throws IOException, InvalidFormatException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFComments comments = doc.createComments(); - XWPFComment comment = comments.createComment(BigInteger.ONE); - XWPFParagraph paragraph = comment.createParagraph(); - XWPFRun r = paragraph.createRun(); - r.addPicture(new ByteArrayInputStream(new byte[0]), - Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); - - assertEquals(1, comments.getAllPictures().size()); - assertEquals(1, doc.getAllPackagePictures().size()); - } - } - - @Test - void testCreateTable() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFComments comments = doc.createComments(); - XWPFComment comment = comments.createComment(BigInteger.ONE); - comment.createTable(1, 1); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(doc); - XWPFComment xwpfComment = docIn.getCommentByID("1"); - assertEquals(1, xwpfComment.getTables().size()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFComments.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFComments.java deleted file mode 100644 index dad5ab877b..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFComments.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.math.BigInteger; - -import static org.junit.jupiter.api.Assertions.*; - -class TestXWPFComments { - - @Test - void testAddCommentsToDoc() throws IOException { - BigInteger cId = BigInteger.ZERO; - try (XWPFDocument docOut = new XWPFDocument()) { - assertNull(docOut.getDocComments()); - - // create comments - XWPFComments comments = docOut.createComments(); - assertNotNull(comments); - assertSame(comments, docOut.createComments()); - - // create comment - XWPFComment comment = comments.createComment(cId); - comment.setAuthor("Author"); - comment.createParagraph().createRun().setText("comment paragraph"); - - // apply comment to run text - XWPFParagraph paragraph = docOut.createParagraph(); - paragraph.getCTP().addNewCommentRangeStart().setId(cId); - paragraph.getCTP().addNewR().addNewT().setStringValue("HelloWorld"); - paragraph.getCTP().addNewCommentRangeEnd().setId(cId); - paragraph.getCTP().addNewR().addNewCommentReference().setId(cId); - - // check - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - assertNotNull(docIn.getDocComments()); - assertEquals(1, docIn.getComments().length); - comment = docIn.getCommentByID("0"); - assertTrue(null != comment); - assertEquals("Author", comment.getAuthor()); - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java deleted file mode 100644 index db1b969b58..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java +++ /dev/null @@ -1,483 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.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.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; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ooxml.POIXMLDocumentPart; -import org.apache.poi.ooxml.POIXMLProperties; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.xwpf.XWPFTestDataSamples; -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.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); -// } - } - assertTrue(found); - - pack.close(); - doc.close(); - } - - @Test - void testOpen() throws Exception { - // Simple file - try (XWPFDocument xml1 = XWPFTestDataSamples.openSampleDocument("sample.docx")) { - // Check it has key parts - assertNotNull(xml1.getDocument()); - assertNotNull(xml1.getDocument().getBody()); - assertNotNull(xml1.getStyle()); - } - - // Complex file - try (XWPFDocument xml2 = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx")) { - assertNotNull(xml2.getDocument()); - assertNotNull(xml2.getDocument().getBody()); - assertNotNull(xml2.getStyle()); - } - } - - @Test - void testMetadataBasics() throws IOException { - try (XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("sample.docx")) { - assertNotNull(xml.getProperties().getCoreProperties()); - assertNotNull(xml.getProperties().getExtendedProperties()); - - assertEquals("Microsoft Office Word", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); - assertEquals(1315, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters()); - assertEquals(10, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); - - assertNull(xml.getProperties().getCoreProperties().getTitle()); - assertFalse(xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().isPresent()); - } - } - - @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(); - } - - @Test - void testWorkbookProperties() throws Exception { - XWPFDocument doc = new XWPFDocument(); - POIXMLProperties props = doc.getProperties(); - assertNotNull(props); - assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication()); - doc.close(); - } - - @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(); - } - - @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]); - } - 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(); - } - - @Test - void testAddHyperlink() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx")) { - XWPFParagraph p = doc.createParagraph(); - XWPFHyperlinkRun h = p.createHyperlinkRun("https://poi.apache.org/"); - h.setText("Apache POI"); - - assertEquals("rId7", h.getHyperlinkId()); - - assertEquals("https://poi.apache.org/", h.getHyperlink(doc).getURL()); - assertEquals(p.getRuns().size(), 1); - assertEquals(p.getRuns().get(0), h); - - h = p.createHyperlinkRun("https://poi.apache.org/"); - h.setText("Apache POI"); - - assertEquals("rId8", h.getHyperlinkId()); - } - } - - @Test - void testRemoveBodyElement() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) { - assertEquals(3, doc.getParagraphs().size()); - assertEquals(3, doc.getBodyElements().size()); - - XWPFParagraph p1 = doc.getParagraphs().get(0); - XWPFParagraph p2 = doc.getParagraphs().get(1); - XWPFParagraph p3 = doc.getParagraphs().get(2); - - assertEquals(p1, doc.getBodyElements().get(0)); - assertEquals(p1, doc.getParagraphs().get(0)); - assertEquals(p2, doc.getBodyElements().get(1)); - assertEquals(p2, doc.getParagraphs().get(1)); - assertEquals(p3, doc.getBodyElements().get(2)); - assertEquals(p3, doc.getParagraphs().get(2)); - - // Add another - XWPFParagraph p4 = doc.createParagraph(); - - assertEquals(4, doc.getParagraphs().size()); - assertEquals(4, doc.getBodyElements().size()); - assertEquals(p1, doc.getBodyElements().get(0)); - assertEquals(p1, doc.getParagraphs().get(0)); - assertEquals(p2, doc.getBodyElements().get(1)); - assertEquals(p2, doc.getParagraphs().get(1)); - assertEquals(p3, doc.getBodyElements().get(2)); - assertEquals(p3, doc.getParagraphs().get(2)); - assertEquals(p4, doc.getBodyElements().get(3)); - assertEquals(p4, doc.getParagraphs().get(3)); - - // Remove the 2nd - assertTrue(doc.removeBodyElement(1)); - assertEquals(3, doc.getParagraphs().size()); - assertEquals(3, doc.getBodyElements().size()); - - assertEquals(p1, doc.getBodyElements().get(0)); - assertEquals(p1, doc.getParagraphs().get(0)); - assertEquals(p3, doc.getBodyElements().get(1)); - assertEquals(p3, doc.getParagraphs().get(1)); - assertEquals(p4, doc.getBodyElements().get(2)); - assertEquals(p4, doc.getParagraphs().get(2)); - - // Remove the 1st - assertTrue(doc.removeBodyElement(0)); - assertEquals(2, doc.getParagraphs().size()); - assertEquals(2, doc.getBodyElements().size()); - - assertEquals(p3, doc.getBodyElements().get(0)); - assertEquals(p3, doc.getParagraphs().get(0)); - assertEquals(p4, doc.getBodyElements().get(1)); - assertEquals(p4, doc.getParagraphs().get(1)); - - // Remove the last - assertTrue(doc.removeBodyElement(1)); - assertEquals(1, doc.getParagraphs().size()); - assertEquals(1, doc.getBodyElements().size()); - - assertEquals(p3, doc.getBodyElements().get(0)); - assertEquals(p3, doc.getParagraphs().get(0)); - } - } - - @Test - void testRegisterPackagePictureData() throws IOException, InvalidFormatException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx")) { - /* manually assemble a new image package part*/ - OPCPackage opcPkg = doc.getPackage(); - XWPFRelation jpgRelation = XWPFRelation.IMAGE_JPEG; - PackagePartName partName = PackagingURIHelper.createPartName(jpgRelation.getDefaultFileName().replace('#', '2')); - PackagePart newImagePart = opcPkg.createPart(partName, jpgRelation.getContentType()); - byte[] nature1 = XWPFTestDataSamples.getImage("abstract4.jpg"); - OutputStream os = newImagePart.getOutputStream(); - os.write(nature1); - os.close(); - XWPFHeader xwpfHeader = doc.getHeaderArray(0); - XWPFPictureData newPicData = new XWPFPictureData(newImagePart); - /* new part is now ready to rumble */ - - assertFalse(xwpfHeader.getAllPictures().contains(newPicData)); - assertFalse(doc.getAllPictures().contains(newPicData)); - assertFalse(doc.getAllPackagePictures().contains(newPicData)); - - doc.registerPackagePictureData(newPicData); - - assertFalse(xwpfHeader.getAllPictures().contains(newPicData)); - assertFalse(doc.getAllPictures().contains(newPicData)); - assertTrue(doc.getAllPackagePictures().contains(newPicData)); - - doc.getPackage().revert(); - opcPkg.close(); - } - } - - @Test - void testFindPackagePictureData() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx")) { - byte[] nature1 = XWPFTestDataSamples.getImage("nature1.gif"); - XWPFPictureData part = doc.findPackagePictureData(nature1, Document.PICTURE_TYPE_GIF); - assertNotNull(part); - assertTrue(doc.getAllPictures().contains(part)); - assertTrue(doc.getAllPackagePictures().contains(part)); - doc.getPackage().revert(); - } - } - - @Test - void testGetAllPictures() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx")) { - List<XWPFPictureData> allPictures = doc.getAllPictures(); - List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures(); - - assertNotNull(allPictures); - assertEquals(3, allPictures.size()); - for (XWPFPictureData xwpfPictureData : allPictures) { - assertTrue(allPackagePictures.contains(xwpfPictureData)); - } - - assertThrows(UnsupportedOperationException.class, () -> allPictures.add(allPictures.get(0)), "This list must be unmodifiable!"); - - doc.getPackage().revert(); - } - } - - @Test - void testGetAllPackagePictures() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx")) { - List<XWPFPictureData> allPackagePictures = doc.getAllPackagePictures(); - - assertNotNull(allPackagePictures); - assertEquals(5, allPackagePictures.size()); - - assertThrows(UnsupportedOperationException.class, () -> allPackagePictures.add(allPackagePictures.get(0)), "This list must be unmodifiable!"); - - doc.getPackage().revert(); - } - } - - @Test - void testPictureHandlingSimpleFile() throws IOException, InvalidFormatException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx")) { - assertEquals(1, doc.getAllPackagePictures().size()); - byte[] newPic = XWPFTestDataSamples.getImage("abstract4.jpg"); - String id1 = doc.addPictureData(newPic, Document.PICTURE_TYPE_JPEG); - assertEquals(2, doc.getAllPackagePictures().size()); - /* copy data, to avoid instance-equality */ - byte[] newPicCopy = Arrays.copyOf(newPic, newPic.length); - String id2 = doc.addPictureData(newPicCopy, Document.PICTURE_TYPE_JPEG); - assertEquals(id1, id2); - doc.getPackage().revert(); - } - } - - @Test - void testPictureHandlingHeaderDocumentImages() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_2.docx")) { - assertEquals(1, doc.getAllPictures().size()); - assertEquals(1, doc.getAllPackagePictures().size()); - assertEquals(1, doc.getHeaderArray(0).getAllPictures().size()); - doc.getPackage().revert(); - } - } - - @Test - void testPictureHandlingComplex() throws IOException, InvalidFormatException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx")) { - XWPFHeader xwpfHeader = doc.getHeaderArray(0); - - assertEquals(3, doc.getAllPictures().size()); - assertEquals(3, xwpfHeader.getAllPictures().size()); - assertEquals(5, doc.getAllPackagePictures().size()); - - byte[] nature1 = XWPFTestDataSamples.getImage("nature1.jpg"); - String id = doc.addPictureData(nature1, Document.PICTURE_TYPE_JPEG); - POIXMLDocumentPart part1 = xwpfHeader.getRelationById("rId1"); - XWPFPictureData part2 = (XWPFPictureData) doc.getRelationById(id); - assertSame(part1, part2); - - doc.getPackage().revert(); - } - } - - @Test - void testZeroLengthLibreOfficeDocumentWithWaterMarkHeader() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("zero-length.docx")) { - POIXMLProperties properties = doc.getProperties(); - - assertNotNull(properties.getCoreProperties()); - - XWPFHeader headerArray = doc.getHeaderArray(0); - assertEquals(1, headerArray.getAllPictures().size()); - assertEquals("image1.png", headerArray.pictures.get(0).getFileName()); - assertEquals("", headerArray.getText()); - - POIXMLProperties.ExtendedProperties extendedProperties = properties.getExtendedProperties(); - assertNotNull(extendedProperties); - assertEquals(0, extendedProperties.getUnderlyingProperties().getCharacters()); - } - } - - @Test - void testSettings() throws IOException { - XWPFSettings settings = new XWPFSettings(); - assertEquals(100, settings.getZoomPercent()); - settings.setZoomPercent(50); - assertEquals(50, settings.getZoomPercent()); - - assertFalse(settings.getEvenAndOddHeadings()); - settings.setEvenAndOddHeadings(true); - assertTrue(settings.getEvenAndOddHeadings()); - - assertFalse(settings.getMirrorMargins()); - settings.setMirrorMargins(true); - assertTrue(settings.getMirrorMargins()); - - XWPFDocument doc = new XWPFDocument(); - assertEquals(100, doc.getZoomPercent()); - - doc.setZoomPercent(50); - assertEquals(50, doc.getZoomPercent()); - - doc.setZoomPercent(200); - assertEquals(200, doc.getZoomPercent()); - - assertFalse(doc.getEvenAndOddHeadings()); - doc.setEvenAndOddHeadings(true); - assertTrue(doc.getEvenAndOddHeadings()); - - assertFalse(doc.getMirrorMargins()); - doc.setMirrorMargins(true); - assertTrue(doc.getMirrorMargins()); - - XWPFDocument back = XWPFTestDataSamples.writeOutAndReadBack(doc); - assertEquals(200, back.getZoomPercent()); - back.close(); - -// OutputStream out = new FileOutputStream("/tmp/testZoom.docx"); -// doc.write(out); -// out.close(); - - doc.close(); - } - - @Test - void testEnforcedWith() throws IOException { - try (XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("EnforcedWith.docx")) { - assertTrue(docx.isEnforcedProtection()); - } - } - - @Test - @Disabled("XWPF should be able to write to a new Stream when opened Read-Only") - void testWriteFromReadOnlyOPC() throws Exception { - 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()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnote.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnote.java deleted file mode 100644 index e375d710fb..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnote.java +++ /dev/null @@ -1,157 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.List; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdnRef; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; - -class TestXWPFEndnote { - - private XWPFDocument docOut; - private String p1Text; - private String p2Text; - private BigInteger endnoteId; - private XWPFEndnote endnote; - - @BeforeEach - void setUp() { - docOut = new XWPFDocument(); - p1Text = "First paragraph in footnote"; - p2Text = "Second paragraph in footnote"; - - // NOTE: XWPFDocument.createEndnote() delegates directly - // to XWPFEndnotes.createEndnote() so this tests - // both creation of new XWPFEndnotes in document - // and XWPFEndnotes.createEndnote(); - - // NOTE: Creating the endnote does not automatically - // create a first paragraph. - endnote = docOut.createEndnote(); - endnoteId = endnote.getId(); - - } - - @Test - void testAddParagraphsToFootnote() throws IOException { - - // Add a run to the first paragraph: - - XWPFParagraph p1 = endnote.createParagraph(); - p1.createRun().setText(p1Text); - - // Create a second paragraph: - - XWPFParagraph p = endnote.createParagraph(); - assertNotNull(p, "Paragraph is null"); - p.createRun().setText(p2Text); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - XWPFEndnote testEndnote = docIn.getEndnoteByID(endnoteId.intValue()); - assertNotNull(testEndnote); - - assertEquals(2, testEndnote.getParagraphs().size()); - XWPFParagraph testP1 = testEndnote.getParagraphs().get(0); - assertEquals(p1Text, testP1.getText()); - - XWPFParagraph testP2 = testEndnote.getParagraphs().get(1); - assertEquals(p2Text, testP2.getText()); - - // The first paragraph added using createParagraph() should - // have the required footnote reference added to the first - // run. - - // Verify that we have a footnote reference in the first paragraph and not - // in the second paragraph. - - XWPFRun r1 = testP1.getRuns().get(0); - assertNotNull(r1); - assertTrue(r1.getCTR().getEndnoteRefList().size() > 0, "No endnote reference in testP1"); - assertNotNull(r1.getCTR().getEndnoteRefArray(0), "No endnote reference in testP1"); - - XWPFRun r2 = testP2.getRuns().get(0); - assertNotNull(r2, "Expected a run in testP2"); - assertEquals(0, r2.getCTR().getEndnoteRefList().size(), "Found an endnote reference in testP2"); - - } - - @Test - void testAddTableToFootnote() throws IOException { - XWPFTable table = endnote.createTable(); - assertNotNull(table); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - XWPFEndnote testFootnote = docIn.getEndnoteByID(endnoteId.intValue()); - XWPFTable testTable = testFootnote.getTableArray(0); - assertNotNull(testTable); - - table = endnote.createTable(2, 3); - assertEquals(2, table.getNumberOfRows()); - assertEquals(3, table.getRow(0).getTableCells().size()); - - // If the table is the first body element of the footnote then - // a paragraph with the footnote reference should have been - // added automatically. - - assertEquals(3, endnote.getBodyElements().size(), "Expected 3 body elements"); - IBodyElement testP1 = endnote.getBodyElements().get(0); - assertTrue(testP1 instanceof XWPFParagraph, "Expected a paragraph, got " + testP1.getClass().getSimpleName()); - XWPFRun r1 = ((XWPFParagraph)testP1).getRuns().get(0); - assertNotNull(r1); - assertTrue(r1.getCTR().getEndnoteRefList().size() > 0, "No footnote reference in testP1"); - assertNotNull(r1.getCTR().getEndnoteRefArray(0), "No footnote reference in testP1"); - - } - - @Test - void testRemoveEndnote() { - // NOTE: XWPFDocument.removeEndnote() delegates directly to - // XWPFEndnotes. - docOut.createEndnote(); - assertEquals(2, docOut.getEndnotes().size(), "Expected 2 endnotes"); - assertNotNull(docOut.getEndnotes().get(1), "Didn't get second endnote"); - boolean result = docOut.removeEndnote(0); - assertTrue(result, "Remove endnote did not return true"); - assertEquals(1, docOut.getEndnotes().size(), "Expected 1 endnote after removal"); - } - - @Test - void testAddFootnoteRefToParagraph() { - XWPFParagraph p = docOut.createParagraph(); - List<XWPFRun> runs = p.getRuns(); - assertEquals(0, runs.size(), "Expected no runs in new paragraph"); - p.addFootnoteReference(endnote); - XWPFRun run = p.getRuns().get(0); - CTR ctr = run.getCTR(); - assertNotNull(run, "Expected a run"); - List<CTFtnEdnRef> endnoteRefList = ctr.getEndnoteReferenceList(); - assertNotNull(endnoteRefList); - CTFtnEdnRef ref = endnoteRefList.get(0); - assertNotNull(ref); - assertEquals(endnote.getId(), ref.getId(), "Endnote ID and reference ID did not match"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnotes.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnotes.java deleted file mode 100644 index 7292553715..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFEndnotes.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -import java.io.IOException; -import java.math.BigInteger; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn; - -class TestXWPFEndnotes { - - @Test - void testCreateEndnotes() throws IOException{ - try (XWPFDocument docOut = new XWPFDocument()) { - XWPFEndnotes footnotes = docOut.createEndnotes(); - assertNotNull(footnotes); - - XWPFEndnotes secondFootnotes = docOut.createEndnotes(); - assertSame(footnotes, secondFootnotes); - } - } - - @Test - void testAddEndnotesToDocument() throws IOException { - try (XWPFDocument docOut = new XWPFDocument()) { - // NOTE: XWPFDocument.createEndnote() delegates directly - // to XWPFFootnotes.createEndnote() so this tests - // both creation of new XWPFFootnotes in document - // and XWPFFootnotes.createEndnote(); - XWPFEndnote endnote = docOut.createEndnote(); - BigInteger noteId = endnote.getId(); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - XWPFEndnote note = docIn.getEndnoteByID(noteId.intValue()); - assertNotNull(note); - assertEquals(STFtnEdn.NORMAL, note.getCTFtnEdn().getType()); - } - } - -} - diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnote.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnote.java deleted file mode 100644 index 9d8e563326..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnote.java +++ /dev/null @@ -1,159 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.junit.jupiter.api.Assertions.*; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.List; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdnRef; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; - -class TestXWPFFootnote { - - private XWPFDocument docOut; - private String p1Text; - private String p2Text; - private BigInteger footnoteId; - private XWPFFootnote footnote; - - @BeforeEach - void setUp() { - docOut = new XWPFDocument(); - p1Text = "First paragraph in footnote"; - p2Text = "Second paragraph in footnote"; - - // NOTE: XWPFDocument.createFootnote() delegates directly - // to XWPFFootnotes.createFootnote() so this tests - // both creation of new XWPFFootnotes in document - // and XWPFFootnotes.createFootnote(); - - // NOTE: Creating the footnote does not automatically - // create a first paragraph. - footnote = docOut.createFootnote(); - footnoteId = footnote.getId(); - - } - - @Test - void testAddParagraphsToFootnote() throws IOException { - - // Add a run to the first paragraph: - - XWPFParagraph p1 = footnote.createParagraph(); - p1.createRun().setText(p1Text); - - // Create a second paragraph: - - XWPFParagraph p = footnote.createParagraph(); - assertNotNull(p, "Paragraph is null"); - p.createRun().setText(p2Text); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - XWPFFootnote testFootnote = docIn.getFootnoteByID(footnoteId.intValue()); - assertNotNull(testFootnote); - - assertEquals(2, testFootnote.getParagraphs().size()); - XWPFParagraph testP1 = testFootnote.getParagraphs().get(0); - assertEquals(p1Text, testP1.getText()); - - XWPFParagraph testP2 = testFootnote.getParagraphs().get(1); - assertEquals(p2Text, testP2.getText()); - - // The first paragraph added using createParagraph() should - // have the required footnote reference added to the first - // run. - - // Verify that we have a footnote reference in the first paragraph and not - // in the second paragraph. - - XWPFRun r1 = testP1.getRuns().get(0); - assertNotNull(r1); - assertTrue(r1.getCTR().getFootnoteRefList().size() > 0, "No footnote reference in testP1"); - assertNotNull(r1.getCTR().getFootnoteRefArray(0), "No footnote reference in testP1"); - - XWPFRun r2 = testP2.getRuns().get(0); - assertNotNull(r2, "Expected a run in testP2"); - assertEquals(0, r2.getCTR().getFootnoteRefList().size(), "Found a footnote reference in testP2"); - - } - - @Test - void testAddTableToFootnote() throws IOException { - XWPFTable table = footnote.createTable(); - assertNotNull(table); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - XWPFFootnote testFootnote = docIn.getFootnoteByID(footnoteId.intValue()); - XWPFTable testTable = testFootnote.getTableArray(0); - assertNotNull(testTable); - - table = footnote.createTable(2, 3); - assertEquals(2, table.getNumberOfRows()); - assertEquals(3, table.getRow(0).getTableCells().size()); - - // If the table is the first body element of the footnote then - // a paragraph with the footnote reference should have been - // added automatically. - - assertEquals(3, footnote.getBodyElements().size(), "Expected 3 body elements"); - IBodyElement testP1 = footnote.getBodyElements().get(0); - assertTrue(testP1 instanceof XWPFParagraph, "Expected a paragraph, got " + testP1.getClass().getSimpleName()); - XWPFRun r1 = ((XWPFParagraph)testP1).getRuns().get(0); - assertNotNull(r1); - assertTrue(r1.getCTR().getFootnoteRefList().size() > 0, "No footnote reference in testP1"); - assertNotNull(r1.getCTR().getFootnoteRefArray(0), "No footnote reference in testP1"); - } - - @Test - void testRemoveFootnote() { - // NOTE: XWPFDocument.removeFootnote() delegates directly to - // XWPFFootnotes. - docOut.createFootnote(); - assertEquals(2, docOut.getFootnotes().size(), "Expected 2 footnotes"); - assertNotNull(docOut.getFootnotes().get(1), "Didn't get second footnote"); - boolean result = docOut.removeFootnote(0); - assertTrue(result, "Remove footnote did not return true"); - assertEquals(1, docOut.getFootnotes().size(), "Expected 1 footnote after removal"); - } - - @Test - void testAddFootnoteRefToParagraph() { - XWPFParagraph p = docOut.createParagraph(); - List<XWPFRun> runs = p.getRuns(); - assertEquals(0, runs.size(), "Expected no runs in new paragraph"); - p.addFootnoteReference(footnote); - XWPFRun run = p.getRuns().get(0); - CTR ctr = run.getCTR(); - assertNotNull(run, "Expected a run"); - CTFtnEdnRef ref = ctr.getFootnoteReferenceList().get(0); - assertNotNull(ref); - // FIXME: Verify that the footnote reference is w:endnoteReference, not w:footnoteReference - assertEquals(footnote.getId(), ref.getId(), "Footnote ID and reference ID did not match"); - - - - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java deleted file mode 100644 index e73baa056c..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.List; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -class TestXWPFFootnotes { - @Test - void testCreateFootnotes() throws IOException{ - try (XWPFDocument docOut = new XWPFDocument()) { - - XWPFAbstractFootnotesEndnotes footnotes = docOut.createFootnotes(); - - assertNotNull(footnotes); - - XWPFAbstractFootnotesEndnotes secondFootnotes = docOut.createFootnotes(); - - assertSame(footnotes, secondFootnotes); - } - } - - @Test - void testAddFootnotesToDocument() throws IOException { - try (XWPFDocument docOut = new XWPFDocument()) { - - // NOTE: XWPFDocument.createFootnote() delegates directly - // to XWPFFootnotes.createFootnote() so this tests - // both creation of new XWPFFootnotes in document - // and XWPFFootnotes.createFootnote(); - XWPFFootnote footnote = docOut.createFootnote(); - BigInteger noteId = footnote.getId(); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - XWPFFootnote note = docIn.getFootnoteByID(noteId.intValue()); - assertNotNull(note); - assertEquals(STFtnEdn.NORMAL, note.getCTFtnEdn().getType()); - } - } - - /** - * Bug 55066 - avoid double loading the footnotes - */ - @Test - void testLoadFootnotesOnce() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx")) { - List<XWPFFootnote> footnotes = doc.getFootnotes(); - int hits = 0; - for (XWPFFootnote fn : footnotes) { - for (IBodyElement e : fn.getBodyElements()) { - if (e instanceof XWPFParagraph) { - String txt = ((XWPFParagraph) e).getText(); - if (txt.contains("Footnote_sdt")) { - hits++; - } - } - } - } - assertEquals(1, hits, "Load footnotes once"); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java deleted file mode 100644 index 73d2eebe20..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java +++ /dev/null @@ -1,261 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.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 java.io.IOException; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; - -final class TestXWPFHeader { - - @Test - void testSimpleHeader() throws IOException { - try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerFooter.docx")) { - - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - - XWPFHeader header = policy.getDefaultHeader(); - XWPFFooter footer = policy.getDefaultFooter(); - assertNotNull(header); - assertNotNull(footer); - } - } - - @Test - void testImageInHeader() throws IOException { - try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx")) { - - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - - XWPFHeader header = policy.getDefaultHeader(); - - assertNotNull(header.getRelations()); - assertEquals(1, header.getRelations().size()); - } - } - - @Test - void testSetHeader() throws IOException { - try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx")) { - // no header is set (yet) - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - assertNull(policy.getDefaultHeader()); - assertNull(policy.getFirstPageHeader()); - assertNull(policy.getDefaultFooter()); - assertNull(policy.getFirstPageFooter()); - - CTP ctP1 = CTP.Factory.newInstance(); - CTR ctR1 = ctP1.addNewR(); - CTText t = ctR1.addNewT(); - String tText = "Paragraph in header"; - t.setStringValue(tText); - - // Commented MB 23 May 2010 - //CTP ctP2 = CTP.Factory.newInstance(); - //CTR ctR2 = ctP2.addNewR(); - //CTText t2 = ctR2.addNewT(); - //t2.setStringValue("Second paragraph.. for footer"); - - // Create two paragraphs for insertion into the footer. - // Previously only one was inserted MB 23 May 2010 - CTP ctP2 = CTP.Factory.newInstance(); - CTR ctR2 = ctP2.addNewR(); - CTText t2 = ctR2.addNewT(); - t2.setStringValue("First paragraph for the footer"); - - CTP ctP3 = CTP.Factory.newInstance(); - CTR ctR3 = ctP3.addNewR(); - CTText t3 = ctR3.addNewT(); - t3.setStringValue("Second paragraph for the footer"); - - XWPFParagraph p1 = new XWPFParagraph(ctP1, sampleDoc); - XWPFParagraph[] pars = new XWPFParagraph[1]; - pars[0] = p1; - - XWPFParagraph p2 = new XWPFParagraph(ctP2, sampleDoc); - XWPFParagraph p3 = new XWPFParagraph(ctP3, sampleDoc); - XWPFParagraph[] pars2 = new XWPFParagraph[2]; - pars2[0] = p2; - pars2[1] = p3; - - // Set headers - XWPFHeader headerD = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars); - XWPFHeader headerF = policy.createHeader(XWPFHeaderFooterPolicy.FIRST); - // Set a default footer and capture the returned XWPFFooter object. - XWPFFooter footerD = policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars2); - XWPFFooter footerF = policy.createFooter(XWPFHeaderFooterPolicy.FIRST); - - // Ensure the headers and footer were set correctly.... - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getDefaultFooter()); - assertNotNull(policy.getFirstPageFooter()); - // ....and that the footer object captured above contains two - // paragraphs of text. - assertEquals(2, footerD.getParagraphs().size()); - assertEquals(0, footerF.getParagraphs().size()); - - // Check the header created with the paragraph got them, and the one - // created without got none - assertEquals(1, headerD.getParagraphs().size()); - assertEquals(tText, headerD.getParagraphs().get(0).getText()); - - assertEquals(0, headerF.getParagraphs().size()); - - // As an additional check, recover the defauls footer and - // make sure that it contains two paragraphs of text and that - // both do hold what is expected. - footerD = policy.getDefaultFooter(); - XWPFParagraph[] paras = footerD.getParagraphs().toArray(new XWPFParagraph[0]); - - assertEquals(2, paras.length); - assertEquals("First paragraph for the footer", paras[0].getText()); - assertEquals("Second paragraph for the footer", paras[1].getText()); - - - // Add some text to the empty header - String fText1 = "New Text!"; - String fText2 = "More Text!"; - headerF.createParagraph().insertNewRun(0).setText(fText1); - headerF.createParagraph().insertNewRun(0).setText(fText2); - // headerF.getParagraphs().get(0).insertNewRun(0).setText(fText1); - - // Check it - assertEquals(tText, headerD.getParagraphs().get(0).getText()); - assertEquals(fText1, headerF.getParagraphs().get(0).getText()); - assertEquals(fText2, headerF.getParagraphs().get(1).getText()); - - - // Save, re-open, ensure it's all still there - XWPFDocument reopened = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc); - policy = reopened.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getFirstPageHeader()); - assertNull(policy.getEvenPageHeader()); - assertNotNull(policy.getDefaultFooter()); - assertNotNull(policy.getFirstPageFooter()); - assertNull(policy.getEvenPageFooter()); - - // Check the new headers still have their text - headerD = policy.getDefaultHeader(); - headerF = policy.getFirstPageHeader(); - assertEquals(tText, headerD.getParagraphs().get(0).getText()); - assertEquals(fText1, headerF.getParagraphs().get(0).getText()); - assertEquals(fText2, headerF.getParagraphs().get(1).getText()); - - // Check the new footers have their new text too - footerD = policy.getDefaultFooter(); - paras = footerD.getParagraphs().toArray(new XWPFParagraph[0]); - footerF = policy.getFirstPageFooter(); - - assertEquals(2, paras.length); - assertEquals("First paragraph for the footer", paras[0].getText()); - assertEquals("Second paragraph for the footer", paras[1].getText()); - assertEquals(1, footerF.getParagraphs().size()); - } - } - - @Test - void testSetWatermark() throws IOException { - try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx")) { - - // No header is set (yet) - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - assertNull(policy.getDefaultHeader()); - assertNull(policy.getFirstPageHeader()); - assertNull(policy.getDefaultFooter()); - - policy.createWatermark("DRAFT"); - - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getEvenPageHeader()); - - // Re-open, and check - XWPFDocument reopened = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc); - policy = reopened.getHeaderFooterPolicy(); - - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getEvenPageHeader()); - } - } - - @Test - void testSetWatermarkOnEmptyDoc() throws IOException { - try (XWPFDocument sampleDoc = new XWPFDocument()) { - - // No header is set (yet) - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - assertNull(policy); - - policy = sampleDoc.createHeaderFooterPolicy(); - policy.createWatermark("DRAFT"); - - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getEvenPageHeader()); - - // Re-open, and check - XWPFDocument reopened = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc); - policy = reopened.getHeaderFooterPolicy(); - - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getEvenPageHeader()); - } - } - - @Disabled - void testAddPictureData() { - // TODO - } - - @Disabled - void testGetAllPictures() { - // TODO - } - - @Disabled - void testGetAllPackagePictures() { - // TODO - } - - @Disabled - void testGetPictureDataById() { - // TODO - } - - @Test - void bug60293() throws Exception { - //test handling of non-standard header/footer options - try (XWPFDocument xwpf = XWPFTestDataSamples.openSampleDocument("60293.docx")) { - assertEquals(3, xwpf.getHeaderList().size()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java deleted file mode 100644 index 5e34741aed..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.io.IOException; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -/** - * @author Paolo Mottadelli - */ -public final class TestXWPFHeadings { - private static final String HEADING1 = "Heading1"; - - @Test - void testSetParagraphStyle() throws IOException { - //new clean instance of paragraph - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("heading123.docx")) { - XWPFParagraph p = doc.createParagraph(); - XWPFRun run = p.createRun(); - run.setText("Heading 1"); - - CTSdtBlock block = doc.getDocument().getBody().addNewSdt(); - assertNotNull(block); - - assertNull(p.getStyle()); - p.setStyle(HEADING1); - assertEquals(HEADING1, p.getCTP().getPPr().getPStyle().getVal()); - - doc.createTOC(); - /* - // TODO - finish this test - if (false) { - CTStyles styles = doc.getStyle(); - CTStyle style = styles.addNewStyle(); - style.setType(STStyleType.PARAGRAPH); - style.setStyleId("Heading1"); - } - - if (false) { - File file = TempFile.createTempFile("testHeaders", ".docx"); - OutputStream out = new FileOutputStream(file); - doc.write(out); - out.close(); - } - */ - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java deleted file mode 100644 index c1806c946a..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java +++ /dev/null @@ -1,156 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.math.BigInteger; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl; - -class TestXWPFNumbering { - - @Test - void testCompareAbstractNum() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx")) { - XWPFNumbering numbering = doc.getNumbering(); - BigInteger numId = BigInteger.valueOf(1); - assertTrue(numbering.numExist(numId)); - XWPFNum num = numbering.getNum(numId); - BigInteger abstrNumId = num.getCTNum().getAbstractNumId().getVal(); - XWPFAbstractNum abstractNum = numbering.getAbstractNum(abstrNumId); - BigInteger compareAbstractNum = numbering.getIdOfAbstractNum(abstractNum); - assertEquals(abstrNumId, compareAbstractNum); - } - } - - @Test - void testAddNumberingToDoc() throws IOException { - BigInteger abstractNumId = BigInteger.valueOf(1); - BigInteger numId = BigInteger.valueOf(1); - - XWPFDocument docOut = new XWPFDocument(); - XWPFNumbering numbering = docOut.createNumbering(); - numId = numbering.addNum(abstractNumId); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - numbering = docIn.getNumbering(); - assertTrue(numbering.numExist(numId)); - XWPFNum num = numbering.getNum(numId); - - BigInteger compareAbstractNum = num.getCTNum().getAbstractNumId().getVal(); - assertEquals(abstractNumId, compareAbstractNum); - } - - @Test - void testAddAbstractNumIfAbstractNumNotEqualNull() throws IOException { - BigInteger abstractNumId = BigInteger.valueOf(1); - XWPFDocument docOut = new XWPFDocument(); - XWPFNumbering numbering = docOut.createNumbering(); - - CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance(); - // must set the AbstractNumId, Otherwise fail - cTAbstractNum.setAbstractNumId(abstractNumId); - XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum); - abstractNumId = numbering.addAbstractNum(abstractNum); - BigInteger numId = numbering.addNum(abstractNumId); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - numbering = docIn.getNumbering(); - XWPFNum num = numbering.getNum(numId); - BigInteger compareAbstractNum = num.getCTNum().getAbstractNumId().getVal(); - assertEquals(abstractNumId, compareAbstractNum); - } - - @Test - void testAddAbstractNumIfAbstractNumEqualNull() throws IOException { - XWPFDocument docOut = new XWPFDocument(); - XWPFNumbering numbering = docOut.createNumbering(); - - XWPFAbstractNum abstractNum = new XWPFAbstractNum(); - BigInteger abstractNumId = numbering.addAbstractNum(abstractNum); - BigInteger numId = numbering.addNum(abstractNumId); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - numbering = docIn.getNumbering(); - XWPFNum num = numbering.getNum(numId); - - BigInteger compareAbstractNum = num.getCTNum().getAbstractNumId().getVal(); - assertEquals(abstractNumId, compareAbstractNum); - } - - @Test - void testGetNumIlvl() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx")) { - BigInteger numIlvl = BigInteger.valueOf(0); - assertEquals(numIlvl, doc.getParagraphs().get(0).getNumIlvl()); - numIlvl = BigInteger.valueOf(1); - assertEquals(numIlvl, doc.getParagraphs().get(5).getNumIlvl()); - } - } - - @Test - void testGetNumFmt() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx")) { - assertEquals("bullet", doc.getParagraphs().get(0).getNumFmt()); - assertEquals("bullet", doc.getParagraphs().get(1).getNumFmt()); - assertEquals("bullet", doc.getParagraphs().get(2).getNumFmt()); - assertEquals("bullet", doc.getParagraphs().get(3).getNumFmt()); - assertEquals("decimal", doc.getParagraphs().get(4).getNumFmt()); - assertEquals("lowerLetter", doc.getParagraphs().get(5).getNumFmt()); - assertEquals("lowerRoman", doc.getParagraphs().get(6).getNumFmt()); - } - } - - @Test - void testLvlText() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx")) { - - assertEquals("%1.%2.%3.", doc.getParagraphs().get(12).getNumLevelText()); - - assertEquals("NEW-%1-FORMAT", doc.getParagraphs().get(14).getNumLevelText()); - - XWPFParagraph p = doc.getParagraphs().get(18); - assertEquals("%1.", p.getNumLevelText()); - //test that null doesn't throw NPE - assertNull(p.getNumFmt()); - } - } - - @Test - void testOverrideList() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("NumberingWOverrides.docx")) { - XWPFParagraph p = doc.getParagraphs().get(4); - XWPFNumbering numbering = doc.getNumbering(); - CTNum ctNum = numbering.getNum(p.getNumID()).getCTNum(); - assertEquals(9, ctNum.sizeOfLvlOverrideArray()); - CTNumLvl ctNumLvl = ctNum.getLvlOverrideArray(0); - assertEquals("upperLetter", ctNumLvl.getLvl().getNumFmt().getVal().toString()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java deleted file mode 100644 index 73eb333e65..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java +++ /dev/null @@ -1,868 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.List; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; -import org.openxmlformats.schemas.drawingml.x2006.picture.PicDocument; -import org.openxmlformats.schemas.drawingml.x2006.picture.impl.PicDocumentImpl; -import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STOnOff1; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTInd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPBdr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTextAlignment; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTextAlignment; - -/** - * Tests for XWPF Paragraphs - */ -public final class TestXWPFParagraph { - - /** - * Check that we get the right paragraph from the header - */ - @Test - void testHeaderParagraph() throws IOException { - try (XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx")) { - - XWPFHeader hdr = xml.getHeaderFooterPolicy().getDefaultHeader(); - assertNotNull(hdr); - - List<XWPFParagraph> ps = hdr.getParagraphs(); - assertEquals(1, ps.size()); - XWPFParagraph p = ps.get(0); - - assertEquals(5, p.getCTP().sizeOfRArray()); - assertEquals("First header column!\tMid header\tRight header!", p.getText()); - } - } - - /** - * Check that we get the right paragraphs from the document - */ - @Test - void testDocumentParagraph() throws IOException { - try (XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx")) { - List<XWPFParagraph> ps = xml.getParagraphs(); - assertEquals(10, ps.size()); - - assertFalse(ps.get(0).isEmpty()); - assertEquals( - "This is a sample word document. It has two pages. It has a three column heading, but no footer.", - ps.get(0).getText()); - - assertTrue(ps.get(1).isEmpty()); - assertEquals("", ps.get(1).getText()); - - assertFalse(ps.get(2).isEmpty()); - assertEquals("HEADING TEXT", ps.get(2).getText()); - - assertTrue(ps.get(3).isEmpty()); - assertEquals("", ps.get(3).getText()); - - assertFalse(ps.get(4).isEmpty()); - assertEquals("More on page one", ps.get(4).getText()); - } - } - - @Test - void testSetGetBorderTop() throws IOException { - //new clean instance of paragraph - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - assertEquals(STBorder.NONE.intValue(), p.getBorderTop().getValue()); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - CTPBdr bdr = ppr.addNewPBdr(); - CTBorder borderTop = bdr.addNewTop(); - borderTop.setVal(STBorder.DOUBLE); - bdr.setTop(borderTop); - - assertEquals(Borders.DOUBLE, p.getBorderTop()); - p.setBorderTop(Borders.SINGLE); - assertEquals(STBorder.SINGLE, borderTop.getVal()); - } - } - - @Test - void testSetGetAlignment() throws IOException { - //new clean instance of paragraph - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - assertEquals(STJc.LEFT.intValue(), p.getAlignment().getValue()); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - CTJc align = ppr.addNewJc(); - align.setVal(STJc.CENTER); - assertEquals(ParagraphAlignment.CENTER, p.getAlignment()); - - p.setAlignment(ParagraphAlignment.BOTH); - assertEquals(STJc.BOTH, ppr.getJc().getVal()); - } - } - - @Test - void testSetGetSpacing() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - assertEquals(-1, p.getSpacingBefore()); - assertEquals(-1, p.getSpacingAfter()); - assertEquals(-1, p.getSpacingBetween(), 0.1); - assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule()); - - CTSpacing spacing = ppr.addNewSpacing(); - spacing.setAfter(new BigInteger("10")); - assertEquals(10, p.getSpacingAfter()); - spacing.setBefore(new BigInteger("10")); - assertEquals(10, p.getSpacingBefore()); - - p.setSpacingAfter(100); - assertEquals("100", spacing.xgetAfter().getStringValue()); - p.setSpacingBefore(100); - assertEquals("100", spacing.xgetBefore().getStringValue()); - - p.setSpacingBetween(.25, LineSpacingRule.EXACT); - assertEquals(.25, p.getSpacingBetween(), 0.01); - assertEquals(LineSpacingRule.EXACT, p.getSpacingLineRule()); - p.setSpacingBetween(1.25, LineSpacingRule.AUTO); - assertEquals(1.25, p.getSpacingBetween(), 0.01); - assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule()); - p.setSpacingBetween(.5, LineSpacingRule.AT_LEAST); - assertEquals(.5, p.getSpacingBetween(), 0.01); - assertEquals(LineSpacingRule.AT_LEAST, p.getSpacingLineRule()); - p.setSpacingBetween(1.15); - assertEquals(1.15, p.getSpacingBetween(), 0.01); - assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule()); - } - } - - @Test - void testSetGetSpacingLineRule() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - assertEquals(STLineSpacingRule.INT_AUTO, p.getSpacingLineRule().getValue()); - - CTSpacing spacing = ppr.addNewSpacing(); - spacing.setLineRule(STLineSpacingRule.AT_LEAST); - assertEquals(LineSpacingRule.AT_LEAST, p.getSpacingLineRule()); - - p.setSpacingAfter(100); - assertEquals("100", spacing.xgetAfter().getStringValue()); - } - } - - @Test - void testSetGetIndentationChars() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - assertEquals(-1, p.getIndentationLeftChars()); - assertEquals(-1, p.getIndentationRightChars()); - // set 1.5 characters - p.setIndentationLeftChars(150); - assertEquals(150, p.getIndentationLeftChars()); - - p.setIndentationRightChars(250); - assertEquals(250, p.getIndentationRightChars()); - } - } - - @Test - void testSetGetIndentation() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - assertEquals(-1, p.getIndentationLeft()); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - assertEquals(-1, p.getIndentationLeft()); - - CTInd ind = ppr.addNewInd(); - ind.setLeft(new BigInteger("10")); - assertEquals(10, p.getIndentationLeft()); - - p.setIndentationLeft(100); - assertEquals("100", ind.xgetLeft().getStringValue()); - } - } - @Test - void testSetGetVerticalAlignment() throws IOException { - //new clean instance of paragraph - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - CTTextAlignment txtAlign = ppr.addNewTextAlignment(); - txtAlign.setVal(STTextAlignment.CENTER); - assertEquals(TextAlignment.CENTER, p.getVerticalAlignment()); - - p.setVerticalAlignment(TextAlignment.BOTTOM); - assertEquals(STTextAlignment.BOTTOM, ppr.getTextAlignment().getVal()); - } - } - - @Test - void testSetGetWordWrap() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - CTOnOff wordWrap = ppr.addNewWordWrap(); - wordWrap.setVal(STOnOff1.OFF); - assertFalse(p.isWordWrap()); - - p.setWordWrapped(true); - assertEquals("on", ppr.getWordWrap().getVal()); - } - } - - @Test - void testSetGetPageBreak() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - CTOnOff pageBreak = ppr.addNewPageBreakBefore(); - pageBreak.setVal(STOnOff1.OFF); - assertFalse(p.isPageBreak()); - - p.setPageBreak(true); - assertEquals("on", ppr.getPageBreakBefore().getVal()); - } - } - - @Test - void testBookmarks() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("bookmarks.docx")) { - XWPFParagraph paragraph = doc.getParagraphs().get(0); - assertEquals("Sample Word Document", paragraph.getText()); - assertEquals(1, paragraph.getCTP().sizeOfBookmarkStartArray()); - assertEquals(0, paragraph.getCTP().sizeOfBookmarkEndArray()); - CTBookmark ctBookmark = paragraph.getCTP().getBookmarkStartArray(0); - assertEquals("poi", ctBookmark.getName()); - for (CTBookmark bookmark : paragraph.getCTP().getBookmarkStartList()) { - assertEquals("poi", bookmark.getName()); - } - } - } - - @Test - void testGetSetNumID() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - p.setNumID(new BigInteger("10")); - assertEquals("10", p.getNumID().toString()); - } - } - - @Test - void testGetSetILvl() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - p.setNumILvl(new BigInteger("1")); - assertEquals("1", p.getNumIlvl().toString()); - } - } - - @Test - void testAddingRuns() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) { - - XWPFParagraph p = doc.getParagraphs().get(0); - assertEquals(2, p.getRuns().size()); - - XWPFRun r = p.createRun(); - assertEquals(3, p.getRuns().size()); - assertEquals(2, p.getRuns().indexOf(r)); - - XWPFRun r2 = p.insertNewRun(1); - assertEquals(4, p.getRuns().size()); - assertEquals(1, p.getRuns().indexOf(r2)); - assertEquals(3, p.getRuns().indexOf(r)); - } - } - - @Test - void testCreateNewRuns() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - - XWPFParagraph p = doc.createParagraph(); - XWPFHyperlinkRun h = p.createHyperlinkRun("http://poi.apache.org"); - XWPFFieldRun fieldRun = p.createFieldRun(); - XWPFRun r = p.createRun(); - - assertEquals(3, p.getRuns().size()); - assertEquals(0, p.getRuns().indexOf(h)); - assertEquals(1, p.getRuns().indexOf(fieldRun)); - assertEquals(2, p.getRuns().indexOf(r)); - - assertEquals(3, p.getIRuns().size()); - assertEquals(0, p.getIRuns().indexOf(h)); - assertEquals(1, p.getIRuns().indexOf(fieldRun)); - assertEquals(2, p.getIRuns().indexOf(r)); - } - } - - @Test - void testInsertNewRuns() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - - XWPFParagraph p = doc.createParagraph(); - XWPFRun r = p.createRun(); - assertEquals(1, p.getRuns().size()); - assertEquals(0, p.getRuns().indexOf(r)); - - XWPFHyperlinkRun h = p.insertNewHyperlinkRun(0, "http://poi.apache.org"); - assertEquals(2, p.getRuns().size()); - assertEquals(0, p.getRuns().indexOf(h)); - assertEquals(1, p.getRuns().indexOf(r)); - - XWPFFieldRun fieldRun2 = p.insertNewFieldRun(2); - assertEquals(3, p.getRuns().size()); - assertEquals(2, p.getRuns().indexOf(fieldRun2)); - } - } - - @Test - void testRemoveRuns() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - - XWPFParagraph p = doc.createParagraph(); - XWPFRun r = p.createRun(); - p.createRun(); - XWPFHyperlinkRun hyperlinkRun = p - .createHyperlinkRun("http://poi.apache.org"); - XWPFFieldRun fieldRun = p.createFieldRun(); - - assertEquals(4, p.getRuns().size()); - assertEquals(2, p.getRuns().indexOf(hyperlinkRun)); - assertEquals(3, p.getRuns().indexOf(fieldRun)); - - p.removeRun(2); - assertEquals(3, p.getRuns().size()); - assertEquals(-1, p.getRuns().indexOf(hyperlinkRun)); - assertEquals(2, p.getRuns().indexOf(fieldRun)); - - p.removeRun(0); - assertEquals(2, p.getRuns().size()); - assertEquals(-1, p.getRuns().indexOf(r)); - assertEquals(1, p.getRuns().indexOf(fieldRun)); - - p.removeRun(1); - assertEquals(1, p.getRuns().size()); - assertEquals(-1, p.getRuns().indexOf(fieldRun)); - } - } - - @Test - void testRemoveAndInsertRunsWithOtherIRunElement() - throws IOException { - XWPFDocument doc = new XWPFDocument(); - - XWPFParagraph p = doc.createParagraph(); - p.createRun(); - // add other run element - p.getCTP().addNewSdt(); - // add two CTR in hyperlink - XWPFHyperlinkRun hyperlinkRun = p - .createHyperlinkRun("http://poi.apache.org"); - hyperlinkRun.getCTHyperlink().addNewR(); - p.createFieldRun(); - - XWPFDocument doc2 = XWPFTestDataSamples.writeOutAndReadBack(doc); - XWPFParagraph paragraph = doc2.getParagraphArray(0); - - assertEquals(4, paragraph.getRuns().size()); - assertEquals(5, paragraph.getIRuns().size()); - - assertTrue(paragraph.getRuns().get(1) instanceof XWPFHyperlinkRun); - assertTrue(paragraph.getRuns().get(2) instanceof XWPFHyperlinkRun); - assertTrue(paragraph.getRuns().get(3) instanceof XWPFFieldRun); - - assertTrue(paragraph.getIRuns().get(1) instanceof XWPFSDT); - assertTrue(paragraph.getIRuns().get(2) instanceof XWPFHyperlinkRun); - - paragraph.removeRun(1); - assertEquals(3, paragraph.getRuns().size()); - assertTrue(paragraph.getRuns().get(1) instanceof XWPFHyperlinkRun); - assertTrue(paragraph.getRuns().get(2) instanceof XWPFFieldRun); - - assertTrue(paragraph.getIRuns().get(1) instanceof XWPFSDT); - assertTrue(paragraph.getIRuns().get(2) instanceof XWPFHyperlinkRun); - - paragraph.removeRun(1); - assertEquals(2, paragraph.getRuns().size()); - assertTrue(paragraph.getRuns().get(1) instanceof XWPFFieldRun); - - assertTrue(paragraph.getIRuns().get(1) instanceof XWPFSDT); - assertTrue(paragraph.getIRuns().get(2) instanceof XWPFFieldRun); - - paragraph.removeRun(0); - assertEquals(1, paragraph.getRuns().size()); - assertTrue(paragraph.getRuns().get(0) instanceof XWPFFieldRun); - - assertTrue(paragraph.getIRuns().get(0) instanceof XWPFSDT); - assertTrue(paragraph.getIRuns().get(1) instanceof XWPFFieldRun); - - XWPFRun newRun = paragraph.insertNewRun(0); - assertEquals(2, paragraph.getRuns().size()); - - assertEquals(3, paragraph.getIRuns().size()); - assertEquals(0, paragraph.getRuns().indexOf(newRun)); - - doc.close(); - doc2.close(); - } - - @Test - void testPictures() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx")) { - assertEquals(7, doc.getParagraphs().size()); - - XWPFParagraph p; - XWPFRun r; - - // Text paragraphs - assertEquals("Sheet with various pictures", doc.getParagraphs().get(0).getText()); - assertEquals("(jpeg, png, wmf, emf and pict) ", doc.getParagraphs().get(1).getText()); - - // Spacer ones - assertEquals("", doc.getParagraphs().get(2).getText()); - assertEquals("", doc.getParagraphs().get(3).getText()); - assertEquals("", doc.getParagraphs().get(4).getText()); - - // Image one - p = doc.getParagraphs().get(5); - assertEquals(6, p.getRuns().size()); - - r = p.getRuns().get(0); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image1.wmf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(1); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image2.png", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(2); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image3.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(3); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image4.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(4); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image5.jpeg", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(5); - assertEquals(" ", r.toString()); - assertEquals(0, r.getEmbeddedPictures().size()); - - // Final spacer - assertEquals("", doc.getParagraphs().get(6).getText()); - - - // Look in detail at one - r = p.getRuns().get(4); - XWPFPicture pict = r.getEmbeddedPictures().get(0); - CTPicture picture = pict.getCTPicture(); - assertEquals("rId8", picture.getBlipFill().getBlip().getEmbed()); - - // Ensure that the ooxml compiler finds everything we need - r.getCTR().getDrawingArray(0); - r.getCTR().getDrawingArray(0).getInlineArray(0); - r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic(); - r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic().getGraphicData(); - PicDocument pd = new PicDocumentImpl(null); - assertTrue(pd.isNil()); - } - } - - @Test - void testTika792() throws Exception { - //This test forces the loading of CTMoveBookmark and - //CTMoveBookmarkImpl into ooxml-lite. - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Tika-792.docx")) { - XWPFParagraph paragraph = doc.getParagraphs().get(0); - assertEquals("", paragraph.getText()); - paragraph = doc.getParagraphs().get(1); - assertEquals("b", paragraph.getText()); - } - } - - @Test - void testSettersGetters() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - assertTrue(p.isEmpty()); - assertFalse(p.removeRun(0)); - - p.setBorderTop(Borders.BABY_PACIFIER); - p.setBorderBetween(Borders.BABY_PACIFIER); - p.setBorderBottom(Borders.BABY_RATTLE); - - assertNotNull(p.getIRuns()); - assertEquals(0, p.getIRuns().size()); - assertFalse(p.isEmpty()); - assertNull(p.getStyleID()); - assertNull(p.getStyle()); - - assertNull(p.getNumID()); - p.setNumID(BigInteger.valueOf(12)); - assertEquals(BigInteger.valueOf(12), p.getNumID()); - p.setNumID(BigInteger.valueOf(13)); - assertEquals(BigInteger.valueOf(13), p.getNumID()); - - assertNull(p.getNumFmt()); - - assertNull(p.getNumIlvl()); - - assertEquals("", p.getParagraphText()); - assertEquals("", p.getPictureText()); - assertEquals("", p.getFootnoteText()); - - p.setBorderBetween(Borders.NONE); - assertEquals(Borders.NONE, p.getBorderBetween()); - p.setBorderBetween(Borders.BASIC_BLACK_DASHES); - assertEquals(Borders.BASIC_BLACK_DASHES, p.getBorderBetween()); - - p.setBorderBottom(Borders.NONE); - assertEquals(Borders.NONE, p.getBorderBottom()); - p.setBorderBottom(Borders.BABY_RATTLE); - assertEquals(Borders.BABY_RATTLE, p.getBorderBottom()); - - p.setBorderLeft(Borders.NONE); - assertEquals(Borders.NONE, p.getBorderLeft()); - p.setBorderLeft(Borders.BASIC_WHITE_SQUARES); - assertEquals(Borders.BASIC_WHITE_SQUARES, p.getBorderLeft()); - - p.setBorderRight(Borders.NONE); - assertEquals(Borders.NONE, p.getBorderRight()); - p.setBorderRight(Borders.BASIC_WHITE_DASHES); - assertEquals(Borders.BASIC_WHITE_DASHES, p.getBorderRight()); - - p.setBorderBottom(Borders.NONE); - assertEquals(Borders.NONE, p.getBorderBottom()); - p.setBorderBottom(Borders.BASIC_WHITE_DOTS); - assertEquals(Borders.BASIC_WHITE_DOTS, p.getBorderBottom()); - - assertFalse(p.isPageBreak()); - p.setPageBreak(true); - assertTrue(p.isPageBreak()); - p.setPageBreak(false); - assertFalse(p.isPageBreak()); - - assertFalse(p.isKeepNext()); - p.setKeepNext(true); - assertTrue(p.isKeepNext()); - p.setKeepNext(false); - assertFalse(p.isKeepNext()); - - assertEquals(-1, p.getSpacingAfter()); - p.setSpacingAfter(12); - assertEquals(12, p.getSpacingAfter()); - - assertEquals(-1, p.getSpacingAfterLines()); - p.setSpacingAfterLines(14); - assertEquals(14, p.getSpacingAfterLines()); - - assertEquals(-1, p.getSpacingBefore()); - p.setSpacingBefore(16); - assertEquals(16, p.getSpacingBefore()); - - assertEquals(-1, p.getSpacingBeforeLines()); - p.setSpacingBeforeLines(18); - assertEquals(18, p.getSpacingBeforeLines()); - - assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule()); - p.setSpacingLineRule(LineSpacingRule.EXACT); - assertEquals(LineSpacingRule.EXACT, p.getSpacingLineRule()); - - assertEquals(-1, p.getIndentationLeft()); - p.setIndentationLeft(21); - assertEquals(21, p.getIndentationLeft()); - - assertEquals(-1, p.getIndentationRight()); - p.setIndentationRight(25); - assertEquals(25, p.getIndentationRight()); - - assertEquals(-1, p.getIndentationHanging()); - p.setIndentationHanging(25); - assertEquals(25, p.getIndentationHanging()); - - assertEquals(-1, p.getIndentationFirstLine()); - p.setIndentationFirstLine(25); - assertEquals(25, p.getIndentationFirstLine()); - - assertFalse(p.isWordWrap()); - p.setWordWrapped(true); - assertTrue(p.isWordWrap()); - p.setWordWrapped(false); - assertFalse(p.isWordWrap()); - - assertNull(p.getStyle()); - p.setStyle("testStyle"); - assertEquals("testStyle", p.getStyle()); - - p.addRun(CTR.Factory.newInstance()); - - //assertTrue(p.removeRun(0)); - - assertNotNull(p.getBody()); - assertEquals(BodyElementType.PARAGRAPH, p.getElementType()); - assertEquals(BodyType.DOCUMENT, p.getPartType()); - } - } - - @Test - void testSearchTextNotFound() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - assertNull(p.searchText("test", new PositionInParagraph())); - assertEquals("", p.getText()); - } - } - - @Test - void testSearchTextFound() throws IOException { - try (XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx")) { - - List<XWPFParagraph> ps = xml.getParagraphs(); - assertEquals(10, ps.size()); - - XWPFParagraph p = ps.get(0); - - TextSegment segment = p.searchText("sample word document", new PositionInParagraph()); - assertNotNull(segment); - - assertEquals("sample word document", p.getText(segment)); - - assertTrue(p.removeRun(0)); - } - } - - @Test - void testFieldRuns() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx")) { - List<XWPFParagraph> ps = doc.getParagraphs(); - assertEquals(1, ps.size()); - - XWPFParagraph p = ps.get(0); - assertEquals(1, p.getRuns().size()); - assertEquals(1, p.getIRuns().size()); - - XWPFRun r = p.getRuns().get(0); - assertEquals(XWPFFieldRun.class, r.getClass()); - - XWPFFieldRun fr = (XWPFFieldRun) r; - assertEquals(" FILENAME \\* MERGEFORMAT ", fr.getFieldInstruction()); - assertEquals("FldSimple.docx", fr.text()); - assertEquals("FldSimple.docx", p.getText()); - } - } - - @SuppressWarnings("deprecation") - @Test - void testRuns() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFParagraph p = doc.createParagraph(); - - CTR run = CTR.Factory.newInstance(); - XWPFRun r = new XWPFRun(run, doc.createParagraph()); - p.addRun(r); - p.addRun(r); - - assertNotNull(p.getRun(run)); - assertNull(p.getRun(null)); - } - } - - @Test - void test58067() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("58067.docx")) { - - StringBuilder str = new StringBuilder(); - for (XWPFParagraph par : doc.getParagraphs()) { - str.append(par.getText()).append("\n"); - } - assertEquals("This is a test.\n\n\n\n3\n4\n5\n\n\n\nThis is a whole paragraph where one word is deleted.\n", str.toString()); - } - } - - @Test - void test61787() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("61787.docx")) { - - StringBuilder str = new StringBuilder(); - for (XWPFParagraph par : doc.getParagraphs()) { - str.append(par.getText()).append("\n"); - } - String s = str.toString(); - assertTrue(s.trim().length() > 0, "Having text: \n" + s + "\nTrimmed length: " + s.trim().length()); - } - } - - /** - * Tests for numbered lists - * - * See also https://github.com/jimklo/apache-poi-sample/blob/master/src/main/java/com/sri/jklo/StyledDocument.java - * for someone else trying a similar thing - */ - @Test - void testNumberedLists() throws Exception { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ComplexNumberedLists.docx")) { - XWPFParagraph p; - - p = doc.getParagraphArray(0); - assertEquals("This is a document with numbered lists", p.getText()); - assertNull(p.getNumID()); - assertNull(p.getNumIlvl()); - assertNull(p.getNumStartOverride()); - - p = doc.getParagraphArray(1); - assertEquals("Entry #1", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertNull(p.getNumStartOverride()); - - p = doc.getParagraphArray(2); - assertEquals("Entry #2, with children", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertNull(p.getNumStartOverride()); - - p = doc.getParagraphArray(3); - assertEquals("2-a", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(1), p.getNumIlvl()); - assertNull(p.getNumStartOverride()); - - p = doc.getParagraphArray(4); - assertEquals("2-b", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(1), p.getNumIlvl()); - assertNull(p.getNumStartOverride()); - - p = doc.getParagraphArray(5); - assertEquals("2-c", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(1), p.getNumIlvl()); - assertNull(p.getNumStartOverride()); - - p = doc.getParagraphArray(6); - assertEquals("Entry #3", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertNull(p.getNumStartOverride()); - - p = doc.getParagraphArray(7); - assertEquals("Entry #4", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertNull(p.getNumStartOverride()); - - // New list - p = doc.getParagraphArray(8); - assertEquals("Restarted to 1 from 5", p.getText()); - assertEquals(BigInteger.valueOf(2), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertNull(p.getNumStartOverride()); - - p = doc.getParagraphArray(9); - assertEquals("Restarted @ 2", p.getText()); - assertEquals(BigInteger.valueOf(2), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertNull(p.getNumStartOverride()); - - p = doc.getParagraphArray(10); - assertEquals("Restarted @ 3", p.getText()); - assertEquals(BigInteger.valueOf(2), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertNull(p.getNumStartOverride()); - - // New list starting at 10 - p = doc.getParagraphArray(11); - assertEquals("Jump to new list at 10", p.getText()); - assertEquals(BigInteger.valueOf(6), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - // TODO Why isn't this seen as 10? - assertNull(p.getNumStartOverride()); - - // TODO Shouldn't we use XWPFNumbering or similar here? - // TODO Make it easier to change - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java deleted file mode 100644 index 7deb6f22a6..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java +++ /dev/null @@ -1,189 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -class TestXWPFPictureData { - - @Test - void testRead() throws InvalidFormatException, IOException { - try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx")) { - List<XWPFPictureData> pictures = sampleDoc.getAllPictures(); - - assertEquals(5, pictures.size()); - String[] ext = {"wmf", "png", "emf", "emf", "jpeg"}; - for (int i = 0; i < pictures.size(); i++) { - assertEquals(ext[i], pictures.get(i).suggestFileExtension()); - } - - int num = pictures.size(); - - byte[] pictureData = XWPFTestDataSamples.getImage("nature1.jpg"); - - String relationId = sampleDoc.addPictureData(pictureData, XWPFDocument.PICTURE_TYPE_JPEG); - // picture list was updated - assertEquals(num + 1, pictures.size()); - XWPFPictureData pict = (XWPFPictureData) sampleDoc.getRelationById(relationId); - assertNotNull(pict); - assertEquals("jpeg", pict.suggestFileExtension()); - assertArrayEquals(pictureData, pict.getData()); - } - } - - @Test - void testPictureInHeader() throws IOException { - try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx")) { - verifyOneHeaderPicture(sampleDoc); - - XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc); - verifyOneHeaderPicture(readBack); - } - } - - @Test - void testCreateHeaderPicture() throws Exception { - try (XWPFDocument doc = new XWPFDocument()) { - - // Starts with no header - XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy(); - assertNull(policy); - - // Add a default header - policy = doc.createHeaderFooterPolicy(); - XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT); - header.createParagraph().createRun().setText("Hello, Header World!"); - header.createParagraph().createRun().setText("Paragraph 2"); - assertEquals(0, header.getAllPictures().size()); - assertEquals(2, header.getParagraphs().size()); - - // Add a picture to the first paragraph - header.getParagraphs().get(0).getRuns().get(0).addPicture( - new ByteArrayInputStream(new byte[]{1, 2, 3, 4}), - Document.PICTURE_TYPE_JPEG, "test.jpg", 2, 2); - - // Check - verifyOneHeaderPicture(doc); - - // Save, re-load, re-check - XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(doc); - verifyOneHeaderPicture(readBack); - } - } - - private void verifyOneHeaderPicture(XWPFDocument sampleDoc) { - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - - XWPFHeader header = policy.getDefaultHeader(); - - List<XWPFPictureData> pictures = header.getAllPictures(); - assertEquals(1, pictures.size()); - } - - @Test - void testNew() throws InvalidFormatException, IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx")) { - byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg"); - assertNotNull(jpegData); - byte[] gifData = XWPFTestDataSamples.getImage("nature1.gif"); - assertNotNull(gifData); - byte[] pngData = XWPFTestDataSamples.getImage("nature1.png"); - assertNotNull(pngData); - - List<XWPFPictureData> pictures = doc.getAllPictures(); - assertEquals(0, pictures.size()); - - // Document shouldn't have any image relationships - assertEquals(13, doc.getPackagePart().getRelationships().size()); - for (PackageRelationship rel : doc.getPackagePart().getRelationships()) { - assertNotEquals(XSSFRelation.IMAGE_JPEG.getRelation(), rel.getRelationshipType(), "Shouldn't have JPEG yet"); - } - - // Add the image - String relationId = doc.addPictureData(jpegData, XWPFDocument.PICTURE_TYPE_JPEG); - assertEquals(1, pictures.size()); - XWPFPictureData jpgPicData = (XWPFPictureData) doc.getRelationById(relationId); - assertNotNull(jpgPicData); - assertEquals("jpeg", jpgPicData.suggestFileExtension()); - assertArrayEquals(jpegData, jpgPicData.getData()); - - // Ensure it now has one - assertEquals(14, doc.getPackagePart().getRelationships().size()); - PackageRelationship jpegRel = null; - for (PackageRelationship rel : doc.getPackagePart().getRelationships()) { - if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation())) { - assertNull(jpegRel, "Found 2 jpegs!"); - jpegRel = rel; - } - } - assertNotNull(jpegRel, "JPEG Relationship not found"); - - // Check the details - assertNotNull(jpegRel); - assertEquals(XWPFRelation.IMAGE_JPEG.getRelation(), jpegRel.getRelationshipType()); - assertEquals("/word/document.xml", jpegRel.getSource().getPartName().toString()); - assertEquals("/word/media/image1.jpeg", jpegRel.getTargetURI().getPath()); - - XWPFPictureData pictureDataByID = doc.getPictureDataByID(jpegRel.getId()); - assertArrayEquals(jpegData, pictureDataByID.getData()); - - // Save an re-load, check it appears - try (XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc)) { - assertEquals(1, docBack.getAllPictures().size()); - assertEquals(1, docBack.getAllPackagePictures().size()); - - // verify the picture that we read back in - pictureDataByID = docBack.getPictureDataByID(jpegRel.getId()); - assertArrayEquals(jpegData, pictureDataByID.getData()); - } - } - } - - @Test - void testBug51770() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug51170.docx")) { - XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy(); - XWPFHeader header = policy.getDefaultHeader(); - - header.getParagraphs().stream() - .map(XWPFParagraph::getRuns) - .flatMap(List::stream) - .map(XWPFRun::getEmbeddedPictures) - .flatMap(List::stream) - .map(XWPFPicture::getPictureData) - .forEach(Assertions::assertNull); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java deleted file mode 100644 index 1de994a804..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java +++ /dev/null @@ -1,851 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.util.List; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.Units; -import org.apache.poi.wp.usermodel.HeaderFooterType; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; -import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STOnOff1; -import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STVerticalAlignRun; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrClear; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STEm; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHighlightColor; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STThemeColor; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STUnderline; - -/** - * Tests for XWPF Run - */ -class TestXWPFRun { - private CTR ctRun; - private XWPFParagraph p; - private IRunBody irb; - private XWPFDocument doc; - - @BeforeEach - void setUp() { - doc = new XWPFDocument(); - p = doc.createParagraph(); - irb = p; - - this.ctRun = CTR.Factory.newInstance(); - } - - @AfterEach - void tearDown() throws Exception { - doc.close(); - } - - @Test - void testSetGetText() { - ctRun.addNewT().setStringValue("TEST STRING"); - ctRun.addNewT().setStringValue("TEST2 STRING"); - ctRun.addNewT().setStringValue("TEST3 STRING"); - - assertEquals(3, ctRun.sizeOfTArray()); - XWPFRun run = new XWPFRun(ctRun, irb); - - assertEquals("TEST2 STRING", run.getText(1)); - - run.setText("NEW STRING", 0); - assertEquals("NEW STRING", run.getText(0)); - - //run.setText("xxx",14); - //fail("Position wrong"); - } - - /* - * bug 59208 - * Purpose: test all valid boolean-like values - * exercise isCTOnOff(CTOnOff) through all valid permutations - */ - @Test - void testCTOnOff() { - CTRPr rpr = ctRun.addNewRPr(); - CTOnOff bold = rpr.addNewB(); - XWPFRun run = new XWPFRun(ctRun, irb); - - // True values: "true", "1", "on" - bold.setVal(STOnOff1.ON); - assertTrue(run.isBold()); - - bold.setVal(STOnOff1.ON); - assertTrue(run.isBold()); - - bold.setVal(STOnOff1.ON); - assertTrue(run.isBold()); - - // False values: "false", "0", "off" - bold.setVal(STOnOff1.OFF); - assertFalse(run.isBold()); - - bold.setVal(STOnOff1.OFF); - assertFalse(run.isBold()); - - bold.setVal(STOnOff1.OFF); - assertFalse(run.isBold()); - } - - @Test - void testSetGetBold() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewB().setVal(STOnOff1.ON); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertTrue(run.isBold()); - - run.setBold(false); - // Implementation detail: POI natively prefers <w:b w:val="false"/>, - // but should correctly read val="0" and val="off" - assertEquals("off", rpr.getBArray(0).getVal()); - } - - @Test - void testSetGetItalic() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewI().setVal(STOnOff1.ON); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertTrue(run.isItalic()); - - run.setItalic(false); - assertEquals("off", rpr.getIArray(0).getVal()); - } - - @Test - void testSetGetStrike() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewStrike().setVal(STOnOff1.ON); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertTrue(run.isStrikeThrough()); - - run.setStrikeThrough(false); - assertEquals("off", rpr.getStrikeArray(0).getVal()); - } - - @Test - void testSetGetUnderline() { - CTRPr rpr = ctRun.addNewRPr(); - XWPFRun run = new XWPFRun(ctRun, irb); - rpr.addNewU().setVal(STUnderline.DASH); - - assertEquals(UnderlinePatterns.DASH.getValue(), run.getUnderline() - .getValue()); - - run.setUnderline(UnderlinePatterns.NONE); - assertEquals(STUnderline.NONE.intValue(), rpr.getUArray(0).getVal() - .intValue()); - } - - @Test - void testSetGetFontFamily() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewRFonts().setAscii("Times New Roman"); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals("Times New Roman", run.getFontFamily()); - - run.setFontFamily("Verdana"); - assertEquals("Verdana", rpr.getRFontsArray(0).getAscii()); - } - - @Test - void testSetGetFontSize() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewSz().setVal(BigInteger.valueOf(14)); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(7, run.getFontSize()); - assertEquals(7.0, run.getFontSizeAsDouble(), 0.01); - - run.setFontSize(24); - assertEquals("48", rpr.getSzArray(0).getVal().toString()); - - run.setFontSize(24.5f); - assertEquals("49", rpr.getSzArray(0).getVal().toString()); - assertEquals(25, run.getFontSize()); - assertEquals(24.5, run.getFontSizeAsDouble(), 0.01); - } - - @Test - void testSetGetTextForegroundBackground() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewPosition().setVal(new BigInteger("4000")); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(4000, run.getTextPosition()); - - run.setTextPosition(2400); - assertEquals("2400", rpr.getPositionArray(0).getVal().toString()); - } - - @Test - void testSetGetColor() { - XWPFRun run = new XWPFRun(ctRun, irb); - run.setColor("0F0F0F"); - String clr = run.getColor(); - assertEquals("0F0F0F", clr); - } - - @Test - void testAddCarriageReturn() { - ctRun.addNewT().setStringValue("TEST STRING"); - ctRun.addNewCr(); - ctRun.addNewT().setStringValue("TEST2 STRING"); - ctRun.addNewCr(); - ctRun.addNewT().setStringValue("TEST3 STRING"); - assertEquals(2, ctRun.sizeOfCrArray()); - - XWPFRun run = new XWPFRun(CTR.Factory.newInstance(), irb); - run.setText("T1"); - run.addCarriageReturn(); - run.addCarriageReturn(); - run.setText("T2"); - run.addCarriageReturn(); - assertEquals(3, run.getCTR().sizeOfCrArray()); - - assertEquals("T1\n\nT2\n", run.toString()); - } - - @Test - void testAddTabsAndLineBreaks() { - ctRun.addNewT().setStringValue("TEST STRING"); - ctRun.addNewCr(); - ctRun.addNewT().setStringValue("TEST2 STRING"); - ctRun.addNewTab(); - ctRun.addNewT().setStringValue("TEST3 STRING"); - assertEquals(1, ctRun.sizeOfCrArray()); - assertEquals(1, ctRun.sizeOfTabArray()); - - XWPFRun run = new XWPFRun(CTR.Factory.newInstance(), irb); - run.setText("T1"); - run.addCarriageReturn(); - run.setText("T2"); - run.addTab(); - run.setText("T3"); - assertEquals(1, run.getCTR().sizeOfCrArray()); - assertEquals(1, run.getCTR().sizeOfTabArray()); - - assertEquals("T1\nT2\tT3", run.toString()); - } - - @Test - void testAddPageBreak() { - ctRun.addNewT().setStringValue("TEST STRING"); - ctRun.addNewBr(); - ctRun.addNewT().setStringValue("TEST2 STRING"); - CTBr breac = ctRun.addNewBr(); - breac.setClear(STBrClear.LEFT); - ctRun.addNewT().setStringValue("TEST3 STRING"); - assertEquals(2, ctRun.sizeOfBrArray()); - - XWPFRun run = new XWPFRun(CTR.Factory.newInstance(), irb); - run.setText("TEXT1"); - run.addBreak(); - run.setText("TEXT2"); - run.addBreak(BreakType.TEXT_WRAPPING); - assertEquals(2, run.getCTR().sizeOfBrArray()); - } - - /** - * Test that on an existing document, we do the - * right thing with it - */ - @Test - void testExisting() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFParagraph p; - XWPFRun run; - - - // First paragraph is simple - p = doc.getParagraphArray(0); - assertEquals("This is a test document.", p.getText()); - assertEquals(2, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("This is a test document", run.toString()); - assertFalse(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - assertNull(run.getCTR().getRPr()); - - run = p.getRuns().get(1); - assertEquals(".", run.toString()); - assertFalse(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - assertNull(run.getCTR().getRPr()); - - - // Next paragraph is all in one style, but a different one - p = doc.getParagraphArray(1); - assertEquals("This bit is in bold and italic", p.getText()); - assertEquals(1, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("This bit is in bold and italic", run.toString()); - assertTrue(run.isBold()); - assertTrue(run.isItalic()); - assertFalse(run.isStrikeThrough()); - assertTrue(run.getCTR().getRPr().sizeOfBArray() > 0); - assertFalse(run.getCTR().getRPr().getBArray(0).isSetVal()); - - - // Back to normal - p = doc.getParagraphArray(2); - assertEquals("Back to normal", p.getText()); - assertEquals(1, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("Back to normal", run.toString()); - assertFalse(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - assertNull(run.getCTR().getRPr()); - - - // Different styles in one paragraph - p = doc.getParagraphArray(3); - assertEquals("This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.", p.getText()); - assertEquals(11, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("This contains ", run.toString()); - assertFalse(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - assertNull(run.getCTR().getRPr()); - - run = p.getRuns().get(1); - assertEquals("BOLD", run.toString()); - assertTrue(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - - run = p.getRuns().get(2); - assertEquals(", ", run.toString()); - assertFalse(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - assertNull(run.getCTR().getRPr()); - - run = p.getRuns().get(3); - assertEquals("ITALIC", run.toString()); - assertFalse(run.isBold()); - assertTrue(run.isItalic()); - assertFalse(run.isStrikeThrough()); - - run = p.getRuns().get(4); - assertEquals(" and ", run.toString()); - assertFalse(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - assertNull(run.getCTR().getRPr()); - - run = p.getRuns().get(5); - assertEquals("BOTH", run.toString()); - assertTrue(run.isBold()); - assertTrue(run.isItalic()); - assertFalse(run.isStrikeThrough()); - - run = p.getRuns().get(6); - assertEquals(", as well as ", run.toString()); - assertFalse(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - assertNull(run.getCTR().getRPr()); - - run = p.getRuns().get(7); - assertEquals("RED", run.toString()); - assertFalse(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - - run = p.getRuns().get(8); - assertEquals(" and ", run.toString()); - assertFalse(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - assertNull(run.getCTR().getRPr()); - - run = p.getRuns().get(9); - assertEquals("YELLOW", run.toString()); - assertFalse(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - - run = p.getRuns().get(10); - assertEquals(" text.", run.toString()); - assertFalse(run.isBold()); - assertFalse(run.isItalic()); - assertFalse(run.isStrikeThrough()); - assertNull(run.getCTR().getRPr()); - - doc.close(); - } - - @Test - void testPictureInHeader() throws IOException { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx"); - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - - XWPFHeader header = policy.getDefaultHeader(); - - int count = 0; - - for (XWPFParagraph p : header.getParagraphs()) { - for (XWPFRun r : p.getRuns()) { - List<XWPFPicture> pictures = r.getEmbeddedPictures(); - - for (XWPFPicture pic : pictures) { - assertNotNull(pic.getPictureData()); - assertEquals("DOZOR", pic.getDescription()); - } - - count += pictures.size(); - } - } - - assertEquals(1, count); - sampleDoc.close(); - } - - @Test - void testSetGetLang() { - XWPFRun run = p.createRun(); - assertNull(run.getLang()); - - run.setLang("en-CA"); - assertEquals("en-CA", run.getLang()); - - run.setLang("fr-CA"); - assertEquals("fr-CA", run.getLang()); - - run.setLang(null); - assertNull(run.getLang()); - } - - @Test - void testSetGetLang2() { - XWPFRun run = p.createRun(); - assertNull(run.getLang()); - - run.getCTR().addNewRPr().addNewLang().setVal("en-CA"); - assertEquals("en-CA", run.getLang()); - - run.getCTR().getRPr().getLangArray(0).setVal("fr-CA"); - assertEquals("fr-CA", run.getLang()); - - run.getCTR().getRPr().getLangArray(0).setVal(null); - assertNull(run.getLang()); - } - - @Test - void testAddPicture() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFParagraph p = doc.getParagraphArray(2); - XWPFRun r = p.getRuns().get(0); - - assertEquals(0, doc.getAllPictures().size()); - assertEquals(0, r.getEmbeddedPictures().size()); - - r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); - - assertEquals(1, doc.getAllPictures().size()); - assertEquals(1, r.getEmbeddedPictures().size()); - - XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc); - XWPFParagraph pBack = docBack.getParagraphArray(2); - XWPFRun rBack = pBack.getRuns().get(0); - - assertEquals(1, docBack.getAllPictures().size()); - assertEquals(1, rBack.getEmbeddedPictures().size()); - docBack.close(); - doc.close(); - } - - /** - * Bugzilla #58237 - Unable to add image to word document header - */ - @Test - void testAddPictureInHeader() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT); - XWPFParagraph p = hdr.createParagraph(); - XWPFRun r = p.createRun(); - - assertEquals(0, hdr.getAllPictures().size()); - assertEquals(0, r.getEmbeddedPictures().size()); - - r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); - - assertEquals(1, hdr.getAllPictures().size()); - assertEquals(1, r.getEmbeddedPictures().size()); - - XWPFPicture pic = r.getEmbeddedPictures().get(0); - CTPicture ctPic = pic.getCTPicture(); - CTBlipFillProperties ctBlipFill = ctPic.getBlipFill(); - - assertNotNull(ctBlipFill); - - CTBlip ctBlip = ctBlipFill.getBlip(); - - assertNotNull(ctBlip); - assertEquals("rId1", ctBlip.getEmbed()); - - XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc); - XWPFHeader hdrBack = docBack.getHeaderArray(0); - XWPFParagraph pBack = hdrBack.getParagraphArray(0); - XWPFRun rBack = pBack.getRuns().get(0); - - assertEquals(1, hdrBack.getAllPictures().size()); - assertEquals(1, rBack.getEmbeddedPictures().size()); - docBack.close(); - doc.close(); - } - - /** - * Bugzilla #52288 - setting the font family on the - * run mustn't NPE - */ - @Test - void testSetFontFamily_52288() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52288.docx")) { - doc.getParagraphs().stream() - .flatMap(p -> p.getRuns().stream()) - .filter(p -> p != null && p.getText(0) != null) - .forEach(r -> assertDoesNotThrow(() -> r.setFontFamily("Times New Roman"))); - } - } - - @Test - void testBug55476() throws IOException, InvalidFormatException { - byte[] image = XWPFTestDataSamples.getImage("abstract1.jpg"); - XWPFDocument document = new XWPFDocument(); - - document.createParagraph().createRun().addPicture( - new ByteArrayInputStream(image), Document.PICTURE_TYPE_JPEG, "test.jpg", Units.toEMU(300), Units.toEMU(100)); - - XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(document); - List<XWPFPicture> pictures = docBack.getParagraphArray(0).getRuns().get(0).getEmbeddedPictures(); - assertEquals(1, pictures.size()); - docBack.close(); - - /*OutputStream stream = new FileOutputStream("c:\\temp\\55476.docx"); - try { - document.write(stream); - } finally { - stream.close(); - }*/ - - document.close(); - } - - @Test - void testBug58922() throws IOException { - XWPFDocument document = new XWPFDocument(); - - final XWPFRun run = document.createParagraph().createRun(); - - - assertEquals(-1, run.getFontSize()); - - run.setFontSize(10); - assertEquals(10, run.getFontSize()); - - run.setFontSize(Short.MAX_VALUE-1); - assertEquals(Short.MAX_VALUE-1, run.getFontSize()); - - run.setFontSize(Short.MAX_VALUE); - assertEquals(Short.MAX_VALUE, run.getFontSize()); - - run.setFontSize(Short.MAX_VALUE+1); - assertEquals(Short.MAX_VALUE+1, run.getFontSize()); - - run.setFontSize(Integer.MAX_VALUE-1); - assertEquals(Integer.MAX_VALUE-1, run.getFontSize()); - - run.setFontSize(Integer.MAX_VALUE); - assertEquals(Integer.MAX_VALUE, run.getFontSize()); - - run.setFontSize(-1); - assertEquals(-1, run.getFontSize()); - - - assertEquals(-1, run.getTextPosition()); - - run.setTextPosition(10); - assertEquals(10, run.getTextPosition()); - - run.setTextPosition(Short.MAX_VALUE-1); - assertEquals(Short.MAX_VALUE-1, run.getTextPosition()); - - run.setTextPosition(Short.MAX_VALUE); - assertEquals(Short.MAX_VALUE, run.getTextPosition()); - - run.setTextPosition(Short.MAX_VALUE+1); - assertEquals(Short.MAX_VALUE+1, run.getTextPosition()); - - run.setTextPosition(Short.MAX_VALUE+1); - assertEquals(Short.MAX_VALUE+1, run.getTextPosition()); - - run.setTextPosition(Integer.MAX_VALUE-1); - assertEquals(Integer.MAX_VALUE-1, run.getTextPosition()); - - run.setTextPosition(Integer.MAX_VALUE); - assertEquals(Integer.MAX_VALUE, run.getTextPosition()); - - run.setTextPosition(-1); - assertEquals(-1, run.getTextPosition()); - - document.close(); - } - - @Test - void testSetters() { - XWPFDocument document = new XWPFDocument(); - final XWPFRun run = document.createParagraph().createRun(); - - // at least trigger some of the setters to ensure classes are included in - // the poi-ooxml-lite - run.setBold(true); - run.setCapitalized(true); - run.setCharacterSpacing(2); - assertEquals(2, run.getCharacterSpacing()); - run.setColor("000000"); - run.setDoubleStrikethrough(true); - run.setEmbossed(true); - run.setFontFamily("Calibri"); - assertEquals("Calibri", run.getFontFamily()); - run.setFontSize(10); - assertEquals(10, run.getFontSize()); - run.setImprinted(true); - run.setItalic(true); - } - - @Test - void testSetGetTextScale() throws IOException { - XWPFDocument document = new XWPFDocument(); - final XWPFRun run = document.createParagraph().createRun(); - assertEquals(100, run.getTextScale()); - run.setTextScale(200); - assertEquals(200, run.getTextScale()); - document.close(); - } - - @Test - void testSetGetTextHighlightColor() throws IOException { - XWPFDocument document = new XWPFDocument(); - final XWPFRun run = document.createParagraph().createRun(); - assertEquals(STHighlightColor.NONE, run.getTextHightlightColor()); - assertFalse(run.isHighlighted()); - run.setTextHighlightColor("darkGreen"); // See 17.18.40 ST_HighlightColor (Text Highlight Colors) - assertEquals(STHighlightColor.DARK_GREEN, run.getTextHightlightColor()); - assertTrue(run.isHighlighted()); - run.setTextHighlightColor("none"); - assertFalse(run.isHighlighted()); - - document.close(); - } - - @Test - void testSetGetVanish() throws IOException { - XWPFDocument document = new XWPFDocument(); - final XWPFRun run = document.createParagraph().createRun(); - assertFalse(run.isVanish()); - run.setVanish(true); - assertTrue(run.isVanish()); - run.setVanish(false); - assertFalse(run.isVanish()); - document.close(); - } - - @Test - void testSetGetVerticalAlignment() throws IOException { - XWPFDocument document = new XWPFDocument(); - XWPFRun run = document.createParagraph().createRun(); - assertEquals(STVerticalAlignRun.BASELINE, run.getVerticalAlignment()); - // Reset to a fresh run so we test case of run not having vertical alignment at all - run = document.createParagraph().createRun(); - run.setVerticalAlignment("subscript"); - assertEquals(STVerticalAlignRun.SUBSCRIPT, run.getVerticalAlignment()); - run.setVerticalAlignment("superscript"); - assertEquals(STVerticalAlignRun.SUPERSCRIPT, run.getVerticalAlignment()); - document.close(); - } - - @Test - void testSetGetVAlign() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewVertAlign().setVal(STVerticalAlignRun.SUBSCRIPT); - - XWPFRun run = new XWPFRun(ctRun, irb); - - run.setSubscript(VerticalAlign.BASELINE); - assertEquals(STVerticalAlignRun.BASELINE, rpr.getVertAlignArray(0).getVal()); - } - - @Test - void testSetGetEmphasisMark() throws IOException { - XWPFDocument document = new XWPFDocument(); - XWPFRun run = document.createParagraph().createRun(); - assertEquals(STEm.NONE, run.getEmphasisMark()); - // Reset to a fresh run so we test case of run not having property at all - run = document.createParagraph().createRun(); - run.setEmphasisMark("dot"); - assertEquals(STEm.DOT, run.getEmphasisMark()); - document.close(); - } - - @Test - void testSetGetUnderlineColor() throws IOException { - XWPFDocument document = new XWPFDocument(); - XWPFRun run = document.createParagraph().createRun(); - assertEquals("auto", run.getUnderlineColor()); - // Reset to a fresh run so we test case of run not having property at all - run = document.createParagraph().createRun(); - String colorRgb = "C0F1a2"; - run.setUnderlineColor(colorRgb); - assertEquals(colorRgb.toUpperCase(LocaleUtil.getUserLocale()), run.getUnderlineColor()); - run.setUnderlineColor("auto"); - assertEquals("auto", run.getUnderlineColor()); - document.close(); - } - - @Test - void testSetGetUnderlineThemeColor() throws IOException { - XWPFDocument document = new XWPFDocument(); - XWPFRun run = document.createParagraph().createRun(); - assertEquals(STThemeColor.NONE, run.getUnderlineThemeColor()); - // Reset to a fresh run so we test case of run not having property at all - run = document.createParagraph().createRun(); - String colorName = "accent4"; - run.setUnderlineThemeColor(colorName); - assertEquals(STThemeColor.Enum.forString(colorName), run.getUnderlineThemeColor()); - run.setUnderlineThemeColor("none"); - assertEquals(STThemeColor.NONE, run.getUnderlineThemeColor()); - document.close(); - } - - - @Test - void testSetStyleId() throws IOException { - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - final XWPFRun run = document.createParagraph().createRun(); - - String styleId = "bolditalic"; - run.setStyle(styleId); - String candStyleId = run.getCTR().getRPr().getRStyleArray(0).getVal(); - assertNotNull( candStyleId, "Expected to find a run style ID" ); - assertEquals(styleId, candStyleId); - - assertEquals(styleId, run.getStyle()); - - document.close(); - } - - @Test - void testGetDepthWidth() throws IOException, InvalidFormatException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx")) { - XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT); - XWPFParagraph p = hdr.createParagraph(); - XWPFRun r = p.createRun(); - - assertEquals(0, hdr.getAllPictures().size()); - assertEquals(0, r.getEmbeddedPictures().size()); - - r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); - - assertEquals(1, hdr.getAllPictures().size()); - assertEquals(1, r.getEmbeddedPictures().size()); - - XWPFPicture pic = r.getEmbeddedPictures().get(0); - - assertEquals(pic.getWidth(), Units.toPoints(21), 0.0); - assertEquals(pic.getDepth(), Units.toPoints(32), 0.0); - } - } - - @Test - void testWhitespace() throws IOException { - String[] text = new String[] { - " The quick brown fox", - "\t\tjumped over the lazy dog" - }; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (XWPFDocument doc = new XWPFDocument();) { - for(String s : text) { - XWPFParagraph p1 = doc.createParagraph(); - XWPFRun r1 = p1.createRun(); - r1.setText(s); - } - - doc.write(bos); - bos.flush(); - } - - try ( - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - XWPFDocument doc = new XWPFDocument(bis) - ) { - List<XWPFParagraph> paragraphs = doc.getParagraphs(); - assertEquals(2, paragraphs.size()); - for (int i = 0; i < text.length; i++) { - XWPFParagraph p1 = paragraphs.get(i); - String expected = text[i]; - assertEquals(expected, p1.getText()); - CTP ctp = p1.getCTP(); - CTR ctr = ctp.getRArray(0); - CTText ctText = ctr.getTArray(0); - // if text has leading whitespace then expect xml-fragment to have xml:space="preserve" set - // <xml-fragment xml:space="preserve" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> - boolean isWhitespace = Character.isWhitespace(expected.charAt(0)); - assertEquals(isWhitespace, ctText.isSetSpace()); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java deleted file mode 100644 index 235c17d3ab..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java +++ /dev/null @@ -1,239 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; - -public final class TestXWPFSDT { - - /** - * Test text extraction from nested SDTs - */ - @Test - void testNestedSDTs() throws Exception { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug64561.docx")) { - XWPFAbstractSDT sdt = extractAllSDTs(doc).get(0); - assertEquals("Subject", sdt.getContent().getText(), "extracted text"); - } - } - - /** - * Test simple tag and title extraction from SDT - */ - @Test - void testTagTitle() throws Exception { - try (XWPFDocument doc =XWPFTestDataSamples.openSampleDocument("Bug54849.docx")) { - String tag = null; - String title = null; - List<XWPFAbstractSDT> sdts = extractAllSDTs(doc); - for (XWPFAbstractSDT sdt : sdts) { - if (sdt.getContent().toString().equals("Rich_text")) { - tag = "MyTag"; - title = "MyTitle"; - break; - } - - } - assertEquals(13, sdts.size(), "controls size"); - - assertEquals("MyTag", tag, "tag"); - assertEquals("MyTitle", title, "title"); - } - } - - @Test - void testGetSDTs() throws Exception { - String[] contents = new String[]{ - "header_rich_text", - "Rich_text", - "Rich_text_pre_table\nRich_text_cell1\t\t\t\n\t\t\t\n\t\t\t\n\nRich_text_post_table", - "Plain_text_no_newlines", - "Plain_text_with_newlines1\nplain_text_with_newlines2", - "Watermelon", - "Dirt", - "4/16/2013", - "Rich_text_in_cell", - "rich_text_in_paragraph_in_cell", - "Footer_rich_text", - "Footnote_sdt", - "Endnote_sdt" - - }; - try (XWPFDocument doc =XWPFTestDataSamples.openSampleDocument("Bug54849.docx")) { - List<XWPFAbstractSDT> sdts = extractAllSDTs(doc); - - assertEquals(contents.length, sdts.size(), "number of sdts"); - - for (int i = 0; i < contents.length; i++) { - XWPFAbstractSDT sdt = sdts.get(i); - assertEquals(contents[i], sdt.getContent().toString(), i + ": " + contents[i]); - } - } - } - - /** - * POI-54771 and TIKA-1317 - */ - @Test - void testSDTAsCell() throws Exception { - //Bug54771a.docx and Bug54771b.docx test slightly - //different recursion patterns. Keep both! - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx")) { - List<XWPFAbstractSDT> sdts = extractAllSDTs(doc); - String text = sdts.get(0).getContent().getText(); - assertEquals(2, sdts.size()); - assertContains(text, "Test"); - - text = sdts.get(1).getContent().getText(); - assertContains(text, "Test Subtitle"); - assertContains(text, "Test User"); - assertTrue(text.indexOf("Test") < text.indexOf("Test Subtitle")); - } - - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54771b.docx")) { - List<XWPFAbstractSDT> sdts = extractAllSDTs(doc); - assertEquals(3, sdts.size()); - assertContains(sdts.get(0).getContent().getText(), "Test"); - - assertContains(sdts.get(1).getContent().getText(), "Test Subtitle"); - assertContains(sdts.get(2).getContent().getText(), "Test User"); - } - } - - /** - * POI-55142 and Tika 1130 - */ - @Test - void testNewLinesBetweenRuns() throws Exception { - try (XWPFDocument doc =XWPFTestDataSamples.openSampleDocument("Bug55142.docx")) { - List<XWPFAbstractSDT> sdts = extractAllSDTs(doc); - List<String> targs = new ArrayList<>(); - //these test newlines and tabs in paragraphs/body elements - targs.add("Rich-text1 abcdefghi"); - targs.add("Rich-text2 abcd\t\tefgh"); - targs.add("Rich-text3 abcd\nefg"); - targs.add("Rich-text4 abcdefg"); - targs.add("Rich-text5 abcdefg\nhijk"); - targs.add("Plain-text1 abcdefg"); - targs.add("Plain-text2 abcdefg\nhijk\nlmnop"); - //this tests consecutive runs within a cell (not a paragraph) - //this test case was triggered by Tika-1130 - targs.add("sdt_incell2 abcdefg"); - - for (int i = 0; i < sdts.size(); i++) { - XWPFAbstractSDT sdt = sdts.get(i); - assertEquals(targs.get(i), sdt.getContent().getText()); - } - } - } - - @Test - void test60341() throws IOException { - //handle sdtbody without an sdtpr - try (XWPFDocument doc =XWPFTestDataSamples.openSampleDocument("Bug60341.docx")) { - List<XWPFAbstractSDT> sdts = extractAllSDTs(doc); - assertEquals(1, sdts.size()); - assertEquals("", sdts.get(0).getTag()); - assertEquals("", sdts.get(0).getTitle()); - } - } - - @Test - void test62859() throws IOException { - //this doesn't test the exact code path for this issue, but - //it does test for a related issue, and the fix fixes both. - //We should try to add the actual triggering document - //to our test suite. - try (XWPFDocument doc =XWPFTestDataSamples.openSampleDocument("Bug62859.docx")) { - List<XWPFAbstractSDT> sdts = extractAllSDTs(doc); - assertEquals(1, sdts.size()); - assertEquals("", sdts.get(0).getTag()); - assertEquals("", sdts.get(0).getTitle()); - } - } - - private List<XWPFAbstractSDT> extractAllSDTs(XWPFDocument doc) { - List<XWPFAbstractSDT> sdts = new ArrayList<>(); - - List<XWPFHeader> headers = doc.getHeaderList(); - for (XWPFHeader header : headers) { - sdts.addAll(extractSDTsFromBodyElements(header.getBodyElements())); - } - sdts.addAll(extractSDTsFromBodyElements(doc.getBodyElements())); - - List<XWPFFooter> footers = doc.getFooterList(); - for (XWPFFooter footer : footers) { - sdts.addAll(extractSDTsFromBodyElements(footer.getBodyElements())); - } - - for (XWPFFootnote footnote : doc.getFootnotes()) { - sdts.addAll(extractSDTsFromBodyElements(footnote.getBodyElements())); - } - for (XWPFEndnote footnote : doc.getEndnotes()) { - sdts.addAll(extractSDTsFromBodyElements(footnote.getBodyElements())); - } - return sdts; - } - - private List<XWPFAbstractSDT> extractSDTsFromBodyElements(List<IBodyElement> elements) { - List<XWPFAbstractSDT> sdts = new ArrayList<>(); - for (IBodyElement e : elements) { - if (e instanceof XWPFSDT) { - XWPFSDT sdt = (XWPFSDT) e; - sdts.add(sdt); - } else if (e instanceof XWPFParagraph) { - - XWPFParagraph p = (XWPFParagraph) e; - for (IRunElement e2 : p.getIRuns()) { - if (e2 instanceof XWPFSDT) { - XWPFSDT sdt = (XWPFSDT) e2; - sdts.add(sdt); - } - } - } else if (e instanceof XWPFTable) { - XWPFTable table = (XWPFTable) e; - sdts.addAll(extractSDTsFromTable(table)); - } - } - return sdts; - } - - private List<XWPFAbstractSDT> extractSDTsFromTable(XWPFTable table) { - - List<XWPFAbstractSDT> sdts = new ArrayList<>(); - for (XWPFTableRow r : table.getRows()) { - for (ICell c : r.getTableICells()) { - if (c instanceof XWPFSDTCell) { - sdts.add((XWPFSDTCell) c); - } else if (c instanceof XWPFTableCell) { - sdts.addAll(extractSDTsFromBodyElements(((XWPFTableCell) c).getBodyElements())); - } - } - } - return sdts; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java deleted file mode 100644 index ffd9a5e02d..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java +++ /dev/null @@ -1,39 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.apache.poi.POITestCase.assertContains; - -import java.io.IOException; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; - -/** - * Tests for reading SmartTags from Word docx. - */ -public final class TestXWPFSmartTag { - @Test - void testSmartTags() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("smarttag-snippet.docx")) { - XWPFParagraph p = doc.getParagraphArray(0); - assertContains(p.getText(), "Carnegie Mellon University School of Computer Science"); - p = doc.getParagraphArray(2); - assertContains(p.getText(), "Alice's Adventures"); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java deleted file mode 100644 index 6c517f4c95..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java +++ /dev/null @@ -1,243 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STStyleType; - -public final class TestXWPFStyles { - @Test - void testGetUsedStyles() throws IOException { - try (XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("Styles.docx")) { - List<XWPFStyle> testUsedStyleList = new ArrayList<>(); - XWPFStyles styles = sampleDoc.getStyles(); - XWPFStyle style = styles.getStyle("berschrift1"); - testUsedStyleList.add(style); - testUsedStyleList.add(styles.getStyle("Standard")); - testUsedStyleList.add(styles.getStyle("berschrift1Zchn")); - testUsedStyleList.add(styles.getStyle("Absatz-Standardschriftart")); - style.hasSameName(style); - - List<XWPFStyle> usedStyleList = styles.getUsedStyleList(style); - assertEquals(usedStyleList, testUsedStyleList); - } - } - - @Test - void testAddStylesToDocument() throws IOException { - try (XWPFDocument docOut = new XWPFDocument()) { - XWPFStyles styles = docOut.createStyles(); - - String strStyleId = "headline1"; - CTStyle ctStyle = CTStyle.Factory.newInstance(); - - ctStyle.setStyleId(strStyleId); - XWPFStyle s = new XWPFStyle(ctStyle); - styles.addStyle(s); - - assertTrue(styles.styleExist(strStyleId)); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - styles = docIn.getStyles(); - assertTrue(styles.styleExist(strStyleId)); - } - } - - /** - * Bug #52449 - We should be able to write a file containing - * both regular and glossary styles without error - */ - @Test - void test52449() throws Exception { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52449.docx")) { - XWPFStyles styles = doc.getStyles(); - assertNotNull(styles); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(doc); - styles = docIn.getStyles(); - assertNotNull(styles); - } - } - - - /** - * YK: tests below don't make much sense, - * they exist only to copy xml beans to pi-ooxml-lite.jar - */ - @Test - void testLanguages() throws IOException { - try (XWPFDocument docOut = new XWPFDocument()) { - XWPFStyles styles = docOut.createStyles(); - styles.setEastAsia("Chinese"); - styles.setSpellingLanguage("English"); - - CTFonts def = CTFonts.Factory.newInstance(); - styles.setDefaultFonts(def); - - assertEquals(1, styles.getDefaultRunStyle().getRPr().sizeOfRFontsArray()); - } - } - - @Test - void testType() { - CTStyle ctStyle = CTStyle.Factory.newInstance(); - XWPFStyle style = new XWPFStyle(ctStyle); - - style.setType(STStyleType.PARAGRAPH); - assertEquals(STStyleType.PARAGRAPH, style.getType()); - } - - @Test - void testLatentStyles() { - CTLatentStyles latentStyles = CTLatentStyles.Factory.newInstance(); - CTLsdException ex = latentStyles.addNewLsdException(); - ex.setName("ex1"); - XWPFLatentStyles ls = new XWPFLatentStyles(latentStyles); - assertTrue(ls.isLatentStyle("ex1")); - assertFalse(ls.isLatentStyle("notex1")); - } - - @Test - void testSetStyles_Bug57254() throws IOException { - try (XWPFDocument docOut = new XWPFDocument()) { - XWPFStyles styles = docOut.createStyles(); - - CTStyles ctStyles = CTStyles.Factory.newInstance(); - String strStyleId = "headline1"; - CTStyle ctStyle = ctStyles.addNewStyle(); - - ctStyle.setStyleId(strStyleId); - styles.setStyles(ctStyles); - - assertTrue(styles.styleExist(strStyleId)); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - styles = docIn.getStyles(); - assertTrue(styles.styleExist(strStyleId)); - } - } - - @Test - void testEasyAccessToStyles() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx")) { - XWPFStyles styles = doc.getStyles(); - assertNotNull(styles); - - // Has 3 paragraphs on page one, a break, and 3 on page 2 - assertEquals(7, doc.getParagraphs().size()); - - // Check the first three have no run styles, just default paragraph style - for (int i = 0; i < 3; i++) { - XWPFParagraph p = doc.getParagraphs().get(i); - assertNull(p.getStyle()); - assertNull(p.getStyleID()); - assertEquals(1, p.getRuns().size()); - - XWPFRun r = p.getRuns().get(0); - assertNull(r.getColor()); - assertNull(r.getFontFamily()); - assertNull(r.getFontName()); - assertNull(r.getFontSizeAsDouble()); - } - - // On page two, has explicit styles, but on runs not on - // the paragraph itself - for (int i = 4; i < 7; i++) { - XWPFParagraph p = doc.getParagraphs().get(i); - assertNull(p.getStyle()); - assertNull(p.getStyleID()); - assertEquals(1, p.getRuns().size()); - - XWPFRun r = p.getRuns().get(0); - assertEquals("Arial Black", r.getFontFamily()); - assertEquals("Arial Black", r.getFontName()); - assertEquals(16.0, r.getFontSizeAsDouble(), 0.01); - assertEquals("548DD4", r.getColor()); - } - - // Check the document styles - // Should have a style defined for each type - assertEquals(4, styles.getNumberOfStyles()); - assertNotNull(styles.getStyle("Normal")); - assertNotNull(styles.getStyle("DefaultParagraphFont")); - assertNotNull(styles.getStyle("TableNormal")); - assertNotNull(styles.getStyle("NoList")); - - // We can't do much yet with latent styles - assertEquals(137, styles.getLatentStyles().getNumberOfStyles()); - - // Check the default styles - assertNotNull(styles.getDefaultRunStyle()); - assertNotNull(styles.getDefaultParagraphStyle()); - - assertEquals(11.0, styles.getDefaultRunStyle().getFontSizeAsDouble(), 0.01); - assertEquals(11.0, styles.getDefaultRunStyle().getFontSizeAsDouble(), 0.01); - assertEquals(200, styles.getDefaultParagraphStyle().getSpacingAfter()); - } - } - - // Bug 60329: style with missing StyleID throws NPE - @Test - void testMissingStyleId() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("60329.docx")) { - XWPFStyles styles = doc.getStyles(); - // Styles exist in the test document in this order, EmptyCellLayoutStyle - // is missing a StyleId - assertNotNull(styles.getStyle("NoList")); - assertNull(styles.getStyle("EmptyCellLayoutStyle")); - assertNotNull(styles.getStyle("BalloonText")); - - // Bug 64600: styleExist throws NPE - assertTrue(styles.styleExist("NoList")); - assertFalse(styles.styleExist("EmptyCellLayoutStyle")); - assertTrue(styles.styleExist("BalloonText")); - } - } - - @Test - void testGetStyleByName() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx")) { - XWPFStyles styles = doc.getStyles(); - assertNotNull(styles); - - String styleName = "Normal Table"; - XWPFStyle style = styles.getStyleWithName(styleName); - assertNotNull(style, "Expected to find style \"" + styleName + "\""); - assertEquals(styleName, style.getName()); - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java deleted file mode 100644 index 0feddb6819..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java +++ /dev/null @@ -1,593 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.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 java.io.IOException; -import java.math.BigInteger; -import java.util.List; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFTable.XWPFBorderType; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblBorders; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblCellMar; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGrid; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGridCol; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder; - - -/** - * Tests for XWPF Tables - */ -class TestXWPFTable { - - @Test - void testConstructor() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable xtab = new XWPFTable(ctTable, doc); - assertNotNull(xtab); - assertEquals(1, ctTable.sizeOfTrArray()); - assertEquals(1, ctTable.getTrArray(0).sizeOfTcArray()); - assertNotNull(ctTable.getTrArray(0).getTcArray(0).getPArray(0)); - - ctTable = CTTbl.Factory.newInstance(); - xtab = new XWPFTable(ctTable, doc, 3, 2); - assertNotNull(xtab); - assertEquals(3, ctTable.sizeOfTrArray()); - assertEquals(2, ctTable.getTrArray(0).sizeOfTcArray()); - assertNotNull(ctTable.getTrArray(0).getTcArray(0).getPArray(0)); - } - } - - @Test - void testTblGrid() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl ctTable = CTTbl.Factory.newInstance(); - CTTblGrid cttblgrid = ctTable.addNewTblGrid(); - cttblgrid.addNewGridCol().setW(BigInteger.valueOf(123)); - cttblgrid.addNewGridCol().setW(BigInteger.valueOf(321)); - - XWPFTable xtab = new XWPFTable(ctTable, doc); - CTTblGridCol[] ca = xtab.getCTTbl().getTblGrid().getGridColArray(); - assertEquals("123", ca[0].getW().toString()); - assertEquals("321", ca[1].getW().toString()); - } - } - - @Test - void testGetText() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl table = CTTbl.Factory.newInstance(); - CTRow row = table.addNewTr(); - CTTc cell = row.addNewTc(); - CTP paragraph = cell.addNewP(); - CTR run = paragraph.addNewR(); - CTText text = run.addNewT(); - text.setStringValue("finally I can write!"); - - XWPFTable xtab = new XWPFTable(table, doc); - assertEquals("finally I can write!\n", xtab.getText()); - } - } - - @Test - void testCreateRow() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - - CTTbl table = CTTbl.Factory.newInstance(); - CTRow r1 = table.addNewTr(); - r1.addNewTc().addNewP(); - r1.addNewTc().addNewP(); - CTRow r2 = table.addNewTr(); - r2.addNewTc().addNewP(); - r2.addNewTc().addNewP(); - CTRow r3 = table.addNewTr(); - r3.addNewTc().addNewP(); - r3.addNewTc().addNewP(); - - XWPFTable xtab = new XWPFTable(table, doc); - assertEquals(3, xtab.getNumberOfRows()); - assertNotNull(xtab.getRow(2)); - - //add a new row - xtab.createRow(); - assertEquals(4, xtab.getNumberOfRows()); - - //check number of cols - assertEquals(2, table.getTrArray(0).sizeOfTcArray()); - - //check creation of first row - xtab = new XWPFTable(CTTbl.Factory.newInstance(), doc); - assertEquals(1, xtab.getCTTbl().getTrArray(0).sizeOfTcArray()); - } - } - - @Test - void testSetGetWidth() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - - XWPFTable xtab = doc.createTable(); - - assertEquals(0, xtab.getWidth()); - assertEquals(TableWidthType.AUTO, xtab.getWidthType()); - - xtab.setWidth(1000); - assertEquals(TableWidthType.DXA, xtab.getWidthType()); - assertEquals(1000, xtab.getWidth()); - - xtab.setWidth("auto"); - assertEquals(TableWidthType.AUTO, xtab.getWidthType()); - assertEquals(0, xtab.getWidth()); - assertEquals(0.0, xtab.getWidthDecimal(), 0.01); - - xtab.setWidth("999"); - assertEquals(TableWidthType.DXA, xtab.getWidthType()); - assertEquals(999, xtab.getWidth()); - - xtab.setWidth("50.5%"); - assertEquals(TableWidthType.PCT, xtab.getWidthType()); - assertEquals(50.5, xtab.getWidthDecimal(), 0.01); - - // Test effect of setting width type to a new value - - // From PCT to NIL: - xtab.setWidthType(TableWidthType.NIL); - assertEquals(TableWidthType.NIL, xtab.getWidthType()); - assertEquals(0, xtab.getWidth()); - - xtab.setWidth("999"); // Sets type to DXA - assertEquals(TableWidthType.DXA, xtab.getWidthType()); - - // From DXA to AUTO: - xtab.setWidthType(TableWidthType.AUTO); - assertEquals(TableWidthType.AUTO, xtab.getWidthType()); - assertEquals(0, xtab.getWidth()); - - xtab.setWidthType(TableWidthType.PCT); - assertEquals(TableWidthType.PCT, xtab.getWidthType()); - - // From PCT to DXA: - xtab.setWidth("33.3%"); - xtab.setWidthType(TableWidthType.DXA); - assertEquals(TableWidthType.DXA, xtab.getWidthType()); - assertEquals(0, xtab.getWidth()); - - // From DXA to DXA: (value should be unchanged) - xtab.setWidth("999"); - xtab.setWidthType(TableWidthType.DXA); - assertEquals(TableWidthType.DXA, xtab.getWidthType()); - assertEquals(999, xtab.getWidth()); - - // From DXA to PCT: - xtab.setWidthType(TableWidthType.PCT); - assertEquals(TableWidthType.PCT, xtab.getWidthType()); - assertEquals(100.0, xtab.getWidthDecimal(), 0.0); - } - } - - @Test - void testSetGetHeight() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - - CTTbl table = CTTbl.Factory.newInstance(); - - XWPFTable xtab = new XWPFTable(table, doc); - XWPFTableRow row = xtab.createRow(); - row.setHeight(20); - assertEquals(20, row.getHeight()); - } - } - - @Test - void testSetGetMargins() throws IOException { - // instantiate the following class so it'll get picked up by - // the XmlBean process and added to the jar file. it's required - // for the following XWPFTable methods. - CTTblCellMar ctm = CTTblCellMar.Factory.newInstance(); - assertNotNull(ctm); - // create a table - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // set margins - table.setCellMargins(50, 50, 250, 450); - // get margin components - int t = table.getCellMarginTop(); - assertEquals(50, t); - int l = table.getCellMarginLeft(); - assertEquals(50, l); - int b = table.getCellMarginBottom(); - assertEquals(250, b); - int r = table.getCellMarginRight(); - assertEquals(450, r); - } - } - - @Test - void testSetGetHBorders() throws IOException { - // instantiate the following classes so they'll get picked up by - // the XmlBean process and added to the jar file. they are required - // for the following XWPFTable methods. - CTTblBorders cttb = CTTblBorders.Factory.newInstance(); - assertNotNull(cttb); - STBorder stb = STBorder.Factory.newInstance(); - assertNotNull(stb); - // create a table - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // check initial state - XWPFBorderType bt = table.getInsideHBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - int sz = table.getInsideHBorderSize(); - assertEquals(-1, sz); - int sp = table.getInsideHBorderSpace(); - assertEquals(-1, sp); - String clr = table.getInsideHBorderColor(); - assertNull(clr); - // set inside horizontal border - table.setInsideHBorder(XWPFBorderType.SINGLE, 4, 0, "FF0000"); - // get inside horizontal border components - bt = table.getInsideHBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - sz = table.getInsideHBorderSize(); - assertEquals(4, sz); - sp = table.getInsideHBorderSpace(); - assertEquals(0, sp); - clr = table.getInsideHBorderColor(); - assertEquals("FF0000", clr); - // remove the border and verify state - table.removeInsideHBorder(); - bt = table.getInsideHBorderType(); - assertNull(bt); - sz = table.getInsideHBorderSize(); - assertEquals(-1, sz); - sp = table.getInsideHBorderSpace(); - assertEquals(-1, sp); - clr = table.getInsideHBorderColor(); - assertNull(clr); - // check other borders - bt = table.getInsideVBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - bt = table.getTopBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - bt = table.getBottomBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - bt = table.getLeftBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - bt = table.getRightBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - // remove the rest all at once and test - table.removeBorders(); - bt = table.getInsideVBorderType(); - assertNull(bt); - bt = table.getTopBorderType(); - assertNull(bt); - bt = table.getBottomBorderType(); - assertNull(bt); - bt = table.getLeftBorderType(); - assertNull(bt); - bt = table.getRightBorderType(); - assertNull(bt); - } - } - - @Test - void testSetGetVBorders() throws IOException { - // create a table - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // check initial state - XWPFBorderType bt = table.getInsideVBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - int sz = table.getInsideVBorderSize(); - assertEquals(-1, sz); - int sp = table.getInsideVBorderSpace(); - assertEquals(-1, sp); - String clr = table.getInsideVBorderColor(); - assertNull(clr); - // set inside vertical border - table.setInsideVBorder(XWPFBorderType.DOUBLE, 4, 0, "00FF00"); - // get inside vertical border components - bt = table.getInsideVBorderType(); - assertEquals(XWPFBorderType.DOUBLE, bt); - sz = table.getInsideVBorderSize(); - assertEquals(4, sz); - sp = table.getInsideVBorderSpace(); - assertEquals(0, sp); - clr = table.getInsideVBorderColor(); - assertEquals("00FF00", clr); - // remove the border and verify state - table.removeInsideVBorder(); - bt = table.getInsideVBorderType(); - assertNull(bt); - sz = table.getInsideVBorderSize(); - assertEquals(-1, sz); - sp = table.getInsideVBorderSpace(); - assertEquals(-1, sp); - clr = table.getInsideVBorderColor(); - assertNull(clr); - // check the rest - bt = table.getInsideHBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - bt = table.getTopBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - bt = table.getBottomBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - bt = table.getLeftBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - bt = table.getRightBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - // remove the rest one at a time and test - table.removeInsideHBorder(); - table.removeTopBorder(); - table.removeBottomBorder(); - table.removeLeftBorder(); - table.removeRightBorder(); - bt = table.getInsideHBorderType(); - assertNull(bt); - bt = table.getTopBorderType(); - assertNull(bt); - bt = table.getBottomBorderType(); - assertNull(bt); - bt = table.getLeftBorderType(); - assertNull(bt); - bt = table.getRightBorderType(); - assertNull(bt); - } - } - - @Test - void testSetGetTopBorders() throws IOException { - // create a table - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // check initial state - XWPFBorderType bt = table.getTopBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - int sz = table.getTopBorderSize(); - assertEquals(-1, sz); - int sp = table.getTopBorderSpace(); - assertEquals(-1, sp); - String clr = table.getTopBorderColor(); - assertNull(clr); - // set top border - table.setTopBorder(XWPFBorderType.THICK, 4, 0, "00FF00"); - // get inside vertical border components - bt = table.getTopBorderType(); - assertEquals(XWPFBorderType.THICK, bt); - sz = table.getTopBorderSize(); - assertEquals(4, sz); - sp = table.getTopBorderSpace(); - assertEquals(0, sp); - clr = table.getTopBorderColor(); - assertEquals("00FF00", clr); - // remove the border and verify state - table.removeTopBorder(); - bt = table.getTopBorderType(); - assertNull(bt); - sz = table.getTopBorderSize(); - assertEquals(-1, sz); - sp = table.getTopBorderSpace(); - assertEquals(-1, sp); - clr = table.getTopBorderColor(); - assertNull(clr); - } - } - - @Test - void testSetGetBottomBorders() throws IOException { - // create a table - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // check initial state - XWPFBorderType bt = table.getBottomBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - int sz = table.getBottomBorderSize(); - assertEquals(-1, sz); - int sp = table.getBottomBorderSpace(); - assertEquals(-1, sp); - String clr = table.getBottomBorderColor(); - assertNull(clr); - // set inside vertical border - table.setBottomBorder(XWPFBorderType.DOTTED, 4, 0, "00FF00"); - // get inside vertical border components - bt = table.getBottomBorderType(); - assertEquals(XWPFBorderType.DOTTED, bt); - sz = table.getBottomBorderSize(); - assertEquals(4, sz); - sp = table.getBottomBorderSpace(); - assertEquals(0, sp); - clr = table.getBottomBorderColor(); - assertEquals("00FF00", clr); - // remove the border and verify state - table.removeBottomBorder(); - bt = table.getBottomBorderType(); - assertNull(bt); - sz = table.getBottomBorderSize(); - assertEquals(-1, sz); - sp = table.getBottomBorderSpace(); - assertEquals(-1, sp); - clr = table.getBottomBorderColor(); - assertNull(clr); - } - } - - @Test - void testSetGetLeftBorders() throws IOException { - // create a table - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // check initial state - XWPFBorderType bt = table.getLeftBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - int sz = table.getLeftBorderSize(); - assertEquals(-1, sz); - int sp = table.getLeftBorderSpace(); - assertEquals(-1, sp); - String clr = table.getLeftBorderColor(); - assertNull(clr); - // set inside vertical border - table.setLeftBorder(XWPFBorderType.DASHED, 4, 0, "00FF00"); - // get inside vertical border components - bt = table.getLeftBorderType(); - assertEquals(XWPFBorderType.DASHED, bt); - sz = table.getLeftBorderSize(); - assertEquals(4, sz); - sp = table.getLeftBorderSpace(); - assertEquals(0, sp); - clr = table.getLeftBorderColor(); - assertEquals("00FF00", clr); - // remove the border and verify state - table.removeLeftBorder(); - bt = table.getLeftBorderType(); - assertNull(bt); - sz = table.getLeftBorderSize(); - assertEquals(-1, sz); - sp = table.getLeftBorderSpace(); - assertEquals(-1, sp); - clr = table.getLeftBorderColor(); - assertNull(clr); - } - } - - @Test - void testSetGetRightBorders() throws IOException { - // create a table - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // check initial state - XWPFBorderType bt = table.getRightBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - int sz = table.getRightBorderSize(); - assertEquals(-1, sz); - int sp = table.getRightBorderSpace(); - assertEquals(-1, sp); - String clr = table.getRightBorderColor(); - assertNull(clr); - // set inside vertical border - table.setRightBorder(XWPFBorderType.DOT_DASH, 4, 0, "00FF00"); - // get inside vertical border components - bt = table.getRightBorderType(); - assertEquals(XWPFBorderType.DOT_DASH, bt); - sz = table.getRightBorderSize(); - assertEquals(4, sz); - sp = table.getRightBorderSpace(); - assertEquals(0, sp); - clr = table.getRightBorderColor(); - assertEquals("00FF00", clr); - // remove the border and verify state - table.removeRightBorder(); - bt = table.getRightBorderType(); - assertNull(bt); - sz = table.getRightBorderSize(); - assertEquals(-1, sz); - sp = table.getRightBorderSpace(); - assertEquals(-1, sp); - clr = table.getRightBorderColor(); - assertNull(clr); - } - } - - @Test - void testSetGetRowBandSize() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - table.setRowBandSize(12); - int sz = table.getRowBandSize(); - assertEquals(12, sz); - } - } - - @Test - void testSetGetColBandSize() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - table.setColBandSize(16); - int sz = table.getColBandSize(); - assertEquals(16, sz); - } - } - - @Test - void testCreateTable() throws Exception { - // open an empty document - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) { - - // create a table with 5 rows and 7 columns - int noRows = 5; - int noCols = 7; - XWPFTable table = doc.createTable(noRows, noCols); - - // assert the table is empty - List<XWPFTableRow> rows = table.getRows(); - assertEquals(noRows, rows.size(), "Table has less rows than requested."); - int row = 0; - for (XWPFTableRow xwpfRow : rows) { - assertNotNull(xwpfRow); - assertEquals(noCols, xwpfRow.getTableCells().size(), - "Row has less columns than requested."); - for (int i = 0; i < 7; i++) { - XWPFTableCell xwpfCell = xwpfRow.getCell(i); - assertNotNull(xwpfCell); - assertEquals(row != 0 || i != 0 ? 0 : 1, xwpfCell.getParagraphs().size(), - "Empty cells should not have one paragraph: " + i); - - xwpfCell = xwpfRow.getCell(i); - assertEquals(row != 0 || i != 0 ? 0 : 1, xwpfCell.getParagraphs().size(), - "Calling 'getCell' must not modify cells content: " + i); - } - - row++; - } - doc.getPackage().revert(); - } - } - - @Test - void testSetGetTableAlignment() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFTable tbl = doc.createTable(1, 1); - tbl.setTableAlignment(TableRowAlign.LEFT); - assertEquals(TableRowAlign.LEFT, tbl.getTableAlignment()); - tbl.setTableAlignment(TableRowAlign.CENTER); - assertEquals(TableRowAlign.CENTER, tbl.getTableAlignment()); - tbl.setTableAlignment(TableRowAlign.RIGHT); - assertEquals(TableRowAlign.RIGHT, tbl.getTableAlignment()); - tbl.removeTableAlignment(); - assertNull(tbl.getTableAlignment()); - } - } -}
\ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java deleted file mode 100644 index 36d0277568..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xwpf.usermodel; - -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; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.List; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign; -import org.apache.xmlbeans.XmlCursor; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHMerge; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcBorders; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVMerge; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc; - -class TestXWPFTableCell { - - @Test - void testSetGetVertAlignment() { - // instantiate the following classes so they'll get picked up by - // the XmlBean process and added to the jar file. they are required - // for the following XWPFTableCell methods. - CTShd ctShd = CTShd.Factory.newInstance(); - assertNotNull(ctShd); - CTVerticalJc ctVjc = CTVerticalJc.Factory.newInstance(); - assertNotNull(ctVjc); - STShd stShd = STShd.Factory.newInstance(); - assertNotNull(stShd); - STVerticalJc stVjc = STVerticalJc.Factory.newInstance(); - assertNotNull(stVjc); - - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); - assertNotNull(tr); - // row has a single cell by default; grab it - XWPFTableCell cell = tr.getCell(0); - - cell.setVerticalAlignment(XWPFVertAlign.BOTH); - XWPFVertAlign al = cell.getVerticalAlignment(); - assertEquals(XWPFVertAlign.BOTH, al); - } - - @Test - void testSetGetColor() { - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); - assertNotNull(tr); - // row has a single cell by default; grab it - XWPFTableCell cell = tr.getCell(0); - - cell.setColor("F0000F"); - String clr = cell.getColor(); - assertEquals("F0000F", clr); - } - - /** - * ensure that CTHMerge and CTTcBorders go in poi-ooxml.jar - */ - @Test - void test54099() { - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - XWPFTableRow tr = table.getRow(0); - XWPFTableCell cell = tr.getCell(0); - - CTTc ctTc = cell.getCTTc(); - CTTcPr tcPr = ctTc.addNewTcPr(); - CTHMerge hMerge = tcPr.addNewHMerge(); - hMerge.setVal(STMerge.RESTART); - - CTTcBorders tblBorders = tcPr.addNewTcBorders(); - assertNotNull(tblBorders); - CTVMerge vMerge = tcPr.addNewVMerge(); - assertNotNull(vMerge); - } - - @Test - void testCellVerticalAlign() throws Exception{ - try (XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("59030.docx")) { - List<XWPFTable> tables = docx.getTables(); - assertEquals(1, tables.size()); - - XWPFTable table = tables.get(0); - - List<XWPFTableRow> tableRows = table.getRows(); - assertEquals(2, tableRows.size()); - - assertNull(tableRows.get(0).getCell(0).getVerticalAlignment()); - assertEquals(XWPFVertAlign.BOTTOM, tableRows.get(0).getCell(1).getVerticalAlignment()); - assertEquals(XWPFVertAlign.CENTER, tableRows.get(1).getCell(0).getVerticalAlignment()); - assertNull(tableRows.get(1).getCell(1).getVerticalAlignment()); // should return null since alignment isn't set - } - } - - @Test - void testCellVerticalAlignShouldNotThrowNPE() throws Exception { - try (XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("TestTableCellAlign.docx")) { - String[] act = docx.getTables().stream() - .flatMap(t -> t.getRows().stream()) - .flatMap(r -> r.getTableICells().stream()) - .map(XWPFTableCell.class::cast) - .map(XWPFTableCell::getVerticalAlignment) - .map(e -> e == null ? null : e.name()) - .toArray(String[]::new); - - String[] exp = { null, "BOTTOM", "CENTER", null}; - assertArrayEquals(exp, act); - } - } - - @Test - void testCellGetSetWidth() throws Exception { - XWPFDocument doc = new XWPFDocument(); - XWPFTable table = doc.createTable(); - XWPFTableRow tr = table.createRow(); - XWPFTableCell cell = tr.addNewTableCell(); - - cell.setWidth("50%"); - assertEquals(TableWidthType.PCT, cell.getWidthType()); - assertEquals(50.0, cell.getWidthDecimal(), 0.0); - assertEquals(2500, cell.getWidth()); - doc.close(); - } - - @Test - void testAddParagraph() throws Exception { - XWPFDocument doc = new XWPFDocument(); - XWPFTable table = doc.createTable(); - XWPFTableRow tr = table.createRow(); - XWPFTableCell cell = tr.addNewTableCell(); - - // now paragraph or body element initially - assertEquals(0, cell.getParagraphs().size()); - assertEquals(0, cell.getBodyElements().size()); - - XWPFParagraph p = cell.addParagraph(); - assertEquals(1, cell.getParagraphs().size()); - assertEquals(1, cell.getBodyElements().size()); - assertSame(p, cell.getParagraphArray(0)); - assertEquals(cell.getParagraphArray(0), cell.getBodyElements().get(0)); - - doc.close(); - } - - @Test - void testRemoveParagraph() throws Exception { - XWPFDocument doc = new XWPFDocument(); - XWPFTable table = doc.createTable(); - XWPFTableRow tr = table.createRow(); - XWPFTableCell cell = tr.addNewTableCell(); - - // cell have no paragraph by default - assertNull(cell.getParagraphArray(0)); - - XWPFParagraph p0 = cell.addParagraph(); - XWPFParagraph p1 = cell.addParagraph(); - cell.addParagraph(); - - // remove 3rd - cell.removeParagraph(2); - assertEquals(2, cell.getParagraphs().size()); - assertEquals(2, cell.getBodyElements().size()); - assertEquals(p0, cell.getParagraphArray(0)); - assertEquals(p1, cell.getParagraphArray(1)); - assertEquals(p0, cell.getBodyElements().get(0)); - assertEquals(p1, cell.getBodyElements().get(1)); - - // remove 2nd - cell.removeParagraph(1); - assertEquals(1, cell.getParagraphs().size()); - assertEquals(1, cell.getBodyElements().size()); - assertEquals(p0, cell.getParagraphArray(0)); - assertEquals(p0, cell.getBodyElements().get(0)); - - doc.close(); - } - - @Test - void testRemoveTable() throws Exception { - XWPFDocument doc = new XWPFDocument(); - XWPFTable table = doc.createTable(); - XWPFTableRow tr = table.createRow(); - XWPFTableCell cell = tr.addNewTableCell(); - - // cell should not have any elements by default - assertTrue(cell.getParagraphs().isEmpty()); - - XWPFParagraph p = cell.addParagraph(); - assertNotNull(p); - - XWPFParagraph p0 = cell.getParagraphArray(0); - XmlCursor newCursor = p0.getCTP().newCursor(); - cell.insertNewTbl(newCursor); - newCursor.dispose(); - - assertEquals(1, cell.getTables().size()); - assertEquals(2, cell.getBodyElements().size()); - - // remove table - cell.removeTable(0); - assertEquals(0, cell.getTables().size()); - assertEquals(1, cell.getBodyElements().size()); - assertEquals(p0, cell.getBodyElements().get(0)); - - doc.close(); - } - - @Test - void testBug63624() throws Exception { - XWPFDocument doc = new XWPFDocument(); - XWPFTable table = doc.createTable(1, 1); - XWPFTableRow row = table.getRow(0); - XWPFTableCell cell = row.getCell(0); - - String expected = "this must not be empty"; - cell.setText(expected); - String actual = cell.getText(); - assertEquals(expected, actual); - doc.close(); - } - - @Test - void test63624() { - XWPFDocument doc = new XWPFDocument(); - XWPFTable table = doc.createTable(1, 1); - XWPFTableRow row = table.getRow(0); - XWPFTableCell cell = row.getCell(0); - - cell.setText("test text 1"); - assertEquals("test text 1", cell.getText()); - - // currently the text is added, I am not sure if this is expected or not... - cell.setText("test text 2"); - assertEquals("test text 1test text 2", cell.getText()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java deleted file mode 100644 index 1c1fe03c88..0000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java +++ /dev/null @@ -1,187 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.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.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ooxml.util.POIXMLUnits; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHeight; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHeightRule; - -class TestXWPFTableRow { - - @Test - void testCreateRow() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFTable table = doc.createTable(1, 1); - XWPFTableRow tr = table.createRow(); - assertNotNull(tr); - } - } - - @Test - void testSetGetCantSplitRow() throws IOException { - // create a table - try (XWPFDocument doc = new XWPFDocument()) { - XWPFTable table = doc.createTable(1, 1); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); - assertNotNull(tr); - - // Assert the repeat header is false by default - boolean isCantSplit = tr.isCantSplitRow(); - assertFalse(isCantSplit); - - // Repeat the header - tr.setCantSplitRow(true); - isCantSplit = tr.isCantSplitRow(); - assertTrue(isCantSplit); - - // Make the header no longer repeating - tr.setCantSplitRow(false); - isCantSplit = tr.isCantSplitRow(); - assertFalse(isCantSplit); - } - } - - @Test - void testSetGetRepeatHeader() throws IOException { - // create a table - try (XWPFDocument doc = new XWPFDocument()) { - XWPFTable table = doc.createTable(3, 1); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); - assertNotNull(tr); - - // Assert the repeat header is false by default - boolean isRpt = tr.isRepeatHeader(); - assertFalse(isRpt); - - // Repeat the header - tr.setRepeatHeader(true); - isRpt = tr.isRepeatHeader(); - assertTrue(isRpt); - - // Make the header no longer repeating - tr.setRepeatHeader(false); - isRpt = tr.isRepeatHeader(); - assertFalse(isRpt); - - // If the third row is set to repeat, but not the second, - // isRepeatHeader should report false because Word will - // ignore it. - tr = table.getRow(2); - tr.setRepeatHeader(true); - isRpt = tr.isRepeatHeader(); - assertFalse(isRpt); - } - } - - // Test that validates the table header value can be parsed from a document - // generated in Word - @Test - void testIsRepeatHeader() throws Exception { - try (XWPFDocument doc = XWPFTestDataSamples - .openSampleDocument("Bug60337.docx")) { - XWPFTable table = doc.getTables().get(0); - XWPFTableRow tr = table.getRow(0); - boolean isRpt = tr.isRepeatHeader(); - assertTrue(isRpt); - - tr = table.getRow(1); - isRpt = tr.isRepeatHeader(); - assertFalse(isRpt); - - tr = table.getRow(2); - isRpt = tr.isRepeatHeader(); - assertFalse(isRpt); - } - } - - - // Test that validates the table header value can be parsed from a document - // generated in Word - @Test - void testIsCantSplit() throws Exception { - try (XWPFDocument doc = XWPFTestDataSamples - .openSampleDocument("Bug60337.docx")) { - XWPFTable table = doc.getTables().get(0); - XWPFTableRow tr = table.getRow(0); - boolean isCantSplit = tr.isCantSplitRow(); - assertFalse(isCantSplit); - - tr = table.getRow(1); - isCantSplit = tr.isCantSplitRow(); - assertFalse(isCantSplit); - - tr = table.getRow(2); - isCantSplit = tr.isCantSplitRow(); - assertTrue(isCantSplit); - } - } - - @Test - void testRemoveCell() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFTableRow tr = doc.createTable(1, 1).createRow(); - - assertEquals(1, tr.getTableCells().size()); - assertEquals(tr.getTableCells().size(), tr.getCtRow().sizeOfTcArray()); - - tr.removeCell(0); - assertEquals(0, tr.getTableCells().size()); - assertEquals(tr.getTableCells().size(), tr.getCtRow().sizeOfTcArray()); - } - } - - @Test - void testGetSetHeightRule() throws IOException { - try (XWPFDocument doc = new XWPFDocument()) { - XWPFTableRow tr = doc.createTable(1, 1).createRow(); - assertEquals(TableRowHeightRule.AUTO, tr.getHeightRule()); - - tr.setHeightRule(TableRowHeightRule.AT_LEAST); - assertEquals(TableRowHeightRule.AT_LEAST, tr.getHeightRule()); - - tr.setHeightRule(TableRowHeightRule.EXACT); - assertEquals(TableRowHeightRule.EXACT, tr.getHeightRule()); - } - } - - @Test - void testBug62174() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug60337.docx")) { - XWPFTable table = doc.getTables().get(0); - XWPFTableRow tr = table.getRow(0); - - int twipsPerInch = 1440; - tr.setHeight(twipsPerInch/10); - CTHeight height = tr.getCtRow().getTrPr().getTrHeightArray(0); - height.setHRule(STHeightRule.EXACT); - assertEquals(twipsPerInch/10., Units.toDXA(POIXMLUnits.parseLength(height.xgetVal())), 0); - } - } -} |