files = new ArrayList<>(7);
- final POIFSReader r = new POIFSReader();
- final POIFSReaderListener pfl = event -> assertDoesNotThrow(() -> {
- final POIFile f = new POIFile();
- f.setName(event.getName());
- f.setPath(event.getPath());
- final InputStream in = event.getStream();
- if (PropertySet.isPropertySetStream(in)) {
- f.setBytes(IOUtils.toByteArray(in));
- files.add(f);
- }
- });
-
- /* Register the listener for all POI files. */
- r.registerListener(pfl);
-
- /* Read the POI filesystem. */
- r.read(poiFs);
-
- return files;
- }
-}
diff --git a/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java b/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java
deleted file mode 100644
index 85d7d02b89..0000000000
--- a/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hpsf.extractor;
-
-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.IOException;
-import java.io.InputStream;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hpsf.Thumbnail;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.extractor.ExcelExtractor;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.junit.jupiter.api.Test;
-
-final class TestHPSFPropertiesExtractor {
- private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance();
-
- @Test
- void testNormalProperties() throws Exception {
- try (InputStream is = _samples.openResourceAsStream("TestMickey.doc");
- POIFSFileSystem fs = new POIFSFileSystem(is);
- HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs)) {
- // Check each bit in turn
- String summary = ext.getSummaryInformationText();
- String docSummary = ext.getDocumentSummaryInformationText();
-
- assertContains(summary, "TEMPLATE = Normal");
- assertContains(summary, "SUBJECT = sample subject");
- assertContains(docSummary, "MANAGER = sample manager");
- assertContains(docSummary, "COMPANY = sample company");
-
- // Now overall
- String text = ext.getText();
- assertContains(text, "TEMPLATE = Normal");
- assertContains(text, "SUBJECT = sample subject");
- assertContains(text, "MANAGER = sample manager");
- assertContains(text, "COMPANY = sample company");
- }
- }
-
- @Test
- void testNormalUnicodeProperties() throws Exception {
-
- try (InputStream is = _samples.openResourceAsStream("TestUnicode.xls");
- POIFSFileSystem fs = new POIFSFileSystem(is);
- HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs)) {
- // Check each bit in turn
- String summary = ext.getSummaryInformationText();
- String docSummary = ext.getDocumentSummaryInformationText();
-
- assertContains(summary, "AUTHOR = marshall");
- assertContains(summary, "TITLE = Titel: \u00c4h");
- assertContains(docSummary, "COMPANY = Schreiner");
- assertContains(docSummary, "SCALE = false");
-
- // Now overall
- String text = ext.getText();
- assertContains(text, "AUTHOR = marshall");
- assertContains(text, "TITLE = Titel: \u00c4h");
- assertContains(text, "COMPANY = Schreiner");
- assertContains(text, "SCALE = false");
- }
- }
-
- @Test
- void testCustomProperties() throws Exception {
- try (InputStream is = _samples.openResourceAsStream("TestMickey.doc");
- POIFSFileSystem fs = new POIFSFileSystem(is);
- HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs)) {
-
- // Custom properties are part of the document info stream
- String dinfText = ext.getDocumentSummaryInformationText();
- assertContains(dinfText, "Client = sample client");
- assertContains(dinfText, "Division = sample division");
-
- String text = ext.getText();
- assertContains(text, "Client = sample client");
- assertContains(text, "Division = sample division");
- }
- }
-
- @Test
- void testConstructors() throws IOException {
- final String fsText;
- final String hwText;
- final String eeText;
-
- try (POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream("TestUnicode.xls"));
- HSSFWorkbook wb = new HSSFWorkbook(fs);
- ExcelExtractor excelExt = new ExcelExtractor(wb)) {
-
- try (HPSFPropertiesExtractor fsExt = new HPSFPropertiesExtractor(fs)) {
- // Don't close re-used test resources!
- fsExt.setCloseFilesystem(false);
- fsText = fsExt.getText();
- }
-
- try (HPSFPropertiesExtractor hwExt = new HPSFPropertiesExtractor(wb)) {
- // Don't close re-used test resources!
- hwExt.setCloseFilesystem(false);
- hwText = hwExt.getText();
- }
-
- try (HPSFPropertiesExtractor eeExt = new HPSFPropertiesExtractor(excelExt)) {
- // Don't close re-used test resources!
- eeExt.setCloseFilesystem(false);
- eeText = eeExt.getText();
- }
- }
-
- assertEquals(fsText, hwText);
- assertEquals(fsText, eeText);
-
- assertContains(fsText, "AUTHOR = marshall");
- assertContains(fsText, "TITLE = Titel: \u00c4h");
- }
-
- @Test
- void test42726() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42726.xls");
- HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(wb)) {
- String txt = ext.getText();
- assertContains(txt, "PID_AUTHOR");
- assertContains(txt, "PID_EDITTIME");
- assertContains(txt, "PID_REVNUMBER");
- assertContains(txt, "PID_THUMBNAIL");
- }
- }
-
- @Test
- void testThumbnail() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream("TestThumbnail.xls"));
- HSSFWorkbook wb = new HSSFWorkbook(fs);
- Thumbnail thumbnail = new Thumbnail(wb.getSummaryInformation().getThumbnail());
- assertEquals(-1, thumbnail.getClipboardFormatTag());
- assertEquals(3, thumbnail.getClipboardFormat());
- assertNotNull(thumbnail.getThumbnailAsWMF());
- wb.close();
- }
-
- @Test
- void test52258() throws Exception {
- try (InputStream is = _samples.openResourceAsStream("TestVisioWithCodepage.vsd");
- POIFSFileSystem fs = new POIFSFileSystem(is);
- HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs)) {
- assertNotNull(ext.getDocSummaryInformation());
- assertNotNull(ext.getDocumentSummaryInformationText());
- assertNotNull(ext.getSummaryInformation());
- assertNotNull(ext.getSummaryInformationText());
- assertNotNull(ext.getText());
- }
- }
-
- @Test
- void test61300Extractor() throws IOException {
- try (POIFSFileSystem poifs = new POIFSFileSystem(
- POIDataSamples.getPOIFSInstance().getFile("61300.bin"))) {
- HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(poifs);
- assertContains(ext.getText(), "PID_CODEPAGE = 1252");
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/HSSFITestDataProvider.java b/src/testcases/org/apache/poi/hssf/HSSFITestDataProvider.java
deleted file mode 100644
index 5d80a26d53..0000000000
--- a/src/testcases/org/apache/poi/hssf/HSSFITestDataProvider.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf;
-
-import java.io.InputStream;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-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;
-
-/**
- * @author Yegor Kozlov
- */
-public final class HSSFITestDataProvider implements ITestDataProvider {
- public static final HSSFITestDataProvider instance = new HSSFITestDataProvider();
-
- private HSSFITestDataProvider(){
- // enforce singleton
- }
-
- @Override
- public HSSFWorkbook openSampleWorkbook(String sampleFileName) {
- return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
- }
-
- public InputStream openWorkbookStream(String sampleFileName) {
- return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
- }
-
- @Override
- public HSSFWorkbook writeOutAndReadBack(Workbook original) {
- if(!(original instanceof HSSFWorkbook)) {
- throw new IllegalArgumentException("Expected an instance of HSSFWorkbook");
- }
- return HSSFTestDataSamples.writeOutAndReadBack((HSSFWorkbook)original);
- }
-
- @Override
- public HSSFWorkbook createWorkbook(){
- return new HSSFWorkbook();
- }
-
- //************ SXSSF-specific methods ***************//
- @Override
- public HSSFWorkbook createWorkbook(int rowAccessWindowSize) {
- return createWorkbook();
- }
-
- @Override
- public void trackAllColumnsForAutosizing(Sheet sheet) {}
- //************ End SXSSF-specific methods ***************//
-
- @Override
- public FormulaEvaluator createFormulaEvaluator(Workbook wb) {
- return new HSSFFormulaEvaluator((HSSFWorkbook) wb);
- }
-
- @Override
- public byte[] getTestDataFileContent(String fileName) {
- return POIDataSamples.getSpreadSheetInstance().readFile(fileName);
- }
-
- @Override
- public SpreadsheetVersion getSpreadsheetVersion(){
- return SpreadsheetVersion.EXCEL97;
- }
-
- @Override
- public String getStandardFileNameExtension() {
- return "xls";
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java b/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java
deleted file mode 100644
index 2fe3359d4d..0000000000
--- a/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.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.hssf;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-
-/**
- * Centralises logic for finding/opening sample files in the src/testcases/org/apache/poi/hssf/hssf/data folder.
- *
- * @author Josh Micich
- */
-public final class HSSFTestDataSamples {
-
- private static final POIDataSamples _inst = POIDataSamples.getSpreadSheetInstance();
-
- public static InputStream openSampleFileStream(String sampleFileName) {
- return _inst.openResourceAsStream(sampleFileName);
- }
- public static File getSampleFile(String sampleFileName) {
- return _inst.getFile(sampleFileName);
- }
- public static byte[] getTestDataFileContent(String fileName) {
- return _inst.readFile(fileName);
- }
-
- public static HSSFWorkbook openSampleWorkbook(String sampleFileName) {
- try {
- return new HSSFWorkbook(_inst.openResourceAsStream(sampleFileName));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * Writes a spreadsheet to a ByteArrayOutputStream and reads it back
- * from a ByteArrayInputStream.
- * Useful for verifying that the serialisation round trip
- */
- public static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) {
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
- original.write(baos);
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- return new HSSFWorkbook(bais);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java b/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java
deleted file mode 100644
index 91481c80ec..0000000000
--- a/src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-package org.apache.poi.hssf.dev;
-
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.stream.Stream;
-
-import org.apache.poi.POIDataSamples;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.Arguments;
-import org.junit.jupiter.params.provider.MethodSource;
-
-/**
- * Base class for integration-style tests which iterate over all test-files
- * and execute the same action to find out if any change breaks these applications.
- */
-public abstract class BaseTestIteratingXLS {
- protected static final Map> EXCLUDED = new HashMap<>();
-
- private static Stream files() {
- String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY);
- if(dataDirName == null) {
- dataDirName = "test-data";
- }
-
- List files = new ArrayList<>();
- findFile(files, dataDirName + "/spreadsheet");
- findFile(files, dataDirName + "/hpsf");
-
- return files.stream();
- }
-
- private static void findFile(List list, String dir) {
- String[] files = new File(dir).list((arg0, arg1) -> arg1.toLowerCase(Locale.ROOT).endsWith(".xls"));
- assertNotNull(files, "Did not find any xls files in directory " + dir);
-
- for(String file : files) {
- list.add(Arguments.of(new File(dir, file)));
- }
- }
-
- @ParameterizedTest
- @MethodSource("files")
- void testMain(File file) throws Exception {
- String fileName = file.getName();
-
- Class extends Throwable> t = EXCLUDED.get(fileName);
-
- if (t == null) {
- runOneFile(file);
- } else {
- assertThrows(t, () -> runOneFile(file));
- }
-
- }
-
- abstract void runOneFile(File pFile) throws Exception;
-}
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java
deleted file mode 100644
index ee06b7d101..0000000000
--- a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.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.hssf.dev;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.hssf.OldExcelFormatException;
-import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.util.NullOutputStream;
-import org.apache.poi.util.RecordFormatException;
-import org.junit.jupiter.api.BeforeAll;
-
-class TestBiffDrawingToXml extends BaseTestIteratingXLS {
- @BeforeAll
- public static void setup() {
- EXCLUDED.clear();
- EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
- EXCLUDED.put("51832.xls", EncryptedDocumentException.class);
- EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
- EXCLUDED.put("password.xls", EncryptedDocumentException.class);
- EXCLUDED.put("46904.xls", OldExcelFormatException.class);
- EXCLUDED.put("59074.xls", OldExcelFormatException.class);
- EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2
- EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2
- EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2
- EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95
- EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well
- EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class);
- EXCLUDED.put("61300.xls", RecordFormatException.class);
- EXCLUDED.put("64130.xls", OldExcelFormatException.class); // BIFF 5
- }
-
- @Override
- void runOneFile(File pFile) throws Exception {
- try (InputStream wb = new FileInputStream(pFile)) {
- BiffDrawingToXml.writeToFile(new NullOutputStream(), wb, false, new String[0]);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java
deleted file mode 100644
index 7c6cf1b1f5..0000000000
--- a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.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.hssf.dev;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-
-import org.apache.poi.hssf.OldExcelFormatException;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.util.LocaleUtil;
-import org.apache.poi.util.NullOutputStream;
-import org.apache.poi.util.RecordFormatException;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.parallel.Execution;
-import org.junit.jupiter.api.parallel.ExecutionMode;
-
-@Execution(ExecutionMode.CONCURRENT)
-class TestBiffViewer extends BaseTestIteratingXLS {
- @BeforeAll
- public static void setup() {
- EXCLUDED.clear();
- EXCLUDED.put("35897-type4.xls", IllegalArgumentException.class); // unsupported crypto api header
- EXCLUDED.put("51832.xls", IllegalArgumentException.class);
- EXCLUDED.put("xor-encryption-abc.xls", RecordFormatException.class);
- EXCLUDED.put("password.xls", IllegalArgumentException.class);
- EXCLUDED.put("46904.xls", OldExcelFormatException.class);
- EXCLUDED.put("59074.xls", OldExcelFormatException.class);
- EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2
- EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2
- EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2
- EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95
- EXCLUDED.put("43493.xls", RecordFormatException.class); // HSSFWorkbook cannot open it as well
- // EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class);
- EXCLUDED.put("50833.xls", IllegalArgumentException.class); // "Name is too long" when setting username
- EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun"
- EXCLUDED.put("61300.xls", IndexOutOfBoundsException.class);
- EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5
- }
-
- @Override
- void runOneFile(File fileIn) throws IOException {
- try (POIFSFileSystem fs = new POIFSFileSystem(fileIn, true);
- InputStream is = BiffViewer.getPOIFSInputStream(fs)) {
- // use a NullOutputStream to not write the bytes anywhere for best runtime
- PrintWriter dummy = new PrintWriter(new OutputStreamWriter(new NullOutputStream(), LocaleUtil.CHARSET_1252));
- BiffViewer.runBiffViewer(dummy, is, true, true, true, false);
- }
- }
-
-// @Test
-// @Disabled("only used for manual tests")
-// @SuppressWarnings("java:S2699")
-// void testOneFile() throws Exception {
-// POIDataSamples samples = POIDataSamples.getSpreadSheetInstance();
-// runOneFile(samples.getFile("43493.xls"));
-// }
-}
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java
deleted file mode 100644
index 56be2c87af..0000000000
--- a/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.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.hssf.dev;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintStream;
-
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.hssf.OldExcelFormatException;
-import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.util.NullPrintStream;
-import org.apache.poi.util.RecordFormatException;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.parallel.ResourceLock;
-import org.junit.jupiter.api.parallel.Resources;
-
-@ResourceLock(Resources.SYSTEM_OUT)
-class TestEFBiffViewer extends BaseTestIteratingXLS {
- @BeforeAll
- public static void setup() {
- EXCLUDED.clear();
- EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
- EXCLUDED.put("51832.xls", EncryptedDocumentException.class);
- EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
- EXCLUDED.put("password.xls", EncryptedDocumentException.class);
- EXCLUDED.put("46904.xls", OldExcelFormatException.class);
- EXCLUDED.put("59074.xls", OldExcelFormatException.class);
- EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2
- EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2
- EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2
- EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95
- EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well
- EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class);
- // EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun"
- EXCLUDED.put("61300.xls", RecordFormatException.class);
- EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5
- }
-
- @Override
- void runOneFile(File fileIn) throws IOException {
- PrintStream save = System.out;
- try {
- // redirect standard out during the test to avoid spamming the console with output
- System.setOut(new NullPrintStream());
-
- EFBiffViewer.main(new String[] { fileIn.getAbsolutePath() });
- } finally {
- System.setOut(save);
- }
- }
-
- //@Test
- void testFile() throws IOException {
- EFBiffViewer viewer = new EFBiffViewer();
- viewer.setFile(new File("test-data/spreadsheet/59074.xls").getAbsolutePath());
- viewer.run();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java
deleted file mode 100644
index a0cdaddcd2..0000000000
--- a/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.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.hssf.dev;
-
-import static org.junit.jupiter.api.Assumptions.assumeTrue;
-
-import java.io.File;
-import java.io.PrintStream;
-
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.hssf.OldExcelFormatException;
-import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.util.NullPrintStream;
-import org.apache.poi.util.RecordFormatException;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.parallel.ResourceLock;
-import org.junit.jupiter.api.parallel.Resources;
-
-@ResourceLock(Resources.SYSTEM_OUT)
-class TestFormulaViewer extends BaseTestIteratingXLS {
- @BeforeAll
- public static void setup() {
- EXCLUDED.clear();
- EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
- EXCLUDED.put("51832.xls", EncryptedDocumentException.class);
- EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
- EXCLUDED.put("password.xls", EncryptedDocumentException.class);
- EXCLUDED.put("46904.xls", OldExcelFormatException.class);
- EXCLUDED.put("59074.xls", OldExcelFormatException.class);
- EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2
- EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2
- EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2
- EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95
- EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well
- EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class);
- EXCLUDED.put("61300.xls", RecordFormatException.class);
- EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5
- }
-
- @Override
- void runOneFile(File fileIn) throws Exception {
- PrintStream save = System.out;
- try {
- // redirect standard out during the test to avoid spamming the console with output
- System.setOut(new NullPrintStream());
-
- FormulaViewer viewer = new FormulaViewer();
- viewer.setFile(fileIn.getAbsolutePath());
- viewer.setList(true);
- viewer.run();
- } catch (RuntimeException re) {
- String m = re.getMessage();
- if (m.startsWith("toFormulaString") || m.startsWith("3D references")) {
- // TODO: fix those cases, but ignore them for now ...
- assumeTrue(true);
- } else {
- throw re;
- }
- } finally {
- System.setOut(save);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestReSave.java b/src/testcases/org/apache/poi/hssf/dev/TestReSave.java
deleted file mode 100644
index 868561df21..0000000000
--- a/src/testcases/org/apache/poi/hssf/dev/TestReSave.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-package org.apache.poi.hssf.dev;
-
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.File;
-import java.io.PrintStream;
-
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hssf.OldExcelFormatException;
-import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.util.NullPrintStream;
-import org.apache.poi.util.RecordFormatException;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.parallel.Isolated;
-import org.junit.jupiter.api.parallel.ResourceLock;
-import org.junit.jupiter.api.parallel.Resources;
-
-@Isolated("Modifies the test data directory")
-@ResourceLock(Resources.SYSTEM_OUT)
-class TestReSave extends BaseTestIteratingXLS {
- @BeforeAll
- public static void setup() {
- EXCLUDED.clear();
- EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
- EXCLUDED.put("51832.xls", EncryptedDocumentException.class);
- EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
- EXCLUDED.put("password.xls", EncryptedDocumentException.class);
- EXCLUDED.put("46904.xls", OldExcelFormatException.class);
- EXCLUDED.put("59074.xls", OldExcelFormatException.class);
- EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2
- EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2
- EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2
- EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95
- EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well
- EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class);
- EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun"
- EXCLUDED.put("61300.xls", RecordFormatException.class);
- EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5
- }
-
- @Override
- void runOneFile(File fileIn) throws Exception {
- // avoid running on files leftover from previous failed runs
- if(fileIn.getName().endsWith("-saved.xls")) {
- return;
- }
-
- PrintStream save = System.out;
- try {
- // redirect standard out during the test to avoid spamming the console with output
- System.setOut(new NullPrintStream());
-
- File reSavedFile = new File(fileIn.getParentFile(), fileIn.getName().replace(".xls", "-saved.xls"));
- try {
- ReSave.main(new String[] { fileIn.getAbsolutePath() });
-
- // also try BiffViewer on the saved file
- new TestBiffViewer().runOneFile(reSavedFile);
-
- // had one case where the re-saved could not be re-saved!
- ReSave.main(new String[] { "-bos", reSavedFile.getAbsolutePath() });
- } finally {
- // clean up the re-saved file
- assertTrue(!reSavedFile.exists() || reSavedFile.delete());
- }
- } finally {
- System.setOut(save);
- }
- }
-
- @Disabled("Only used for local testing")
- @Test
- void testOneFile() throws Exception {
- String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY);
- if(dataDirName == null) {
- dataDirName = "test-data";
- }
-
- runOneFile(new File(dataDirName + "/spreadsheet", "49931.xls"));
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java b/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java
deleted file mode 100644
index 9eb6ebc255..0000000000
--- a/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.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.hssf.dev;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintStream;
-
-import org.apache.poi.hssf.OldExcelFormatException;
-import org.apache.poi.util.NullPrintStream;
-import org.apache.poi.util.RecordFormatException;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.parallel.ResourceLock;
-import org.junit.jupiter.api.parallel.Resources;
-
-@ResourceLock(Resources.SYSTEM_OUT)
-class TestRecordLister extends BaseTestIteratingXLS {
- @BeforeAll
- public static void setup() {
- EXCLUDED.clear();
- EXCLUDED.put("46904.xls", OldExcelFormatException.class);
- EXCLUDED.put("59074.xls", OldExcelFormatException.class);
- EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2
- EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2
- EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2
- EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
- EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95
- EXCLUDED.put("61300.xls", RecordFormatException.class);
- EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5
- }
-
- @Override
- void runOneFile(File fileIn) throws IOException {
- PrintStream save = System.out;
- try {
- // redirect standard out during the test to avoid spamming the console with output
- System.setOut(new NullPrintStream());
-
- RecordLister viewer = new RecordLister();
- viewer.setFile(fileIn.getAbsolutePath());
- viewer.run();
- } finally {
- System.setOut(save);
- }
- }
-
- //@Test
- void testFile() throws IOException {
- RecordLister viewer = new RecordLister();
- viewer.setFile(new File("test-data/spreadsheet/testEXCEL_95.xls").getAbsolutePath());
- viewer.run();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java b/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java
deleted file mode 100644
index 058e1eda09..0000000000
--- a/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.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.hssf.eventmodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.eventusermodel.AbortableHSSFListener;
-import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
-import org.apache.poi.hssf.eventusermodel.HSSFRequest;
-import org.apache.poi.hssf.record.BOFRecord;
-import org.apache.poi.hssf.record.EOFRecord;
-import org.apache.poi.hssf.record.Record;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link AbortableHSSFListener}
- */
-final class TestAbortableListener {
-
- private POIFSFileSystem openSample() throws IOException {
- ByteArrayInputStream is = new ByteArrayInputStream(HSSFITestDataProvider.instance
- .getTestDataFileContent("SimpleWithColours.xls"));
- return new POIFSFileSystem(is);
- }
-
- @Test
- void testAbortingBasics() throws Exception {
- AbortableCountingListener l = new AbortableCountingListener(1000);
-
- HSSFRequest req = new HSSFRequest();
- req.addListenerForAllRecords(l);
-
- HSSFEventFactory f = new HSSFEventFactory();
-
- assertEquals(0, l.countSeen);
- assertNull(l.lastRecordSeen);
-
- POIFSFileSystem fs = openSample();
- short res = f.abortableProcessWorkbookEvents(req, fs);
-
- assertEquals(0, res);
- assertEquals(175, l.countSeen);
- assertEquals(EOFRecord.sid, l.lastRecordSeen.getSid());
- }
-
- @Test
- void testAbortStops() throws Exception {
- AbortableCountingListener l = new AbortableCountingListener(1);
-
- HSSFRequest req = new HSSFRequest();
- req.addListenerForAllRecords(l);
-
- HSSFEventFactory f = new HSSFEventFactory();
-
- assertEquals(0, l.countSeen);
- assertNull(l.lastRecordSeen);
-
- POIFSFileSystem fs = openSample();
- short res = f.abortableProcessWorkbookEvents(req, fs);
-
- assertEquals(1234, res);
- assertEquals(1, l.countSeen);
- assertEquals(BOFRecord.sid, l.lastRecordSeen.getSid());
- }
-
- private static final class AbortableCountingListener extends AbortableHSSFListener {
- private final int abortAfterIndex;
- public int countSeen;
- public Record lastRecordSeen;
-
- public AbortableCountingListener(int abortAfter) {
- abortAfterIndex = abortAfter;
- countSeen = 0;
- lastRecordSeen = null;
- }
- @Override
- public short abortableProcessRecord(org.apache.poi.hssf.record.Record record) {
- countSeen++;
- lastRecordSeen = record;
-
- if (countSeen == abortAfterIndex) {
- return 1234;
- }
- return 0;
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java b/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java
deleted file mode 100644
index 8bb1b6771c..0000000000
--- a/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.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.hssf.eventmodel;
-
-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.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.SequenceInputStream;
-import java.util.Iterator;
-import java.util.stream.Stream;
-
-import org.apache.commons.collections4.IteratorUtils;
-import org.apache.poi.hssf.record.BOFRecord;
-import org.apache.poi.hssf.record.ContinueRecord;
-import org.apache.poi.hssf.record.EOFRecord;
-import org.apache.poi.hssf.record.Record;
-import org.apache.poi.hssf.record.RecordFactory;
-import org.apache.poi.hssf.record.StandardRecord;
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.apache.poi.hssf.record.UnknownRecord;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-/**
- * enclosing_type describe the purpose here
- */
-final class TestEventRecordFactory {
- private static final byte[][] CONTINUE_DATA = {
- // an unknown record with 0 length
- {0, -1, 0, 0,},
- // a continuation record with 3 bytes of data
- {0x3C, 0, 3, 0, 1, 2, 3,},
- // one more continuation record with 1 byte of data
- {0x3C, 0, 1, 0, 4}
- };
-
- /**
- * tests that the records can be processed and properly return values.
- */
- @Test
- void testProcessRecords() {
- final boolean[] wascalled = { false }; // hack to pass boolean by ref into inner class
-
- ERFListener listener = rec -> {
- wascalled[0] = true;
- assertEquals(rec.getSid(), BOFRecord.sid, "must be BOFRecord got SID=" + rec.getSid());
- return true;
- };
- EventRecordFactory factory = new EventRecordFactory(listener, new short[] {BOFRecord.sid});
-
- BOFRecord bof = new BOFRecord();
- bof.setBuild((short)0);
- bof.setBuildYear((short)1999);
- bof.setRequiredVersion(123);
- bof.setType(BOFRecord.TYPE_WORKBOOK);
- bof.setVersion((short)0x06);
- bof.setHistoryBitMask(BOFRecord.HISTORY_MASK);
-
- EOFRecord eof = EOFRecord.instance;
- byte[] bytes = new byte[bof.getRecordSize() + eof.getRecordSize()];
- int offset = 0;
- offset = bof.serialize(offset,bytes);
- eof.serialize(offset,bytes);
-
- factory.processRecords(new ByteArrayInputStream(bytes));
- assertTrue(wascalled[0], "The record listener must be called");
- }
-
-
- /**
- * tests that the create record function returns a properly
- * constructed record in the simple case.
- */
- @Test
- void testCreateRecord() {
- BOFRecord bof = new BOFRecord();
- bof.setBuild((short)0);
- bof.setBuildYear((short)1999);
- bof.setRequiredVersion(123);
- bof.setType(BOFRecord.TYPE_WORKBOOK);
- bof.setVersion((short)0x06);
- bof.setHistoryBitMask(BOFRecord.HISTORY_MASK);
-
- byte[] bytes = bof.serialize();
-
- Record[] records = RecordFactory.createRecord(TestcaseRecordInputStream.create(bytes));
-
- assertEquals(1, records.length, "record.length must be 1, was =" + records.length);
-
- byte[] rec1 = bof.serialize();
- byte[] rec2 = records[0].serialize();
- assertArrayEquals(rec1, rec2);
- }
-
- /*
- * tests that the create record function returns a properly
- * constructed record in the case of a continued record.
- * TODO - need a real world example to put in a unit test
- */
- // @NotImplemented
- // @Test
- // @Disabled
- // void testCreateContinuedRecord() {
- // }
-
-
- /**
- * TEST NAME: Test Creating ContinueRecords After Unknown Records From An InputStream
- * OBJECTIVE: Test that the RecordFactory given an InputStream
- * constructs the expected records.
- * SUCCESS: Record factory creates the expected records.
- * FAILURE: The wrong records are created or contain the wrong values
- *
- */
- @Test
- void testContinuedUnknownRecord() throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- for (byte[] b : CONTINUE_DATA) {
- bos.write(b);
- }
- continueHelper(new ByteArrayInputStream(bos.toByteArray()));
- }
-
- @Test
- @Disabled("same as testContinuedUnknownRecord but with SequenceInputStream which causes the available() bug 59893")
- void bug59893() {
- Iterator iter = Stream.of(CONTINUE_DATA).map(ByteArrayInputStream::new).iterator();
- SequenceInputStream sis = new SequenceInputStream(IteratorUtils.asEnumeration(iter));
- continueHelper(sis);
- }
-
- private void continueHelper(InputStream data) {
- Iterator> expectedType =
- Stream.of(UnknownRecord.class, ContinueRecord.class, ContinueRecord.class).iterator();
- Iterator expectedData = Stream.of(CONTINUE_DATA).iterator();
-
- ERFListener listener = rec -> {
- assertEquals(expectedType.next(), rec.getClass());
- assertArrayEquals(expectedData.next(), rec.serialize());
- return true;
- };
- EventRecordFactory factory = new EventRecordFactory(listener, new short[] {-256, 0x3C});
- factory.processRecords(data);
- assertFalse(expectedData.hasNext(), "left over input data");
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java
deleted file mode 100644
index fcd9d81dbc..0000000000
--- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.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.hssf.eventusermodel;
-
-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 java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener;
-import org.apache.poi.hssf.model.HSSFFormulaParser;
-import org.apache.poi.hssf.model.InternalWorkbook;
-import org.apache.poi.hssf.record.FormulaRecord;
-import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.formula.ptg.Ref3DPtg;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link EventWorkbookBuilder}
- */
-final class TestEventWorkbookBuilder {
- private final List fRecs = new ArrayList<>();
- private SheetRecordCollectingListener listener;
-
- @BeforeEach
- void setUp() throws IOException {
- HSSFRequest req = new HSSFRequest();
- fRecs.clear();
- listener = new SheetRecordCollectingListener(this::addFormulaRecord);
- req.addListenerForAllRecords(listener);
-
- HSSFEventFactory factory = new HSSFEventFactory();
- try (InputStream is = HSSFTestDataSamples.openSampleFileStream("3dFormulas.xls");
- POIFSFileSystem fs = new POIFSFileSystem(is)) {
- factory.processWorkbookEvents(req, fs);
- }
- }
-
- private void addFormulaRecord(org.apache.poi.hssf.record.Record r) {
- if (r instanceof FormulaRecord) {
- fRecs.add((FormulaRecord)r);
- }
- }
-
- @Test
- void testBasics() {
- assertNotNull(listener.getSSTRecord());
- assertNotNull(listener.getBoundSheetRecords());
- assertNotNull(listener.getExternSheetRecords());
- }
-
- @Test
- void testGetStubWorkbooks() {
- assertNotNull(listener.getStubWorkbook());
- assertNotNull(listener.getStubHSSFWorkbook());
- }
-
- @Test
- void testContents() {
- assertEquals(2, listener.getSSTRecord().getNumStrings());
- assertEquals(3, listener.getBoundSheetRecords().length);
- assertEquals(1, listener.getExternSheetRecords().length);
-
- assertEquals(3, listener.getStubWorkbook().getNumSheets());
-
- InternalWorkbook ref = listener.getStubWorkbook();
- assertEquals("Sh3", ref.findSheetFirstNameFromExternSheet(0));
- assertEquals("Sheet1", ref.findSheetFirstNameFromExternSheet(1));
- assertEquals("S2", ref.findSheetFirstNameFromExternSheet(2));
- }
-
- @Test
- void testFormulas() {
-
- // Check our formula records
- assertEquals(6, fRecs.size());
-
- InternalWorkbook stubWB = listener.getStubWorkbook();
- assertNotNull(stubWB);
- HSSFWorkbook stubHSSF = listener.getStubHSSFWorkbook();
- assertNotNull(stubHSSF);
-
- // Check these stubs have the right stuff on them
- assertEquals("Sheet1", stubWB.getSheetName(0));
- assertEquals("Sheet1", stubHSSF.getSheetName(0));
- assertEquals("S2", stubWB.getSheetName(1));
- assertEquals("S2", stubHSSF.getSheetName(1));
- assertEquals("Sh3", stubWB.getSheetName(2));
- assertEquals("Sh3", stubHSSF.getSheetName(2));
-
- // Check we can get the formula without breaking
- for (FormulaRecord fRec : fRecs) {
- HSSFFormulaParser.toFormulaString(stubHSSF, fRec.getParsedExpression());
- }
-
- // Peer into just one formula, and check that
- // all the ptgs give back the right things
- Ptg[] ptgs = fRecs.get(0).getParsedExpression();
- assertEquals(1, ptgs.length);
- assertTrue(ptgs[0] instanceof Ref3DPtg);
-
- Ref3DPtg ptg = (Ref3DPtg)ptgs[0];
- HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(stubHSSF);
- assertEquals("Sheet1!A1", ptg.toFormulaString(book));
-
-
- // Now check we get the right formula back for
- // a few sample ones
- FormulaRecord fr;
-
- // Sheet 1 A2 is on same sheet
- fr = fRecs.get(0);
- assertEquals(1, fr.getRow());
- assertEquals(0, fr.getColumn());
- assertEquals("Sheet1!A1", HSSFFormulaParser.toFormulaString(stubHSSF, fr.getParsedExpression()));
-
- // Sheet 1 A5 is to another sheet
- fr = fRecs.get(3);
- assertEquals(4, fr.getRow());
- assertEquals(0, fr.getColumn());
- assertEquals("'S2'!A1", HSSFFormulaParser.toFormulaString(stubHSSF, fr.getParsedExpression()));
-
- // Sheet 1 A7 is to another sheet, range
- fr = fRecs.get(5);
- assertEquals(6, fr.getRow());
- assertEquals(0, fr.getColumn());
- assertEquals("SUM(Sh3!A1:A4)", HSSFFormulaParser.toFormulaString(stubHSSF, fr.getParsedExpression()));
-
-
- // Now, load via Usermodel and re-check
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("3dFormulas.xls");
- assertEquals("Sheet1!A1", wb.getSheetAt(0).getRow(1).getCell(0).getCellFormula());
- assertEquals("SUM(Sh3!A1:A4)", wb.getSheetAt(0).getRow(6).getCell(0).getCellFormula());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java
deleted file mode 100644
index 74ac31845d..0000000000
--- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.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.hssf.eventusermodel;
-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.File;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.CellValueRecordInterface;
-import org.apache.poi.hssf.record.FormulaRecord;
-import org.apache.poi.hssf.record.NumberRecord;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for FormatTrackingHSSFListener
- */
-final class TestFormatTrackingHSSFListener {
- private FormatTrackingHSSFListener listener;
- private MockHSSFListener mockListen;
-
- private void processFile(String filename) throws Exception {
- HSSFRequest req = new HSSFRequest();
- mockListen = new MockHSSFListener();
- listener = new FormatTrackingHSSFListener(mockListen);
- req.addListenerForAllRecords(listener);
-
- File file = HSSFTestDataSamples.getSampleFile(filename);
- HSSFEventFactory factory = new HSSFEventFactory();
- POIFSFileSystem fs = new POIFSFileSystem(file);
- factory.processWorkbookEvents(req, fs);
- fs.close();
- }
-
- @Test
- void testFormats() throws Exception {
- processFile("MissingBits.xls");
-
- assertEquals("_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)", listener.getFormatString(41));
- assertEquals("_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)", listener.getFormatString(42));
- assertEquals("_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)", listener.getFormatString(43));
- assertEquals("_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)", listener.getFormatString(44));
- }
-
- /**
- * Ensure that all number and formula records can be
- * turned into strings without problems.
- * For now, we're just looking to get text back, no
- * exceptions thrown, but in future we might also
- * want to check the exact strings!
- */
- @Test
- void testTurnToString() throws Exception {
- String[] files = new String[] {
- "45365.xls", "45365-2.xls", "MissingBits.xls"
- };
- for (String file : files) {
- processFile(file);
-
- // Check we found our formats
- assertTrue(listener.getNumberOfCustomFormats() > 5);
- assertTrue(listener.getNumberOfExtendedFormats() > 5);
-
- // Now check we can turn all the numeric
- // cells into strings without error
- for(org.apache.poi.hssf.record.Record r : mockListen._records) {
- CellValueRecordInterface cvr = null;
-
- if(r instanceof NumberRecord) {
- cvr = (CellValueRecordInterface)r;
- }
- if(r instanceof FormulaRecord) {
- cvr = (CellValueRecordInterface)r;
- }
-
- if(cvr != null) {
- // Should always give us a string
- String s = listener.formatNumberDateCell(cvr);
- assertNotNull(s);
- assertTrue(s.length() > 0);
- }
- }
-
- // TODO - test some specific format strings
- }
- }
-
- private static final class MockHSSFListener implements HSSFListener {
- public MockHSSFListener() {}
- private final List _records = new ArrayList<>();
-
- @Override
- public void processRecord(org.apache.poi.hssf.record.Record record) {
- _records.add(record);
- }
- }
-}
\ No newline at end of file
diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java
deleted file mode 100644
index 24fba3e492..0000000000
--- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.eventusermodel;
-
-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.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.BoundSheetRecord;
-import org.apache.poi.hssf.record.ContinueRecord;
-import org.apache.poi.hssf.record.DVALRecord;
-import org.apache.poi.hssf.record.DVRecord;
-import org.apache.poi.hssf.record.EOFRecord;
-import org.apache.poi.hssf.record.FeatHdrRecord;
-import org.apache.poi.hssf.record.NumberRecord;
-import org.apache.poi.hssf.record.SelectionRecord;
-import org.apache.poi.hssf.record.WindowTwoRecord;
-import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.junit.jupiter.api.Test;
-
-/**
- * Testing for {@link HSSFEventFactory}
- */
-final class TestHSSFEventFactory {
- private final List records = new ArrayList<>();
-
- private void openSample(String sampleFileName) throws IOException {
- records.clear();
- HSSFRequest req = new HSSFRequest();
- req.addListenerForAllRecords(records::add);
- try (InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName);
- POIFSFileSystem fs = new POIFSFileSystem(is)) {
- HSSFEventFactory factory = new HSSFEventFactory();
- factory.processWorkbookEvents(req, fs);
- }
- }
-
- @Test
- void testWithMissingRecords() throws Exception {
-
- openSample("SimpleWithSkip.xls");
-
- int numRec = records.size();
-
- // Check we got the records
- assertTrue( numRec > 100 );
-
- // Check that the last few records are as we expect
- // (Makes sure we don't accidently skip the end ones)
- Class>[] exp = { WindowTwoRecord.class, SelectionRecord.class, EOFRecord.class };
- Class>[] act = records.subList(numRec - 3, numRec).stream().map(Object::getClass).toArray(Class[]::new);
- assertArrayEquals(exp, act);
- }
-
- @Test
- void testWithCrazyContinueRecords() throws Exception {
- // Some files have crazy ordering of their continue records
- // Check that we don't break on them (bug #42844)
-
- openSample("ContinueRecordProblem.xls");
-
- int numRec = records.size();
- // Check we got the records
- assertTrue( numRec > 100 );
-
- // And none of them are continue ones
- assertFalse(records.stream().anyMatch(r -> r instanceof ContinueRecord));
-
- // Check that the last few records are as we expect
- // (Makes sure we don't accidentally skip the end ones)
- Class>[] exp = { DVALRecord.class, DVRecord.class, FeatHdrRecord.class, EOFRecord.class };
- Class>[] act = records.subList(numRec-4, numRec).stream().map(Object::getClass).toArray(Class[]::new);
- assertArrayEquals(exp, act);
- }
-
- /**
- * Unknown records can be continued.
- * Check that HSSFEventFactory doesn't break on them.
- * (the test file was provided in a reopen of bug #42844)
- */
- @Test
- @SuppressWarnings("java:S2699")
- void testUnknownContinueRecords() throws Exception {
- openSample("42844.xls");
- }
-
- @Test
- @SuppressWarnings("java:S2699")
- void testWithDifferentWorkbookName() throws Exception {
- openSample("BOOK_in_capitals.xls");
- openSample("WORKBOOK_in_capitals.xls");
- }
-
- @Test
- @SuppressWarnings("java:S2699")
- void testWithPasswordProtectedWorkbooksNoPass() {
- // Without a password, can't be read
- assertThrows(EncryptedDocumentException.class, () -> openSample("xor-encryption-abc.xls"));
- }
-
- @Test
- void testWithPasswordProtectedWorkbooks() throws Exception {
- // With the password, is properly processed
- Biff8EncryptionKey.setCurrentUserPassword("abc");
- try {
- openSample("xor-encryption-abc.xls");
-
- // Check we got the sheet and the contents
- assertTrue(records.size() > 50);
-
- // Has one sheet, with values 1,2,3 in column A rows 1-3
- boolean hasSheet = false, hasA1 = false, hasA2 = false, hasA3 = false;
- for (org.apache.poi.hssf.record.Record r : records) {
- if (r instanceof BoundSheetRecord) {
- BoundSheetRecord bsr = (BoundSheetRecord) r;
- assertEquals("Sheet1", bsr.getSheetname());
- hasSheet = true;
- }
- if (r instanceof NumberRecord) {
- NumberRecord nr = (NumberRecord) r;
- if (nr.getColumn() == 0 && nr.getRow() == 0) {
- assertEquals(1, (int) nr.getValue());
- hasA1 = true;
- }
- if (nr.getColumn() == 0 && nr.getRow() == 1) {
- assertEquals(2, (int) nr.getValue());
- hasA2 = true;
- }
- if (nr.getColumn() == 0 && nr.getRow() == 2) {
- assertEquals(3, (int) nr.getValue());
- hasA3 = true;
- }
- }
- }
-
- assertTrue(hasSheet, "Sheet record not found");
- assertTrue(hasA1, "Numeric record for A1 not found");
- assertTrue(hasA2, "Numeric record for A2 not found");
- assertTrue(hasA3, "Numeric record for A3 not found");
- } finally {
- Biff8EncryptionKey.setCurrentUserPassword(null);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java
deleted file mode 100644
index 852f07e9de..0000000000
--- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.eventusermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.function.Predicate;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
-import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
-import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingRowDummyRecord;
-import org.apache.poi.hssf.record.BlankRecord;
-import org.apache.poi.hssf.record.CellValueRecordInterface;
-import org.apache.poi.hssf.record.DimensionsRecord;
-import org.apache.poi.hssf.record.LabelSSTRecord;
-import org.apache.poi.hssf.record.MulBlankRecord;
-import org.apache.poi.hssf.record.NumberRecord;
-import org.apache.poi.hssf.record.RowRecord;
-import org.apache.poi.hssf.record.SharedFormulaRecord;
-import org.apache.poi.hssf.record.WindowTwoRecord;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for MissingRecordAwareHSSFListener
- */
-final class TestMissingRecordAwareHSSFListener {
-
- private final List _records = new ArrayList<>();
-
- private void readRecords(String sampleFileName) throws IOException {
- _records.clear();
- HSSFRequest req = new HSSFRequest();
- req.addListenerForAllRecords(new MissingRecordAwareHSSFListener(_records::add));
-
- HSSFEventFactory factory = new HSSFEventFactory();
- try (InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName);
- POIFSFileSystem fs = new POIFSFileSystem(is)) {
- factory.processWorkbookEvents(req, fs);
- }
-
- assertTrue(_records.size() > 100);
- }
-
- @Test
- void testMissingRowRecords() throws IOException {
- readRecords("MissingBits.xls");
-
- // We have rows 0, 1, 2, 20 and 21
- int row0 = lastIndexOf(r -> r instanceof RowRecord && ((RowRecord)r).getRowNumber() == 0);
- assertTrue(row0 > -1);
-
- // Records: row 0: column 1, 2), then missing rows, rows 20,21,22 each 1 column
- String exp1 =
- "0:rr,1:rr,2:rr,3:mr,4:mr,5:mr,6:mr,7:mr,8:mr,9:mr,10:mr,11:mr,12:mr,13:mr,14:mr," +
- "15:mr,16:mr,17:mr,18:mr,19:mr,20:rr,21:rr,22:rr";
- String act1 = digest(row0, 22);
- assertEquals(exp1, act1);
-
-
- // Find the cell at 0,0
- int cell00 = lastIndexOf(r -> r instanceof LabelSSTRecord && ((LabelSSTRecord)r).getRow() == 0 && ((LabelSSTRecord)r).getColumn() == 0);
-
- String exp2 =
- "0:ls0lc0," +
- "1:nr0/11mc1mc2nr3/23lc3," +
- "2:nr0/45mc1mc2mc3mc4nr5/22lc5," +
- "3:lc,4:lc,5:lc,6:lc,7:lc,8:lc,9:lc,10:lc,11:lc,12:lc,13:lc,14:lc,15:lc,16:lc,17:lc,18:lc,19:lc," +
- "20:nr0/50nr1/51nr2/52nr3/53nr4/54lc4," +
- "21:ls0ls1mc2nr3/12mc4nr5/23nr6/42lc6," +
- "22:ls0mc1mc2ls3ls4mc5mc6mc7mc8mc9mc10ls11lc11";
- String act2 = digest(cell00, 57);
- assertEquals(exp2, act2);
- }
-
- // Make sure we don't put in any extra new lines that aren't already there
- @Test
- void testNoExtraNewLines() throws IOException {
- // Load a different file
- // This file has has something in lines 1-33
- readRecords("MRExtraLines.xls");
-
- int rowCount=0;
- for (org.apache.poi.hssf.record.Record rec : _records) {
- if (rec instanceof LastCellOfRowDummyRecord) {
- LastCellOfRowDummyRecord eor = (LastCellOfRowDummyRecord) rec;
- assertEquals(rowCount, eor.getRow());
- rowCount++;
- }
- }
- // Check we got the 33 rows
- assertEquals(33, rowCount);
- }
-
- /**
- * Make sure that the presence of shared formulas does not cause extra end-of-row records.
- */
- @Test
- void testEndOfRow_bug45672() throws IOException {
- readRecords("ex45672.xls");
- assertEquals(1, matches(r -> r instanceof SharedFormulaRecord));
- assertEquals(1, matches(r -> r instanceof LastCellOfRowDummyRecord));
- }
-
- /**
- * MulBlank records hold multiple blank cells.
- * Check that we don't have any MulBlankRecords, but do have lots of BlankRecords
- */
- @Test
- void testMulBlankHandling() throws IOException {
- readRecords("45672.xls");
- assertEquals(20, matches(r -> r instanceof BlankRecord));
- assertEquals(2, matches(r -> r instanceof LastCellOfRowDummyRecord));
- assertEquals(0, matches(r -> r instanceof MulBlankRecord));
- }
-
- @Test
- void testStringRecordHandling() throws IOException {
- readRecords("53588.xls");
- assertEquals(1, matches(r -> r instanceof MissingCellDummyRecord));
- assertEquals(1, matches(r -> r instanceof LastCellOfRowDummyRecord));
- }
-
- @Test
- void testFormulasWithStringResultsHandling() throws IOException {
- readRecords("53433.xls");
-
- String exp =
- "dr0:mr,1:mr,2:mr,3:rr,4:rr,5:rr,6:rr,7:rr,8:rr,9:rr,10:mr,11:mr,12:mr,13:mr,14:mr,15:rr,16:rr,17:mr,18:rr," +
- "0:lc,1:lc,2:lc,3:mc0ls1ls2ls3ls4lc4,4:mc0ls1cv2urnr3/12cv4urlc4," +
- "5:mc0cv1urnr2/23nr3/23cv4urlc4,6:mc0mc1nr2/25nr3/45nr4/32815lc4," +
- "7:mc0ls1cv2cv3urcv4lc4,8:mc0mc1mc2mc3cv4lc4,9:mc0mc1mc2ls3lc3," +
- "10:lc,11:lc,12:lc,13:lc,14:lc,15:mc0ls1lc1,16:mc0mc1mc2ls3lc3," +
- "17:lc,18:mc0mc1mc2mc3ls4lc4wr";
- String act = digest(95, 89);
- assertEquals(exp, act);
- }
-
- private int lastIndexOf(Predicate pre) {
- int found = -1;
- int i = 0;
- for (org.apache.poi.hssf.record.Record r : _records) {
- if (pre.test(r)) {
- found = i;
- }
- i++;
- }
- return found;
- }
-
- private String digest(int start, int len) {
- StringBuilder sb = new StringBuilder(len*10);
- int lastRow = -1;
- for (org.apache.poi.hssf.record.Record r : _records.subList(start, start+len+1)) {
- String dig = null;
- int row = -1;
- if (r instanceof RowRecord) {
- RowRecord rr = (RowRecord)r;
- row = rr.getRowNumber();
- dig = "rr";
- } else if (r instanceof MissingRowDummyRecord) {
- MissingRowDummyRecord mr = (MissingRowDummyRecord)r;
- row = mr.getRowNumber();
- dig = "mr";
- } else if (r instanceof MissingCellDummyRecord) {
- MissingCellDummyRecord mc = (MissingCellDummyRecord)r;
- row = mc.getRow();
- dig = "mc" + mc.getColumn();
- } else if (r instanceof LastCellOfRowDummyRecord) {
- LastCellOfRowDummyRecord lc = (LastCellOfRowDummyRecord)r;
- row = lc.getRow();
- dig = "lc" + (lc.getLastColumnNumber() > -1 ? lc.getLastColumnNumber() : "");
- } else if (r instanceof NumberRecord) {
- NumberRecord nr = (NumberRecord)r;
- row = nr.getRow();
- dig = "nr" + nr.getColumn() + "/" + (int)nr.getValue();
- } else if (r instanceof LabelSSTRecord) {
- LabelSSTRecord ls = (LabelSSTRecord) r;
- row = ls.getRow();
- dig = "ls" + ls.getColumn();
- } else if (r instanceof WindowTwoRecord) {
- dig = "wr";
- } else if (r instanceof DimensionsRecord) {
- dig = "dr";
- } else if (r instanceof CellValueRecordInterface) {
- CellValueRecordInterface cv = (CellValueRecordInterface) r;
- row = cv.getRow();
- dig = "cv" + cv.getColumn();
- } else {
- // unhandled record
- dig = "ur";
- }
- if (lastRow != row && row > -1) {
- sb.append((lastRow > -1 ? "," : "") + row + ":");
- lastRow = row;
- }
- sb.append(dig);
- }
- return sb.toString();
- }
-
- private long matches(Predicate r) {
- return _records.stream().filter(r).count();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java b/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java
deleted file mode 100644
index 7a5ceef5f1..0000000000
--- a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java
+++ /dev/null
@@ -1,385 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.extractor;
-
-import static org.apache.poi.POITestCase.assertContains;
-import static org.apache.poi.POITestCase.assertStartsWith;
-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.File;
-import java.io.IOException;
-import java.util.Locale;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.poifs.filesystem.DirectoryNode;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- *
- */
-final class TestExcelExtractor {
- private static ExcelExtractor createExtractor(String sampleFileName) throws IOException {
- File file = HSSFTestDataSamples.getSampleFile(sampleFileName);
- POIFSFileSystem fs = new POIFSFileSystem(file);
- return new ExcelExtractor(fs);
- }
-
- @Test
- void testSimple() throws IOException {
- try (ExcelExtractor extractor = createExtractor("Simple.xls")) {
- assertEquals("Sheet1\nreplaceMe\nSheet2\nSheet3\n", extractor.getText());
-
- // Now turn off sheet names
- extractor.setIncludeSheetNames(false);
- assertEquals("replaceMe\n", extractor.getText());
- }
- }
-
- @Test
- void testNumericFormula() throws IOException {
- try (ExcelExtractor extractor = createExtractor("sumifformula.xls")) {
- assertEquals(
- "Sheet1\n" +
- "1000\t1\t5\n" +
- "2000\t2\n" +
- "3000\t3\n" +
- "4000\t4\n" +
- "5000\t5\n" +
- "Sheet2\nSheet3\n",
- extractor.getText()
- );
-
- extractor.setFormulasNotResults(true);
-
- assertEquals(
- "Sheet1\n" +
- "1000\t1\tSUMIF(A1:A5,\">4000\",B1:B5)\n" +
- "2000\t2\n" +
- "3000\t3\n" +
- "4000\t4\n" +
- "5000\t5\n" +
- "Sheet2\nSheet3\n",
- extractor.getText()
- );
- }
- }
-
- @Test
- void testWithContinueRecords() throws IOException {
- try (ExcelExtractor extractor = createExtractor("StringContinueRecords.xls")) {
- // Has masses of text
- // Until we fixed bug #41064, this would've
- // failed by now
- assertTrue(extractor.getText().length() > 40960);
- }
- }
-
- @Test
- void testStringConcat() throws IOException {
- try (ExcelExtractor extractor = createExtractor("SimpleWithFormula.xls")) {
- // Comes out as NaN if treated as a number
- // And as XYZ if treated as a string
- assertEquals("Sheet1\nreplaceme\nreplaceme\nreplacemereplaceme\nSheet2\nSheet3\n", extractor.getText());
-
- extractor.setFormulasNotResults(true);
-
- assertEquals("Sheet1\nreplaceme\nreplaceme\nCONCATENATE(A1,A2)\nSheet2\nSheet3\n", extractor.getText());
- }
- }
-
- @Test
- void testStringFormula() throws IOException {
- try (ExcelExtractor extractor = createExtractor("StringFormulas.xls")) {
- // Comes out as NaN if treated as a number
- // And as XYZ if treated as a string
- assertEquals("Sheet1\nXYZ\nSheet2\nSheet3\n", extractor.getText());
-
- extractor.setFormulasNotResults(true);
-
- assertEquals("Sheet1\nUPPER(\"xyz\")\nSheet2\nSheet3\n", extractor.getText());
- }
- }
-
-
- @Test
- void testEventExtractor() throws Exception {
- // First up, a simple file with string
- // based formulas in it
- try (EventBasedExcelExtractor extractor1 = new EventBasedExcelExtractor(
- new POIFSFileSystem(
- HSSFTestDataSamples.openSampleFileStream("SimpleWithFormula.xls")
- )
- )) {
- extractor1.setIncludeSheetNames(true);
-
- String text = extractor1.getText();
- assertEquals("Sheet1\nreplaceme\nreplaceme\nreplacemereplaceme\nSheet2\nSheet3\n", text);
-
- extractor1.setIncludeSheetNames(false);
- extractor1.setFormulasNotResults(true);
-
- text = extractor1.getText();
- assertEquals("replaceme\nreplaceme\nCONCATENATE(A1,A2)\n", text);
- }
-
- // Now, a slightly longer file with numeric formulas
- try (EventBasedExcelExtractor extractor2 = new EventBasedExcelExtractor(
- new POIFSFileSystem(
- HSSFTestDataSamples.openSampleFileStream("sumifformula.xls")
- )
- )) {
-
- extractor2.setIncludeSheetNames(false);
- extractor2.setFormulasNotResults(true);
-
- String text = extractor2.getText();
- assertEquals(
- "1000\t1\tSUMIF(A1:A5,\">4000\",B1:B5)\n" +
- "2000\t2\n" +
- "3000\t3\n" +
- "4000\t4\n" +
- "5000\t5\n",
- text
- );
- }
- }
-
- @Test
- void testWithComments() throws IOException {
- try (ExcelExtractor extractor = createExtractor("SimpleWithComments.xls")) {
- extractor.setIncludeSheetNames(false);
-
- // Check without comments
- assertEquals(
- "1\tone\n" +
- "2\ttwo\n" +
- "3\tthree\n",
- extractor.getText()
- );
-
- // Now with
- extractor.setIncludeCellComments(true);
- assertEquals(
- "1\tone Comment by Yegor Kozlov: Yegor Kozlov: first cell\n" +
- "2\ttwo Comment by Yegor Kozlov: Yegor Kozlov: second cell\n" +
- "3\tthree Comment by Yegor Kozlov: Yegor Kozlov: third cell\n",
- extractor.getText()
- );
- }
- }
-
- @Test
- void testWithBlank() throws IOException {
- try (ExcelExtractor extractor = createExtractor("MissingBits.xls")) {
- String def = extractor.getText();
- extractor.setIncludeBlankCells(true);
- String padded = extractor.getText();
-
- assertStartsWith(def,
- "Sheet1\n" +
- "&[TAB]\t\n" +
- "Hello\n" +
- "11\t23\n"
- );
-
- assertStartsWith(padded,
- "Sheet1\n" +
- "&[TAB]\t\n" +
- "Hello\n" +
- "11\t\t\t23\n"
- );
- }
- }
-
- @Test
- void testFormatting() throws Exception {
- Locale userLocale = LocaleUtil.getUserLocale();
- LocaleUtil.setUserLocale(Locale.ROOT);
- try (ExcelExtractor extractor = createExtractor("Formatting.xls")) {
- extractor.setIncludeBlankCells(false);
- extractor.setIncludeSheetNames(false);
- String text = extractor.getText();
-
- // Note - not all the formats in the file
- // actually quite match what they claim to
- // be, as some are auto-local builtins...
-
- assertStartsWith(text, "Dates, all 24th November 2006\n");
- assertContains(text, "yyyy/mm/dd\t2006/11/24\n");
- assertContains(text, "yyyy-mm-dd\t2006-11-24\n");
- assertContains(text, "dd-mm-yy\t24-11-06\n");
-
- assertContains(text, "nn.nn\t10.52\n");
- assertContains(text, "nn.nnn\t10.520\n");
- assertContains(text, "\u00a3nn.nn\t\u00a310.52\n");
- } finally {
- LocaleUtil.setUserLocale(userLocale);
- }
- }
-
- /**
- * Embeded in a non-excel file
- */
- @Test
- void testWithEmbeded() throws Exception {
- POIFSFileSystem fs = null;
-
- HSSFWorkbook wbA = null, wbB = null;
- ExcelExtractor exA = null, exB = null;
-
- try {
- fs = new POIFSFileSystem(POIDataSamples.getDocumentInstance().getFile("word_with_embeded.doc"));
-
- DirectoryNode objPool = (DirectoryNode) fs.getRoot().getEntry("ObjectPool");
- DirectoryNode dirA = (DirectoryNode) objPool.getEntry("_1269427460");
- DirectoryNode dirB = (DirectoryNode) objPool.getEntry("_1269427461");
-
- wbA = new HSSFWorkbook(dirA, fs, true);
- exA = new ExcelExtractor(wbA);
- wbB = new HSSFWorkbook(dirB, fs, true);
- exB = new ExcelExtractor(wbB);
-
- assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", exA.getText());
- assertEquals("Sample Excel", exA.getSummaryInformation().getTitle());
- assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", exB.getText());
- assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle());
- } finally {
- if (exB != null) exB.close();
- if (wbB != null) wbB.close();
- if (exA != null) exA.close();
- if (wbA != null) wbA.close();
- if (fs != null) fs.close();
- }
- }
-
- /**
- * Excel embeded in excel
- */
- @Test
- void testWithEmbededInOwn() throws Exception {
- POIDataSamples ssSamples = POIDataSamples.getSpreadSheetInstance();
- POIFSFileSystem fs = null;
- HSSFWorkbook wbA = null, wbB = null;
- ExcelExtractor exA = null, exB = null, ex = null;
-
- try {
- fs = new POIFSFileSystem(ssSamples.getFile("excel_with_embeded.xls"));
-
- DirectoryNode dirA = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B5");
- DirectoryNode dirB = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B4");
-
- wbA = new HSSFWorkbook(dirA, fs, true);
- wbB = new HSSFWorkbook(dirB, fs, true);
-
- exA = new ExcelExtractor(wbA);
- exB = new ExcelExtractor(wbB);
- assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", exA.getText());
- assertEquals("Sample Excel", exA.getSummaryInformation().getTitle());
-
- assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", exB.getText());
- assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle());
-
- // And the base file too
- ex = new ExcelExtractor(fs);
- assertEquals("Sheet1\nI have lots of embeded files in me\nSheet2\nSheet3\n", ex.getText());
- assertEquals("Excel With Embeded", ex.getSummaryInformation().getTitle());
- } finally {
- if (ex != null) ex.close();
- if (exB != null) exB.close();
- if (exA != null) exA.close();
- if (wbB != null) wbB.close();
- if (wbA != null) wbA.close();
- if (fs != null) fs.close();
- }
- }
-
- /**
- * Test that we get text from headers and footers
- */
- @Test
- void test45538() throws IOException {
- String[] files = {
- "45538_classic_Footer.xls", "45538_form_Footer.xls",
- "45538_classic_Header.xls", "45538_form_Header.xls"
- };
- for (String file : files) {
- try (ExcelExtractor extractor = createExtractor(file)) {
- String text = extractor.getText();
- assertContains(file, text, "testdoc");
- assertContains(file, text, "test phrase");
- }
- }
- }
-
- @Test
- void testPassword() throws IOException {
- Biff8EncryptionKey.setCurrentUserPassword("password");
- try (ExcelExtractor extractor = createExtractor("password.xls")) {
- String text = extractor.getText();
- assertContains(text, "ZIP");
- } finally {
- Biff8EncryptionKey.setCurrentUserPassword(null);
-
- }
- }
-
- @Test
- void testNullPointerException() throws IOException {
- try (ExcelExtractor extractor = createExtractor("ar.org.apsme.www_Form%20Inscripcion%20Curso%20NO%20Socios.xls")) {
- assertNotNull(extractor);
- assertNotNull(extractor.getText());
- }
- }
-
- @Test
- void test61045() throws IOException {
- //bug 61045. File is govdocs1 626534
- try (ExcelExtractor extractor = createExtractor("61045_govdocs1_626534.xls")) {
- String txt = extractor.getText();
- assertContains(txt, "NONBUSINESS");
- }
- }
-
- @Test
- void test60405a() throws IOException {
- //bug 61045. File is govdocs1 626534
- try (ExcelExtractor extractor = createExtractor("60405.xls")) {
- String txt = extractor.getText();
- assertContains(txt, "Macro1");
- assertContains(txt, "Macro2");
- }
- }
-
- @Test
- void test60405b() throws IOException {
- //bug 61045. File is govdocs1 626534
- try (ExcelExtractor extractor = createExtractor("60405.xls")) {
- extractor.setFormulasNotResults(true);
- String txt = extractor.getText();
- assertContains(txt, "Macro1");
- assertContains(txt, "Macro2");
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java b/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java
deleted file mode 100644
index 3fb037c93e..0000000000
--- a/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.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.hssf.extractor;
-
-import static org.apache.poi.POITestCase.assertContains;
-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 java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.security.Permission;
-
-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.poifs.filesystem.OfficeXmlFileException;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.util.NullPrintStream;
-import org.apache.poi.util.RecordFormatException;
-import org.junit.jupiter.api.Test;
-
-/**
- * Unit tests for the Excel 5/95 and Excel 4 (and older) text
- * extractor
- */
-final class TestOldExcelExtractor {
- private static OldExcelExtractor createExtractor(String sampleFileName) throws IOException {
- File file = HSSFTestDataSamples.getSampleFile(sampleFileName);
- return new OldExcelExtractor(file);
- }
-
- @Test
- void testSimpleExcel3() throws IOException {
- try (OldExcelExtractor extractor = createExtractor("testEXCEL_3.xls")) {
-
- // Check we can call getText without error
- String text = extractor.getText();
-
- // Check we find a few words we expect in there
- assertContains(text, "Season beginning August");
- assertContains(text, "USDA");
-
- // Check we find a few numbers we expect in there
- assertContains(text, "347");
- assertContains(text, "228");
-
- // Check we find a few string-literal dates in there
- assertContains(text, "1981/82");
-
- // Check the type
- assertEquals(3, extractor.getBiffVersion());
- assertEquals(0x10, extractor.getFileType());
-
- }
- }
-
-
- @Test
- void testSimpleExcel3NoReading() throws IOException {
- try (OldExcelExtractor extractor = createExtractor("testEXCEL_3.xls")) {
- assertNotNull(extractor);
- }
- }
-
- @Test
- void testSimpleExcel4() throws IOException {
- try (OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls")) {
-
- // Check we can call getText without error
- String text = extractor.getText();
-
- // Check we find a few words we expect in there
- assertContains(text, "Size");
- assertContains(text, "Returns");
-
- // Check we find a few numbers we expect in there
- assertContains(text, "11");
- assertContains(text, "784");
-
- // Check the type
- assertEquals(4, extractor.getBiffVersion());
- assertEquals(0x10, extractor.getFileType());
-
- }
- }
-
- @Test
- void testSimpleExcel5() throws IOException {
- for (String ver : new String[] {"5", "95"}) {
- try (OldExcelExtractor extractor = createExtractor("testEXCEL_"+ver+".xls")) {
-
- // Check we can call getText without error
- String text = extractor.getText();
-
- // Check we find a few words we expect in there
- assertContains(text, "Sample Excel");
- assertContains(text, "Written and saved");
-
- // Check we find a few numbers we expect in there
- assertContains(text, "15");
- assertContains(text, "169");
-
- // Check we got the sheet names (new formats only)
- assertContains(text, "Sheet: Feuil3");
-
- // Check the type
- assertEquals(5, extractor.getBiffVersion());
- assertEquals(0x05, extractor.getFileType());
-
- }
- }
- }
-
- @Test
- void testStrings() throws IOException {
- try (OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls")) {
- String text = extractor.getText();
-
- // Simple strings
- assertContains(text, "Table 10 -- Examination Coverage:");
- assertContains(text, "Recommended and Average Recommended Additional Tax After");
- assertContains(text, "Individual income tax returns, total");
-
- // More complicated strings
- assertContains(text, "$100,000 or more");
- assertContains(text, "S corporation returns, Form 1120S [10,15]");
- assertContains(text, "individual income tax return \u201Cshort forms.\u201D");
-
- // Formula based strings
- // TODO Find some then test
- }
- }
-
- @Test
- void testFormattedNumbersExcel4() throws IOException {
- try (OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls")) {
- String text = extractor.getText();
-
- // Simple numbers
- assertContains(text, "151");
- assertContains(text, "784");
-
- // Numbers which come from formulas
- assertContains(text, "0.398"); // TODO Rounding
- assertContains(text, "624");
-
- // Formatted numbers
- // TODO
- // assertContains(text, "55,624");
- // assertContains(text, "11,743,477");
- }
- }
-
- @Test
- void testFormattedNumbersExcel5() throws IOException {
- for (String ver : new String[] {"5", "95"}) {
- try (OldExcelExtractor extractor = createExtractor("testEXCEL_"+ver+".xls")) {
- String text = extractor.getText();
-
- // Simple numbers
- assertContains(text, "1");
-
- // Numbers which come from formulas
- assertContains(text, "13");
- assertContains(text, "169");
-
- // Formatted numbers
- // TODO
- // assertContains(text, "100.00%");
- // assertContains(text, "155.00%");
- // assertContains(text, "1,125");
- // assertContains(text, "189,945");
- // assertContains(text, "1,234,500");
- // assertContains(text, "$169.00");
- // assertContains(text, "$1,253.82");
- }
- }
- }
-
- @Test
- void testFromFile() throws IOException {
- for (String ver : new String[] {"4", "5", "95"}) {
- String filename = "testEXCEL_"+ver+".xls";
- File f = HSSFTestDataSamples.getSampleFile(filename);
-
- try (OldExcelExtractor extractor = new OldExcelExtractor(f)) {
- String text = extractor.getText();
- assertNotNull(text);
- assertTrue(text.length() > 100);
- }
- }
- }
-
- @Test
- void testFromInputStream() throws IOException {
- for (String ver : new String[] {"4", "5", "95"}) {
- String filename = "testEXCEL_"+ver+".xls";
- File f = HSSFTestDataSamples.getSampleFile(filename);
-
- try (InputStream stream = new FileInputStream(f);
- OldExcelExtractor extractor = new OldExcelExtractor(stream)) {
- String text = extractor.getText();
- assertNotNull(text);
- assertTrue(text.length() > 100);
- }
- }
- }
-
- @Test
- void testOpenInvalidFile1() throws IOException {
- // a file that exists, but is a different format
- assertThrows(OfficeXmlFileException.class, () -> createExtractor("WithVariousData.xlsx").close());
-
- // a completely different type of file
- assertThrows(RecordFormatException.class, () -> createExtractor("48936-strings.txt").close());
-
- // a POIFS file which is not a Workbook
- try (InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream("47304.doc")) {
- assertThrows(FileNotFoundException.class, () -> new OldExcelExtractor(is).close());
- }
- }
-
- @Test
- void testOpenNonExistingFile() {
- // a file that exists, but is a different format
- assertThrows(EmptyFileException.class, () -> new OldExcelExtractor(new File("notexistingfile.xls")).close());
- }
-
- @Test
- void testInputStream() throws IOException {
- File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls");
- try (InputStream stream = new FileInputStream(file);
- OldExcelExtractor extractor = new OldExcelExtractor(stream)) {
- String text = extractor.getText();
- assertNotNull(text);
- }
- }
-
- @Test
- void testInputStreamNPOIHeader() throws IOException {
- //TODO: the worksheet names are currently mangled. They're treated
- //as if UTF-16, but they're just ascii. Need to fix this.
- //Is it possible that the leading 0 byte in the worksheet name is a signal
- //that these worksheet names should be interpreted as ascii/1252?
- File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls");
- try (InputStream stream = new FileInputStream(file);
- OldExcelExtractor extractor = new OldExcelExtractor(stream)) {
- String text = extractor.getText();
- assertNotNull(text);
- }
- }
-
- @Test
- void testPOIFSFileSystem() throws IOException {
- File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls");
- try (POIFSFileSystem fs = new POIFSFileSystem(file);
- OldExcelExtractor extractor = new OldExcelExtractor(fs)){
- String text = extractor.getText();
- assertNotNull(text);
- }
- }
-
- @Test
- void testDirectoryNode() throws IOException {
- File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls");
- try (POIFSFileSystem fs = new POIFSFileSystem(file);
- OldExcelExtractor extractor = new OldExcelExtractor(fs.getRoot())) {
- String text = extractor.getText();
- assertNotNull(text);
- }
- }
-
- @Test
- void testDirectoryNodeInvalidFile() throws IOException {
- File file = POIDataSamples.getDocumentInstance().getFile("test.doc");
- try (POIFSFileSystem fs = new POIFSFileSystem(file)) {
- assertThrows(FileNotFoundException.class, () -> new OldExcelExtractor(fs.getRoot()));
- }
- }
-
- @Test
- void testMainUsage() {
- PrintStream save = System.err;
- SecurityManager sm = System.getSecurityManager();
- System.setSecurityManager(new NoExitSecurityManager());
- try {
- System.setErr(new NullPrintStream());
- // calls System.exit()
- assertThrows(ExitException.class, () -> OldExcelExtractor.main(new String[]{}));
- } finally {
- System.setSecurityManager(sm);
- System.setErr(save);
- }
- }
-
- @Test
- void testMain() throws IOException {
- File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls");
- PrintStream save = System.out;
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- PrintStream str = new PrintStream(out, false, "UTF-8");
- System.setOut(str);
- OldExcelExtractor.main(new String[] {file.getAbsolutePath()});
- String string = out.toString("UTF-8");
- assertTrue(string.contains("Table C-13--Lemons"), "Had: " + string);
- } finally {
- System.setOut(save);
- }
- }
-
- @Test
- void testEncryptionException() throws IOException {
- //test file derives from Common Crawl
- File file = HSSFTestDataSamples.getSampleFile("60284.xls");
-
- try (OldExcelExtractor ex = new OldExcelExtractor(file)) {
- assertEquals(5, ex.getBiffVersion());
- assertEquals(5, ex.getFileType());
- assertThrows(EncryptedDocumentException.class, ex::getText);
- }
- }
-
- @Test
- void testSheetWithNoName() throws IOException {
- File file = HSSFTestDataSamples.getSampleFile("64130.xls");
-
- try (OldExcelExtractor ex = new OldExcelExtractor(file)) {
- assertEquals(5, ex.getBiffVersion());
- assertEquals(5, ex.getFileType());
- assertContains(ex.getText(), "Dawn");
- }
- }
-
- private static class NoExitSecurityManager extends SecurityManager {
- @Override
- public void checkPermission(Permission perm) {
- // allow anything.
- }
- @Override
- public void checkPermission(Permission perm, Object context) {
- // allow anything.
- }
- @Override
- public void checkExit(int status) {
- super.checkExit(status);
- throw new ExitException(status);
- }
- }
-
- private static class ExitException extends SecurityException {
- public final int status;
- public ExitException(int status) {
- super("There is no escape!");
- this.status = status;
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java
deleted file mode 100644
index 18138de8ed..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java
+++ /dev/null
@@ -1,904 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-package org.apache.poi.hssf.model;
-
-import static org.apache.poi.poifs.storage.RawDataUtil.decompress;
-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 static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Stream;
-
-import org.apache.poi.ddf.DefaultEscherRecordFactory;
-import org.apache.poi.ddf.EscherContainerRecord;
-import org.apache.poi.ddf.EscherDggRecord;
-import org.apache.poi.ddf.EscherRecord;
-import org.apache.poi.ddf.EscherRecordFactory;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.ContinueRecord;
-import org.apache.poi.hssf.record.DrawingRecord;
-import org.apache.poi.hssf.record.EOFRecord;
-import org.apache.poi.hssf.record.EscherAggregate;
-import org.apache.poi.hssf.record.NoteRecord;
-import org.apache.poi.hssf.record.ObjRecord;
-import org.apache.poi.hssf.record.Record;
-import org.apache.poi.hssf.record.RecordBase;
-import org.apache.poi.hssf.record.RecordFactory;
-import org.apache.poi.hssf.record.TextObjectRecord;
-import org.apache.poi.hssf.record.WindowTwoRecord;
-import org.apache.poi.hssf.record.aggregates.RowRecordsAggregate;
-import org.apache.poi.hssf.usermodel.HSSFPatriarch;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFTestHelper;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-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 TestDrawingAggregate {
- /**
- * information about drawing aggregate in a worksheet
- */
- private static class DrawingAggregateInfo {
- /**
- * start and end indices of the aggregate in the worksheet stream
- */
- private int startRecordIndex, endRecordIndex;
- /**
- * the records being aggregated
- */
- private List aggRecords;
-
- /**
- * @return aggregate info or null if the sheet does not contain drawing objects
- */
- static DrawingAggregateInfo get(HSSFSheet sheet){
- DrawingAggregateInfo info = null;
- InternalSheet isheet = HSSFTestHelper.getSheetForTest(sheet);
- List records = isheet.getRecords();
- for(int i = 0; i < records.size(); i++){
- RecordBase rb = records.get(i);
- if((rb instanceof DrawingRecord) && info == null) {
- info = new DrawingAggregateInfo();
- info.startRecordIndex = i;
- info.endRecordIndex = i;
- } else if (info != null && (
- rb instanceof DrawingRecord
- || rb instanceof ObjRecord
- || rb instanceof TextObjectRecord
- || rb instanceof ContinueRecord
- || rb instanceof NoteRecord
- )){
- info.endRecordIndex = i;
- } else {
- if(rb instanceof EscherAggregate)
- throw new IllegalStateException("Drawing data already aggregated. " +
- "You should cal this method before the first invocation of HSSFSheet#getDrawingPatriarch()");
- if (info != null) break;
- }
- }
- if(info != null){
- info.aggRecords = new ArrayList<>(
- records.subList(info.startRecordIndex, info.endRecordIndex + 1));
- }
- return info;
- }
-
- /**
- * @return the raw data being aggregated
- */
- byte[] getRawBytes(){
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- for (RecordBase rb : aggRecords) {
- Record r = (org.apache.poi.hssf.record.Record) rb;
- try {
- out.write(r.serialize());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return out.toByteArray();
- }
- }
-
- public static Stream samples() {
- File testData = new File(System.getProperty("POI.testdata.path"), "spreadsheet");
- File[] files = testData.listFiles((dir, name) -> name.endsWith(".xls"));
- assertNotNull(files, "Need to find files in test-data path, had path: " + testData);
- return Stream.of(files).map(Arguments::of);
- }
-
- /**
- * test that we correctly read and write drawing aggregates in all .xls files in POI test samples.
- * iterate over all sheets, aggregate drawing records (if there are any)
- * and remember information about the aggregated data.
- * Then serialize the workbook, read back and assert that the aggregated data is preserved.
- *
- * The assertion is strict meaning that the drawing data before and after save must be equal.
- */
- @ParameterizedTest
- @MethodSource("samples")
- void testAllTestSamples(File file) throws IOException {
- boolean ignoreParse = true;
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(file.getName())) {
- ignoreParse = false;
-
- // map aggregate info by sheet index
- Map aggs = new HashMap<>();
- for (int i = 0; i < wb.getNumberOfSheets(); i++){
- HSSFSheet sheet = wb.getSheetAt(i);
- DrawingAggregateInfo info = DrawingAggregateInfo.get(sheet);
- if(info != null) {
- aggs.put(i, info);
- HSSFPatriarch p = sheet.getDrawingPatriarch();
-
- // compare aggregate.serialize() with raw bytes from the record stream
- EscherAggregate agg = HSSFTestHelper.getEscherAggregate(p);
-
- byte[] dgBytes1 = info.getRawBytes();
- byte[] dgBytes2 = agg.serialize();
-
- assertEquals(dgBytes1.length, dgBytes2.length, "different size of raw data ande aggregate.serialize()");
- assertArrayEquals(dgBytes1, dgBytes2, "raw drawing data (" + dgBytes1.length + " bytes) and aggregate.serialize() are different.");
- }
- }
-
- if(aggs.size() != 0){
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb)) {
- for (int i = 0; i < wb2.getNumberOfSheets(); i++) {
- DrawingAggregateInfo info1 = aggs.get(i);
- if (info1 != null) {
- HSSFSheet sheet2 = wb2.getSheetAt(i);
- DrawingAggregateInfo info2 = DrawingAggregateInfo.get(sheet2);
- byte[] dgBytes1 = info1.getRawBytes();
- byte[] dgBytes2 = info2.getRawBytes();
- assertEquals(dgBytes1.length, dgBytes2.length, "different size of drawing data before and after save");
- assertArrayEquals(dgBytes1, dgBytes2, "drawing data (" + dgBytes1.length + " bytes) before and after save is different.");
- }
- }
- }
- }
-
- } catch (Throwable e) {
- // don't bother about files we cannot read - they are different bugs
- if (!ignoreParse) {
- throw e;
- }
- }
- }
-
- /**
- * when reading incomplete data ensure that the serialized bytes match the source
- */
- @Test
- void testIncompleteData() throws IOException {
- //EscherDgContainer and EscherSpgrContainer length exceeds the actual length of the data
- String data =
- "H4sIAAAAAAAAAGWOOw7CQAxE32YTsSRIWSgQJSUloqSm5g4ICURBg+iBK3APGi6wBWeh9xGYbEps2WON"+
- "P+OWwpYeIsECMFC8S2jxNvMdlrYQ5xha5N8K6ryHdir6+avwOer5l3hq2NPYWuWN0n1dIsgfbgshuSj1"+
- "+2eqbvLdxQ0ndhy5KJ/lc1ZZK9okY5X/gSbrHZTH1vE/ozagTcwAAAA=";
- byte[] dgBytes = decompress(data);
-
- List records = new ArrayList<>();
- EscherRecordFactory recordFactory = new DefaultEscherRecordFactory();
- int pos = 0;
- while (pos < dgBytes.length) {
- EscherRecord r = recordFactory.createRecord(dgBytes, pos);
- int bytesRead = r.fillFields(dgBytes, pos, recordFactory);
- records.add(r);
- pos += bytesRead;
- }
- assertEquals(dgBytes.length, pos, "data was not fully read");
-
- // serialize to byte array
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- for(EscherRecord r : records) {
- out.write(r.serialize());
- }
- assertArrayEquals(dgBytes, out.toByteArray());
- }
-
- /**
- * TODO: figure out why it fails with "RecordFormatException: 0 bytes written but getRecordSize() reports 80"
- */
- @Test
- void testFailing() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("15573.xls")) {
- HSSFSheet sh = wb.getSheetAt(0);
- HSSFPatriarch dp = sh.getDrawingPatriarch();
- assertNotNull(dp);
-
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb)) {
- HSSFSheet sh2 = wb2.getSheetAt(0);
- HSSFPatriarch dp2 = sh2.getDrawingPatriarch();
- assertNotNull(dp2);
- }
- }
- }
-
- private static byte[] toByteArray(List records) {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- for (RecordBase rb : records) {
- Record r = (org.apache.poi.hssf.record.Record) rb;
- try {
- out.write(r.serialize());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return out.toByteArray();
- }
-
- @Test
- void testSolverContainerMustBeSavedDuringSerialization() throws IOException{
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("SolverContainerAfterSPGR.xls")) {
- HSSFSheet sh = wb1.getSheetAt(0);
- InternalSheet ish = HSSFTestHelper.getSheetForTest(sh);
- List records = ish.getRecords();
- // records to be aggregated
- List dgRecords = records.subList(19, 22);
- byte[] dgBytes = toByteArray(dgRecords);
- sh.getDrawingPatriarch();
- EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid);
- assertNotNull(agg);
- assertEquals(agg.getEscherRecords().get(0).getChildRecords().size(), 3);
- assertEquals(agg.getEscherRecords().get(0).getChild(2).getRecordId(), EscherContainerRecord.SOLVER_CONTAINER);
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
- sh = wb2.getSheetAt(0);
- sh.getDrawingPatriarch();
- ish = HSSFTestHelper.getSheetForTest(sh);
- agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid);
- assertNotNull(agg);
- assertEquals(agg.getEscherRecords().get(0).getChildRecords().size(), 3);
- assertEquals(agg.getEscherRecords().get(0).getChild(2).getRecordId(), EscherContainerRecord.SOLVER_CONTAINER);
-
-
- // collect drawing records into a byte buffer.
- agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid);
- assertNotNull(agg);
- byte[] dgBytesAfterSave = agg.serialize();
- assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save");
- assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different");
- }
- }
- }
-
- @Test
- void testFileWithTextbox() throws IOException{
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("text.xls")) {
- HSSFSheet sh = wb.getSheetAt(0);
- InternalSheet ish = HSSFTestHelper.getSheetForTest(sh);
- List records = ish.getRecords();
- // records to be aggregated
- List dgRecords = records.subList(19, 23);
- byte[] dgBytes = toByteArray(dgRecords);
- sh.getDrawingPatriarch();
-
- // collect drawing records into a byte buffer.
- EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid);
- assertNotNull(agg);
- byte[] dgBytesAfterSave = agg.serialize();
- assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save");
- assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different");
- }
- }
-
- @Test
- void testFileWithCharts() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49581.xls")) {
- HSSFSheet sh = wb.getSheetAt(0);
- InternalSheet ish = HSSFTestHelper.getSheetForTest(sh);
- List records = ish.getRecords();
- // records to be aggregated
- List dgRecords = records.subList(19, 21);
- byte[] dgBytes = toByteArray(dgRecords);
- sh.getDrawingPatriarch();
-
- // collect drawing records into a byte buffer.
- EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid);
- assertNotNull(agg);
- byte[] dgBytesAfterSave = agg.serialize();
- assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save");
- for (int i = 0; i < dgBytes.length; i++) {
- if (dgBytes[i] != dgBytesAfterSave[i]) {
- System.out.println("pos = " + i);
- }
- }
- assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different");
- }
- }
-
- /**
- * test reading drawing aggregate from a test file from Bugzilla 45129
- */
- @Test
- void test45129() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("45129.xls")) {
- HSSFSheet sh = wb.getSheetAt(0);
-
- InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb);
- InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh);
-
- List records = isheet.getRecords();
-
- // the sheet's drawing is not aggregated
- assertEquals(394, records.size(), "wrong size of sheet records stream");
- // the last record before the drawing block
- assertTrue(records.get(18) instanceof RowRecordsAggregate,
- "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName());
-
- // records to be aggregated
- List dgRecords = records.subList(19, 389);
- // collect drawing records into a byte buffer.
- byte[] dgBytes = toByteArray(dgRecords);
-
- for (RecordBase rb : dgRecords) {
- Record r = (org.apache.poi.hssf.record.Record) rb;
- short sid = r.getSid();
- // we expect that drawing block consists of either
- // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord
- assertTrue(
- sid == DrawingRecord.sid ||
- sid == ContinueRecord.sid ||
- sid == ObjRecord.sid ||
- sid == TextObjectRecord.sid);
- }
-
- // the first record after the drawing block
- assertTrue(records.get(389) instanceof WindowTwoRecord, "records.get(389) is expected to be Window2");
-
- // aggregate drawing records.
- // The subrange [19, 388] is expected to be replaced with a EscherAggregate object
- DrawingManager2 drawingManager = iworkbook.findDrawingGroup();
- int loc = isheet.aggregateDrawingRecords(drawingManager, false);
- EscherAggregate agg = (EscherAggregate) records.get(loc);
-
- assertEquals(25, records.size(), "wrong size of the aggregated sheet records stream");
- assertTrue(records.get(18) instanceof RowRecordsAggregate,
- "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName());
- assertTrue(records.get(19) instanceof EscherAggregate,
- "records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName());
- assertTrue(records.get(20) instanceof WindowTwoRecord,
- "records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName());
-
- byte[] dgBytesAfterSave = agg.serialize();
- assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save");
- assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different");
- }
- }
-
- /**
- * Try to check file with such record sequence
- * ...
- * DrawingRecord
- * ContinueRecord
- * ObjRecord | TextObjRecord
- * ...
- */
- @Test
- void testSerializeDrawingBigger8k() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DrawingContinue.xls")) {
- InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb);
- HSSFSheet sh = wb.getSheetAt(0);
- InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh);
-
-
- List records = isheet.getRecords();
-
- // the sheet's drawing is not aggregated
- assertEquals(32, records.size(), "wrong size of sheet records stream");
- // the last record before the drawing block
- assertTrue(records.get(18) instanceof RowRecordsAggregate,
- "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName());
-
- // records to be aggregated
- List dgRecords = records.subList(19, 26);
- for (RecordBase rb : dgRecords) {
- Record r = (org.apache.poi.hssf.record.Record) rb;
- short sid = r.getSid();
- // we expect that drawing block consists of either
- // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord
- assertTrue(
- sid == DrawingRecord.sid ||
- sid == ContinueRecord.sid ||
- sid == ObjRecord.sid ||
- sid == NoteRecord.sid ||
- sid == TextObjectRecord.sid);
- }
- // collect drawing records into a byte buffer.
- byte[] dgBytes = toByteArray(dgRecords);
-
- // the first record after the drawing block
- assertTrue(records.get(26) instanceof WindowTwoRecord, "records.get(26) is expected to be Window2");
-
- // aggregate drawing records.
- // The subrange [19, 38] is expected to be replaced with a EscherAggregate object
- DrawingManager2 drawingManager = iworkbook.findDrawingGroup();
- int loc = isheet.aggregateDrawingRecords(drawingManager, false);
- EscherAggregate agg = (EscherAggregate) records.get(loc);
-
- assertEquals(26, records.size(), "wrong size of the aggregated sheet records stream");
- assertTrue(records.get(18) instanceof RowRecordsAggregate,
- "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName());
- assertTrue(records.get(19) instanceof EscherAggregate,
- "records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName());
- assertTrue(records.get(20) instanceof WindowTwoRecord,
- "records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName());
-
- byte[] dgBytesAfterSave = agg.serialize();
- assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save");
- assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different");
- }
- }
-
-
- @Test
- void testSerializeDrawingBigger8k_noAggregation() throws IOException {
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("DrawingContinue.xls")) {
- InternalSheet isheet = HSSFTestHelper.getSheetForTest(wb1.getSheetAt(0));
- List records = isheet.getRecords();
-
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
- InternalSheet isheet2 = HSSFTestHelper.getSheetForTest(wb2.getSheetAt(0));
- List records2 = isheet2.getRecords();
-
- assertEquals(records.size(), records2.size());
- for (int i = 0; i < records.size(); i++) {
- RecordBase r1 = records.get(i);
- RecordBase r2 = records2.get(i);
- assertSame(r1.getClass(), r2.getClass());
- assertEquals(r1.getRecordSize(), r2.getRecordSize());
- if (r1 instanceof Record) {
- assertEquals(((org.apache.poi.hssf.record.Record) r1).getSid(), ((org.apache.poi.hssf.record.Record) r2).getSid());
- assertArrayEquals(((org.apache.poi.hssf.record.Record) r1).serialize(), ((org.apache.poi.hssf.record.Record) r2).serialize());
- }
- }
- }
- }
- }
-
- @Test
- void testSerializeDrawingWithComments() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DrawingAndComments.xls")) {
- HSSFSheet sh = wb.getSheetAt(0);
- InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb);
- InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh);
-
- List records = isheet.getRecords();
-
- // the sheet's drawing is not aggregated
- assertEquals(46, records.size(), "wrong size of sheet records stream");
- // the last record before the drawing block
- assertTrue(records.get(18) instanceof RowRecordsAggregate,
- "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName());
-
- // records to be aggregated
- List dgRecords = records.subList(19, 39);
- for (RecordBase rb : dgRecords) {
- Record r = (org.apache.poi.hssf.record.Record) rb;
- short sid = r.getSid();
- // we expect that drawing block consists of either
- // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord
- assertTrue(
- sid == DrawingRecord.sid ||
- sid == ContinueRecord.sid ||
- sid == ObjRecord.sid ||
- sid == NoteRecord.sid ||
- sid == TextObjectRecord.sid);
- }
- // collect drawing records into a byte buffer.
- byte[] dgBytes = toByteArray(dgRecords);
-
- // the first record after the drawing block
- assertTrue(records.get(39) instanceof WindowTwoRecord, "records.get(39) is expected to be Window2");
-
- // aggregate drawing records.
- // The subrange [19, 38] is expected to be replaced with a EscherAggregate object
- DrawingManager2 drawingManager = iworkbook.findDrawingGroup();
- int loc = isheet.aggregateDrawingRecords(drawingManager, false);
- EscherAggregate agg = (EscherAggregate) records.get(loc);
-
- assertEquals(27, records.size(), "wrong size of the aggregated sheet records stream");
- assertTrue(records.get(18) instanceof RowRecordsAggregate,
- "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName());
- assertTrue(records.get(19) instanceof EscherAggregate,
- "records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName());
- assertTrue(records.get(20) instanceof WindowTwoRecord,
- "records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName());
-
- byte[] dgBytesAfterSave = agg.serialize();
- assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save");
- assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different");
- }
- }
-
-
- @Test
- void testFileWithPictures() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ContinueRecordProblem.xls")) {
- HSSFSheet sh = wb.getSheetAt(0);
-
- InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb);
- InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh);
-
- List records = isheet.getRecords();
-
- // the sheet's drawing is not aggregated
- assertEquals(315, records.size(), "wrong size of sheet records stream");
- // the last record before the drawing block
- assertTrue(records.get(21) instanceof RowRecordsAggregate,
- "records.get(21) is expected to be RowRecordsAggregate but was " + records.get(21).getClass().getSimpleName());
-
- // records to be aggregated
- List dgRecords = records.subList(22, 300);
- for (RecordBase rb : dgRecords) {
- Record r = (org.apache.poi.hssf.record.Record) rb;
- short sid = r.getSid();
- // we expect that drawing block consists of either
- // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord
- assertTrue(
- sid == DrawingRecord.sid ||
- sid == ContinueRecord.sid ||
- sid == ObjRecord.sid ||
- sid == TextObjectRecord.sid);
- }
- // collect drawing records into a byte buffer.
- byte[] dgBytes = toByteArray(dgRecords);
-
- // the first record after the drawing block
- assertTrue(records.get(300) instanceof WindowTwoRecord, "records.get(300) is expected to be Window2");
-
- // aggregate drawing records.
- // The subrange [19, 299] is expected to be replaced with a EscherAggregate object
- DrawingManager2 drawingManager = iworkbook.findDrawingGroup();
- int loc = isheet.aggregateDrawingRecords(drawingManager, false);
- EscherAggregate agg = (EscherAggregate) records.get(loc);
-
- assertEquals(38, records.size(), "wrong size of the aggregated sheet records stream");
- assertTrue(records.get(21) instanceof RowRecordsAggregate,
- "records.get(21) is expected to be RowRecordsAggregate but was " + records.get(21).getClass().getSimpleName());
- assertTrue(records.get(22) instanceof EscherAggregate,
- "records.get(22) is expected to be EscherAggregate but was " + records.get(22).getClass().getSimpleName());
- assertTrue(records.get(23) instanceof WindowTwoRecord,
- "records.get(23) is expected to be Window2 but was " + records.get(23).getClass().getSimpleName());
-
- byte[] dgBytesAfterSave = agg.serialize();
- assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save");
- assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different");
- }
- }
-
- @Test
- void testUnhandledContinue() throws IOException {
- String data =
- "H4sIAAAAAAAAAO3adVRU2/4A8EPHAEOnlEooNaSUdCNIg4CUDCEtQ6gwlITSjYiSkoKA0ikg0i1IyCjS"+
- "QwpSEr8B73v3PS6+9+67vz/eH+615pyz9tn71PqevT/rfGcJOIcLBtDXrNgAgBjAXcMFAAAb9SPDBAAw"+
- "gLGmzna8xlxjR9WhAXhrxMAfCzqAf9IPQPXBAn6078IBgAyCH/VgVD2ADwCxAGhNBbXpc9LUF2h8n4we"+
- "iOoNAKEnywaAFmAEGtDQABLgCA0AcAHfZvLjeozjc+gAUMATgAEygBNqzQTwHl8lcH5dGHWmvGY+1FJD"+
- "FQOTHHX1x+dkBta2H9UcoLam0I7bAYCRrJMjDOoIM9W56wx1vcnt6WAfF92t0gIhfrfqv0o8e9khH4fE"+
- "thqnQJHiJqOZUrbDByG8xwYeiEmYJPcUPoP17NH6hTz9cVtyfvnyyUuV3BzE06+vDH/Dlxi+/pYeV32e"+
- "IGIy2p+e90VyZ+i9OlDL+Rp6Dmot/G2tUgYbGW5vpkSep5Fk2eKtJthDdEvKkzrvC4cmWe7kKaliC7ip"+
- "0sMjlMUdN/akSG0ticE4nweeA7LUha1xyjNLXZEJUx80rOZMmgMIveJ5pQ7Hio17qM558+zaZgheNOHN"+
- "tk7hCxKIZgFTs9t1NGhTdj0EIdz0tEcV4KZebLmun1t9qpQ2fF6N29/P3I3j3pYc8kI9zaMjjFNPi/ej"+
- "qfkAaisS9bRAqLXpHai9Kw/38TIr6s3tZghB0GpAXUB/ncuYLE2mulOgiSpODb6R8rVbnQasDoj6bIiB"+
- "gpPYItWexPrqVgUk73GpZwT2sBroUQZ07ovZJ6SXgbdvjH//55ZoggllM0Rdw7K6gHmeIt/exXytDGpq"+
- "VeVUw1D6S2kCKezDar0iZnm3GGAy99/4bWY7VIgeWUlVmOVn8kdFOmIsel1/vx9MX9vNOZHYeqdvYnuy"+
- "PuP2uxHPjCotCFiHoJKzFzI4MTQn1bBVdLQQT0LmrX8os3+t4Nu7F1SC7mDgrFsvKsHS80DFHx3O8SsA"+
- "AJZ3XHlcbcydoagIOY6SWl1Vp3EIQT34gw8x7PqBwdNgkpp5LViiOWHMLE5uaQp1LIusFllOAzxrOusm"+
- "WExAlgdfVmW/LRLc67SnF1MHKe/PT2vXvfZQw1g/fIwStuEpmaxlQa9NEWv40J8h8PmVmRGejXo+EW2v"+
- "HEI0qo7ZNPb5niruyPOdHhnQLRUPGb+y4Wwo0WGygw6NOzBXGDYgzKBYzu+v6872oAZEaXgP4VtOrDV5"+
- "LyQtP9wxoKWMM/buA960eUbfNY0RKG1vKafEuMZMtwJjh5N0+JRy8JYlbS/r6OhsqifipW+Gx4NtrO4B"+
- "znA/UjinjWh9TytvuD/PeHSCSyZI5WEAslSzQZpIoczUQ5XM8tCuQSArrxGN5VGZ1OKFiaOi+zEpKW/o"+
- "vaSMwbfZQYveck70N1ZjZrwdxtKxlzAobG5kMl1LQFazAkJqVsrYDgCNeunmvRhm4c6jbinypsbQpyUr"+
- "wX1UwXJ9mtLhn3qC321JFsoymDATqy98V+hQ3ZBcpxN+W1+6wo6FrlRGKhW2ug7eAH3Dvn0rNWTG6vvr"+
- "qKDGWqAXYu0s8ZmmdMM3xFjWIjXsqtT56ly7tMPY9d40CZ/CQ0b4OLsD9qG5CB5n47N2/2qJMKo1+rUg"+
- "TTpa4D7au2JRC6XrayDXu7ZXGpvcwM5DWoz4HdBBTfQnmzN1K2YG+hpYNVGkX6ZlZGv7OM1XZeaZU1e2"+
- "Rt+QEzSTyLSYPXezW5pSbf62gbi5iHWB7xBAZ2leDdXI7Kat5+Epnor5sC3ZefMh0hUTSQ8VP+BIz2fh"+
- "t3eD2z9TLOhGRLoIErwXi+9yUgMZHhVGhWusRIi4J297mNL4iBUbHaKdFaRyobYMnKg9BWjH4+uPILV0"+
- "8nC8A3U/jlFjjX71Jgi595V1xmS7qScwAiEcrTYLmRbMfuaHL6EOo1NjPeWNa8hlBYLWd64rInOTrmyv"+
- "FPTmG8O5ys73rWL5VnYIcryPaJz1hicCpRGXFTgKhf3IKiBPTEzV5pMWMjt2zJfd24LZxbIx8ecWeVuF"+
- "eCqzynPsivav2VzI2+hbgvBvzjdDA5uZQkqynn+lwzfceOc/l4qsu1hsOTVzy6AnNW9HhaqZ8yHRS87z"+
- "01vZyoyAyGRlaOVkgW6lsSNCaOFlWqgRBJ2ZaR02lhwDHRJ1xN2B1xc64WubpudpxVONMUW7GMG/w61N"+
- "qLmi+xXRMaSqigzr33Iwc3owsLyZl1hUaNChDstgByZaRb2FUik+0vh0uZw72thqliZVKKQydVxsnHk3"+
- "yPj3tx8NnQv4+UTxz+WMaeP0AU6Pnb8XbrR/GklPdzw98vxeLqH/cRw63ft0SPxeejD/ECAaqljYP6Zo"+
- "TOAbas2G/aMp8RrpyQyOBpihYQAbqK0+1BxuiKojWTvefxM1J1MApKiTggESs9MPZ+nkUghPWpajkQKk"+
- "6H/bg/3bDYkDqHuDQT1hXLziJ1WUv+3+2wE6cY650PkPXCD+CRcAqPZf4ALfb1y4csIF3l9c+MWF/44L"+
- "j9ungt3+JRe6HacgxPUvhzyKvXJ2F/yZmvIM81egZfIaDI0XieSQH6KXZeYHV8Oe9jmC77MXmJyzbuVH"+
- "7Dxh7HWqUYgJgJQPP+qfFs2Wy5VJLBvjrb4LP6d2qSSiIEa1EDOTzXzBAf7NYTKe9Uv+BzvZxsBSGlzq"+
- "j2IjVpqWoXU2lXXDhRppha9tKwNMX4WqNEd+qo3WpH0X21ausDawEugMlpZ1XaXro5TpEAOTyMX3q32g"+
- "MJxtF2+idkYSmm3o6N6l7W39svNCNlqfzruLTTpsXDpob1SYnlNqhqsWeUW8X0QLFtb0RgBb4RFZ5sL0"+
- "d0/SQfbKUi5bT3OBzDhhYW67b3Rb0nlESHfbpvodNwNarcSwSY0MT4wUiebd+x+jYc7Y1n2+lUQtURRx"+
- "30MmxUonWXqrOwS88XfYSPvWDKWTxAd15QH75K4YXh20CYiyU3YjQcbGEoJcjplI/AMtEo7r7XINk573"+
- "ttxnL6/9tUHRi1OE6J/j4C+e18b5+n2Sujwc78Z2iVgqPx6w8gr3STZTEnam+x76oWmpHGSLuwkiJvTG"+
- "RlKOOIuBQ9oojJdCS+4ryVHpYg358B7SDCFMC46CEUMqT575UKujkzl/itEcCTxEr8cwQdh5o5lxmTEm"+
- "sBHYgkxtulQL0LCL7vs/j9lrs2FGJpAmZb1khCo2GylQdMmohMWCCNdlSh5UgdKDv7/24CGqTnOKID6P"+
- "zVFodIvClLZo9WhLi4c6eh1EzC5SzyMTLmTnaWpiPnzRRdLGOGLDNc4iUwyxMqmSe6ed0PRpeHenTdnu"+
- "OLWibGodMxRubxi1VyEzLFOFs7LTt8poQuMjWvzk6Ews6D2wxOX6F1iIMr2OwsJbhNo+Ubfgulo5Ravk"+
- "JUteZgv/qaiWkdJy++ryV4WQnU13JuY9z566hsH7oslDpXJGjvbpFH65FOhTlwdfaNChF1Qs3GSMctPh"+
- "Nbz9Fm+pKrB9Z++2XPC1VZ2OCtUKaQm5UWaWKDF9woBGK5HEoXLY2/hUPIeLbibJao0EH3edb2ALE9T4"+
- "ZQV+5Zl+PQUW6ZVIRMQ0pjyc21bn9c6Y4njsNgCvvVmcFDX+RLQKZ9pzmbtT97CkcWN3zy0+hSrChV8h"+
- "jVBJfGUk2+xSWQQden2qE/JJ0wf93E45aJWQUtYEJQ5idRqUycJ3TzENxD4I/XJlTx63k95POuxW6jSb"+
- "NU5wwAcj6djFzYfLB6U7YLpvGT2Swk3LEhF0wpUTMPJESYaj/zktnB54/pwWTsfE76Xr32uB9QwtYKOm"+
- "5GMt4ACzZ2iB+C9qge8/1QLJz7TQ/1e0wP9LC7+08P+hBWVCae5j4tP+VAtqruNMxHUe2Ud+n1fmLyTQ"+
- "2YXx5fEvPB/0XNrBMcMbTT7fB5TM7O+t+C9liWwSe9yRtqHauspQ07lU7sQyCrpFV0itVmSh8uCy2/tc"+
- "rkxkTnA/Icuwi65LXrzZJjtnHVc9/PG3+Paqyx5jxLjp9kTYCh49bnfJR++wGTq+hLGRe9o5GK58GrHP"+
- "7FjDwHSCxrWuXyx9SlJbKsY84b3W1/QO+3VV1NceWUxtBxid1fMEeb7QKAz1A+wk8WG36NZBztBeCYG7"+
- "Ff3BFrRdwldH+yS7B5aW1um8pvWF+8W0tsKaqgWwpTsuZC5YpqhZ0AYqlV/g4gm3iiPF6YRmwpvFhd/D"+
- "33NdS0ps2ALJJj/q52V5VMG0QPbiqOj+HW98bDtnDJerSZ+1+lZo6ggtvZWebZfZBtN9YuxrmAlHTxYf"+
- "cVMDllgfs9JcREuB7CZEfBGQhT07MvJnX2sM/PFxwfU8dYjmBZW53fWD60iNEH3cB9p76dFftdDU0XE0"+
- "eQtfiKn4AVpcWOxftPeb0ZsDA8pLJEO4ut35E4Okqnz7NKwgjs4EOccfF5rfSNDc95WDaY4wHbB9SZU+"+
- "2C3b89lxyHxNsxk8eXENfcuYb3FPwzTNo5HutoMS0IX1onkxJE5oLbCpVoAuDVGtSH07DxyWULrA7qew"+
- "93XSHVJ7S0eaI6tFWGSkkSqG5fXNNIaewY9XxXL904XR5S+itGBOaaoyMuLjYUtuabkPoKtE9IZqZH7D"+
- "f5ZINS+ovLSROlfUeChS3SrjUT9xwJ2ej3XF6+6k/TPFzm+IJyWCBBUe1XwIIS6DA21muvSJqx77Oqur"+
- "DDQNorlG+2d64a68eyEHak/+z7ygeeyFQJQXwMdeEGV970demkTM+/g3L7g4WBuZ7yC5LjyY/yKyDZ/b"+
- "gok76IaXN1V32OAfmGAqzTetqTixv5i0voLHNPd49oWQocYHEM5g+8zbpPDK0QVj+0R4gEyI+wWF9M16"+
- "GvOlR1rss/eySUS7skoe7TItY7t2ujMbvxeOyBB7YfC8OTBGcKqE/O3cVyPNtkqvXWqdV9asDQO7TNfb"+
- "3N/gPR/Rd9gD2kKHUxPpOKhcEgoRegu26aFPXPExpL7aNpRT9D7eaNLCPZAZ7yNnTZcxyqlmD5fnoyra"+
- "wzuIqH+twGznTh7ki6/NuB8Ajx/AYzQmjXV05puyUVLC3CFe7CZZDjaipzsyJ7tzBF55V6FcjB7We32x"+
- "ZTeUreF/TgunB54/p4XTEfF7+Q++LZylBTyA8EQL+IDrGVog+Yta4D9bC104p1MRpD/TgtBfSUUIAL9S"+
- "Eb+08P+gBSMhtMnjl5b+51rQHoecaEE6837xU9bHUW+s2AnqYPixjWDi8hTPy6oMyheJGuqdWNg0iK5G"+
- "EVHdMLHdXq4/6HsLRVwujx8WVJgTF1MVia0W0M0cEfHxqqTvFnE1mVdhz4T2bA+sd04hE0PrS0HpneEl"+
- "BKyvjaSiNsK3P55XNq6KLnS2zo6lzSkrKVzbKUNmlVrgfClUabUVVTW2fp47oaDiQ3bdk8QeY9nwshsF"+
- "U0ZueXZ4zUDu+RqlNpwxbCz7lcVq6py5Qdt74hc0hcut9C0DiJbBMtVR0FinhbSAV2lkYQ3nOyZflfbu"+
- "wsTpcz5lTcx5iT+5Zn3pegbXSIle3PB0Cn8kMr+/oSQy+F7N4orDRGJD+XaCIEWYS7Y8SI/R+ahmYXTa"+
- "jMBDyW+XwWI6cPpNZkWQMeQSpbfDODPeFMYlG/nMz9kGSdVWwBPruVFyNykS/+67tDLkoT7aUXKSberW"+
- "T4+Yu9slePniXDlUGffJxlN7yEheEmPmdDtkDuVhnsONyNKCijToxwBxJioQsvz9ZswLnz8JEfpVDhSl"+
- "FsVD56mJw9Wb9+TswrgB0jvhjcdeuAi7MXKcjIhMY4ZnHjHCx21u4RzyPrvIYsah0+PN+B3kpVibPhKE"+
- "nmaYJvFia3qArN6mS7sA7cIIwjwvfnSmVkftHY3VQuf90Z5H3HO0g1H8yPdlfg3sCcJ3P98Ly6m5tzXv"+
- "ny6SETr94g5cXtcrv4ZddXMiT68thBCEq+NvQp2nGMlRC+FJchk179vxn52zkQlfka3B4coruG/+9muu"+
- "fapi57uGeFsBglGxLM4wNRxbTy6dC2UNJCbn9g4+ipE5KrqHSp4ZpOM9XLvH352LfpaKuHn9RypCUmCk"+
- "5coC9RBwkoqwhBMoe3HZdVKOuJe7EfjU0ctAJD6muK6ILFcN3i24PISLVMm8tHmfhCndtVm17nkx3Ggi"+
- "DBDpFbCO7/dvMhFO6uXmybZv6la3zrixy4XPPKZGHdj0/Z5/SScoPQn52HA+TfkWxQbaGNdswrJMZb7z"+
- "OfkKgxKtYCp8vdDvMtOMBTzyzDNfF7wNuBke719LaLaXS6ZSZ6+rvx0rJmXy+rDW+IpQ+CBso1pdHRRc"+
- "yZIjBbQHH7QmiN/qAakyb4IcZLWTAvEd4udrIZTt1yq/im1+n3kuiH/jFagSzH5Flw3W8ipOfSeCgSgj"+
- "iiKLjELxlsz5xptFVxQ9vGDBuyNXI9okPSQZwiwGqtZ3jXCcJTaWcP7XuHB65PlzXDgdEn+KC2elIkBA"+
- "8gkXCI7/dfAHLpD+RS4InMUFcaDthAtt/8AFsp9wwZf/r3BB8DcuCJxwgfsXF35x4b/jQouTZIA7Kv7O"+
- "/YtUxI9/LojhVueUB4iqhbfJJ2bUENhFCYDT2u5YXEsgUFZLkThQaleuYHC3CTKxTCbd1WT0EahBGslv"+
- "DVS32ii8KogjzQvMo62Dwg72hZO1psRHKPQVVBUiB/prviITb5iO+tuV8Cf4gpbxNSDVG/UcMS0Pn9pX"+
- "1fA9HSo2ohu/A25wf6KTwNh4tyDGJVmddORGO0dF7IBkC70hNsJXKFHlI05Ibn6hbebFsMuvbvjzplET"+
- "SHnmI++kTM7evTcpq/uhfFbDakQz8qsyjX32rhp8Ep/1zTZd2tJVkquZu8KMOVIPhflEnxnPxcax9scj"+
- "lToDBcO0pj5X3t7kifqSPfmyOjC8dKfK1GBAJ0ydvb8WSyv18/6Vwdj9aYKeNLT1q7nMXLlgkoOFNqzE"+
- "2nm7cSKRT4xtUp10hOZfm4YE0Ypt3Z/MaGB/DmqcUQt5RHWUzfTQJS21R/ToZnLorfPzIZocgeD19QPw"+
- "XHTIFdwHg7Mlmota6OqYilolxSmSlx8CKjwsELJHKCrINvmNCxi34NV87Ipn6YNICQjQvqAz/rKMznR+"+
- "xLnkeisDE8nNYUGNo/Yd6z5nn79bwVxU+VrjMw6FYyvsRHjKviTE8i3z9Tag580i9Ern5SnETqo8xEsw"+
- "fIyRKSNIzwJRMUUgiRI8wm5TB8UZvJzFngq0eBhAJRO5vbBiKg5703eOV45AT6Sh6XK9gDG76nyVal0a"+
- "GR0lk4aLl1kWQ6H+WmNtU1jngMZR7RpLTy8JgWWcC6Gelj7Icfervb2pQuc3RKswbdDSUy3K1mwMB09O"+
- "lBZ8Pj1LRWmBn0xd0b0TcWaMvhRwTruEejUL/yMtjCZxXMuKevsgpH2fOmbNcDiBq2jZnuNYC7lyjL3W"+
- "qwueYx20DlUl8XqYe3XExPqBVvFjxAb1PUWkUsOab20KKdiK5yizYzde8dLz1mmLILgnsHdJoYpxUgvG"+
- "/PjoRnHGWuODhPomZGNKi+ICT3xpqjdmSokyIOcwY/Q6GjQGghDxtZ5GXkroNGSRBZXJVzXWn/V8EX8z"+
- "bh2EV1VrM2gkFVGxYum4qEsJHd2DPj6kJnJzVTADlCZWR7ItRI7zEPBUU2RiU8t1G6QOxXMhpekJvVQ4"+
- "IppKQdVys+cLtUY6Un0+hI2Z0wMzAxO8Lr0LbaILk8WtNsxpaFYMrTjC22723OH5GFkUi+ux8An2Hi0F"+
- "fvcr1v8aFU6POn+OCqfj4ffS/e+pcOEMKhABrCdUAAPhwB+pQHYGFcT/BBUEz6LC/wGpc+eRNSkAAA==";
-
- byte[] dgBytes = decompress(data);
- List dgRecords = RecordFactory.createRecords(new ByteArrayInputStream(dgBytes));
- assertEquals(20, dgRecords.size());
-
- int[] expectedSids = {
- DrawingRecord.sid, ObjRecord.sid,
- DrawingRecord.sid, TextObjectRecord.sid,
- DrawingRecord.sid, ObjRecord.sid,
- DrawingRecord.sid, TextObjectRecord.sid,
- DrawingRecord.sid, ObjRecord.sid,
- DrawingRecord.sid, TextObjectRecord.sid,
- DrawingRecord.sid, ObjRecord.sid,
- DrawingRecord.sid, TextObjectRecord.sid,
- ContinueRecord.sid, ObjRecord.sid,
- ContinueRecord.sid, TextObjectRecord.sid
- };
-
- int[] actualSids = dgRecords.stream().mapToInt(Record::getSid).toArray();
- assertArrayEquals(expectedSids, actualSids, "unexpected record.sid");
-
- DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord());
-
- // create a dummy sheet consisting of our test data
- InternalSheet sheet = InternalSheet.createSheet();
- List records = sheet.getRecords();
- records.clear();
- records.addAll(dgRecords);
- records.add(EOFRecord.instance);
-
-
- sheet.aggregateDrawingRecords(drawingManager, false);
- assertEquals(2, records.size(), "drawing was not fully aggregated");
- assertTrue(records.get(0) instanceof EscherAggregate, "expected EscherAggregate");
- assertTrue(records.get(1) instanceof EOFRecord, "expected EOFRecord");
- EscherAggregate agg = (EscherAggregate) records.get(0);
-
- byte[] dgBytesAfterSave = agg.serialize();
- assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save");
- assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different");
- }
-
- @Test
- void testUnhandledContinue2() throws IOException {
- String data =
- "H4sIAAAAAAAAAO3bdVRUW9sA8AGGrqFHSlpAhSEcQAkJ6UYQyaFBmiEFpCVEOiREGikJSekGlRJQuiQl"+
- "FQFB4ptBvxvIvd+97/fete4f7rWYc9aZc4aZw7P3/s3zbFYB/FiEANTNeD4AAATA2sQCAADIH0wgAEAI"+
- "QNv04kNugZusiGMoAOxNEODHhgrAObkOgLgGHfDt/GlMAID4+3EUxHEADgDgB8DdVEbsNgDAgPMAHxQl"+
- "nzpAAwoI8XsbUfh1QwCvUPiNAIBjFCzEO/BuoUOeiYZ89fPA60AloCBQGCgO5EE8XgPKA4WA/MCrQDoA"+
- "F+IsRgDDR0VM5JUAwHVAbosYYl9ZDg1ICsA4+Sz0gM3dkJpDxN4s4gwSxFZb3NbG0cTGUf+mm50JXJfD"+
- "1doqJrJbthUC6tjw3QAtsFvnYRJZvMDMlyLTPQ+TzrYehmInaLpMTTqKcMzi0JotHH9kzL01ZkHKc6Ni"+
- "kq2K4yJorozv7TaO8FulNhosxSW8sMlIXxqugsRXD+7W4bYy1NBcBKvi7KqW0pqLcXjSxXM+DifJFmzX"+
- "wxikWpWZvDlUODjJ7JArLYfB6yRHcy9MRtBma/86sYUxiBBz5k0WQBxc2B4jM7/6OjxudljZdFGvxQ/f"+
- "I5br+tFosU4PBbUn555F+hUmPa5ss2Tu+7yRzIRgVsuXDWrkr4Nxp5w01EYk7+l7XHgKn2n3qpbe8no+"+
- "ZuWesRfDsSsy6IG4v8fHaKfuFteEvsEbxF444m7hIrb6DiZWcE4O5GNmRNOdFgje/Q2/Or/+OvtR8XMZ"+
- "irYBenKYNTjaMvJGrzRZrKfqsyGakrbXPlDsC3/c2KmE5CaUuoZhvFXADUk3WXwPm17x0PT0jvLtn2mN"+
- "xBuXgU3VNawp8hrkSnHvM+WppoPBcjJPtB7QsKXyJrO+VegVgOUa0TqKuTf5fM62rrx6bHq9EpaXwRMR"+
- "boP2wUNp6CCQprb70nh8u0Pf+O5kffqdjneu6dWqEMKbeFWXeiED44OL1xt2nh0vxxKReN46EjuQz9/u"+
- "KKC44kwIOOujl5871I5HBQAOMJDdAQAwdoBzws0N7EwQEYKMkgJ1GZsxCOkExRIN1joJfgWxVDFpGcGo"+
- "Qj9YEQ7QSLdKI2WLKLhspp46hiokRtiv0E9vFmE7qKSqOuqo2bojlj1JcezuxZCzqNDWlyirjpMyPT3c"+
- "EfRJfo5Zn+XL/tDzDGxJWZIUEhZ+hc04do8U4Xu81g7nSFIK/SWmffPB3sCismdGvWojIRoSNA8SHYrJ"+
- "xTQkWvJ17lYzUdnpcXF+PiRRGoqK0ilkHaLo8VVb0bZtDeXeaVXlfxqR7pAvX8ybfFfS7/YofnHVpRBH"+
- "0lApA95hPONuVas3kX7dpR2hQkHNJRuE0Jq2/XrGQUM6mQ6/LRQe7XSZ6eMH/Eutk2bCD/ZpYNXv10Zu"+
- "PmSPkomEhfJa817co9K8plVfn7dYGr3pIBT/9DUJtWGrDHrAHZG1yTXhiqmxsYmvO3D3sXtjnuZeZfqj"+
- "RayNk8XdX7z5qNaLaGO3FWazI9RvwT55f9LInEuNb01nVUbDJ38oCeKRHAM+uZ/BM8WnJY3XlPZ6uCO6"+
- "05vVj9B3iZffJ/yhcE6rh5Zc1hO1kkp2Y2pmzTfy2gHGh2IWUkNqjm721ZDu7M9xKoy+H9EDvK3ei/Bz"+
- "KkOwBMpWnQ2XQmXKWC41Mb1ifefDUyitSEO9t7nyiWu1eKTEN7Q03XgVNnoVxTTxeHDBYejjCAM5OtMW"+
- "bO7omPh9p0WvOSPFgd2celfAQRIAQ32ZwcXDM7rqLUQ3PSmHYYpSpmjmPAZ8Sthn67Z+cwbMMHo6NPaK"+
- "pN3m5HhHpikPygTa1vuwBaAln7788kVGO302kID8dL1eAUknroFcleOjaGk34QtRlwBmrePCn9b6Zylt"+
- "nlDxY/umra1wTHlGrXVlAcrjUS4aWHEEsWRLVJA36DOSw6tlvFDPCuKXAuvz1Ii+G4aCHIu/BbGxrYuN"+
- "g4kzMoblI14ptkBAN3alD/yuSFuBnFJYY66qi4qZqEmMlsLMiBfpDa+VKkQfCUXH5U3s9Yzz8Lx7vken"+
- "XUrSDtXi2rxAC0pz0OXNMyyeqJ28cL3gfd50oYZvk57mo5x3t3iELzsWcZdo14RMg0xykkXXdPiyBhfK"+
- "I8YVHS+Q7shaM7mwKtzAbXGn5tCmdJ1Ei61VqUpbeOyae+Po+VFs1Zz4PZtt+KfydJcxYW2bKBYCknYb"+
- "2/ttJKALGC7Q4wFbdD+AdPW4V1J2Z5VTM6SRH0zgJxpCQbgmNl8OfV/Dq0Wc4Y5BH6FTiUm57X5bayYi"+
- "yK9TnFo7R3VJygCERmOfE14cfo3QEWg0Y+wZ2u/a1R68QXP7rhtmyBZfttcvowEK6mXAH08cv29nTCOn"+
- "X+D0WPpr40D53ch6+sLTI9GvjQ31x3Hp9NWnQ+DXtg78ISCU5dAxvk3fQMA2YsuH8e1U0Cbx9/kdhIoG"+
- "6EY824eGB8BHHCHaRB7XBVACyBCzPCpCBkSw0zdnFbCEeVoCqP+gBLh/SuCnBP57ErjpXBiC7H9HfyiB"+
- "7rABCKie8SNB3EbNnkXSZZVoMkd0ilYN3R0U+dkyojCakWwRd7HZkLLwRnE70YNVnkzb1mFFVZhPS4VQ"+
- "Zo+84BTf1Ovh6C0EBUK+UWDwOwWYvuxvb0VznabAyBw3i6A2TjAd8BYXmLh28EWYkJKJnBaRE/udl03a"+
- "WLeJ8IscZuajCuhd22r7dhlPKHCZDUEBPzUq7aK2GO6dQTF+Nfob8xoJMAv+j3iYz8uoYPa3SZchIT3N"+
- "Khs8LCtxho8JHo9cupb0EbPJbvprXa9NScmut9ZnumVhV9vnKs1NX/QbReV2aB1IBZd3vG3Dx2dyKdWZ"+
- "ohmawBYv+gvmbA3WvPc+5KV0xbXmD8mncyttAhgV2VnVtyx277mMediuO59P7O3W3bLeLdnr97CoTwe5"+
- "H0JJ0Catmhskb0KhwXwBBaPE0ZikVQzMmPVM5Dd8oH2G/a5AAaMyhc0vl1Bn8CmIxR1YeY7ovzQFcX+h"+
- "Az9GJ/Kw+iLAsjCgxX7oG+J3m56EtSnKdJSbKT9e9tpTgvShNguDUYXlyxn3ge/hONgjb72KOZQh0gJl"+
- "S86mSzEyZQzfJQC/LKP42G2upWgoY8pgqMQf7zlCAubjWqimKRtwuFa5a0XQDRRDWvzx4ycQgmTnICi8"+
- "KRxTL1ans4EIphwLhQe+uxJsiT/AfHdLfk5bfBn/oAVGO3rBTmxFzpVUvoAkuaS0HStsMknEWvV5rve6"+
- "z559INy3PIkz+3MsvSsrWSc1y2YfKxRrSWwY9RnNAqtqSm8QE7yYx3D9/N668T383V78ZKDo1I5TvsuF"+
- "UqFqUs01p0ZZcBJuejBbZGHbBkVwuYD1mydnBnFQfewychqIOFsCNyMUlE76sPRBYKe0DkhO5K3qy1IL"+
- "ujR7lJJC6qoAFt2LiZmyzaOH7oIYo1V75YfD94QS8POYtS10jXj97EgBkS940/upMNr2P15FmxV851sp"+
- "KYdxbRkGFRJJ2tR5pMc57zzPBww0j4djlO/qKuZetMytokpQvFOg3s6+rjKKTxa3y69TzovjG8M+aT6u"+
- "vKUoPFh6oOPJpvMpbxIH/qROZCA/XZ/j7e3o1nNG8RQtBwRB8X4i0OM3Sr6ieJlaq8JWjHHjbhbnUml4"+
- "A9thSAnoxJeXfK0qlSSyvIthRJdlcU6i+B2n+nymFAN1B8qs5r7cw4HPLLLe6/a2BHZBg4SPD3IGNsm1"+
- "lRA94DmaghKnqL3H3Geqf5sETo9Ef08Cp0Pg/ysBNCAgEfEtvw+ABxg9QwKoZ0rg/YkExn4jAbR/UAI8"+
- "3yUg8xsJCP2UwE8J/GcSKAnuIYz+05yAnM0YBPQ9J+BJPRICYzOnKUtK50peABRIjIixqdLd9ipl77P2"+
- "oU0LXMpeuoDMCdCzVT/8ert1p5m2126hbi/y/QOn7r4oWXXslNkTCOiQkj3J+bIw9DwazJiFzYlFkpzt"+
- "Kk5W30krQlmEmwBK4fSXAPnmA0nZ9MwnmFJyPqEXBl8lw5+HXQ4oCL7f4LBOFlVA59qNgEBgyh0m5gAt"+
- "5TzOx+hm0Aq9YGyT1eAAuzzVkFGZatgIbPUcgWQZAZ1OrIkzbUB/jyHpW9Y29pVByVWndmFKVKJFFJYV"+
- "A7RjsQHDwD7MESl8+pcNdn5hy8J2IILZyUVah/AcypvROiGkRpnLWs9DGlBGImderZiyXzPkjFcLzmNo"+
- "MwPbq4o/GVUacxkLX9vdsflafzg+WT5VcX70/Fr8zkVKmO2iqWEjYr7YIIp9qBDlxLbyrGEOZaJQps2H"+
- "U0bidvqV17cEgzAN/PsxjEVCpeptOyOApeLVAnbkUoupEtUCRA996ZOhQBoyeFmkrEjOLEyrEyhbklld"+
- "Qdr1KeANQV7gEs77EIP7Csv4SATw4JwbafKyM0g1inAw719r78OONpfRDJFJUXuGZqYV4XvVaa4lJ7+j"+
- "p0Wjg5j79cuQkgz7FaxH1kfRSfnqgWZJmnHKrzN8vh5fDEXLEUrv1tl87/OOjOKTLRDsmPVqfGZbfFay"+
- "RT5YT4SsrV35Ln5DcUJgD/Z47z5OvSyLBlvP7SEYkGJjrV7xDpQIIlQssn5HscT5a1tMPRRImIWa0IJB"+
- "S9mG4fMCBA2UChQIiaFQY+jC+xz66J1UvVDCROMKHJdPtJjqa3a+i76xuxNb32iHt3oxNF6CZIBh7MHX"+
- "3qCh6lFjEZSzAlh6X2qcCvHMw7+YD4iKIhZ7nEeXVooSCb00nNDqFjQcZjWQ6dWbmXXHpb4evi648EC0"+
- "wvhiqHWZ4bSSIJ3Y/Avzm210Y7Xjkr/kAxQ1NZniKeC0FC9u5Q4/070BkRh5xPP08YqhrLUebteahItY"+
- "2q07jNXiFuxa4EmjKiuLaTcedreMYvHuax91HhyYHV4s6Qo8eP1Z7fO2pG2psK51OkuyZKiuPv4rKTpF"+
- "vPWbB0oN5Hjr3jH5E5UWITHaF/DQdDDjW9romoIDnXM/aSV91KW8HNwv5AeSfqaNoQY+SQiAx3vt6uvg"+
- "B25YfqClzquedJ4SO6ySyWn3IA+LHcvCrLztMRNTwn1mHdvmCP9tCDg9CP09BJyOgF/bh/8bAdynEICG"+
- "eAPoAFMkAlDwAdlnIADtL6YDgP8gAngBP9MBPxHwX0PA6+aBzkeInnb4lxAgEzbf6ZuV6tRnE9Jul4hW"+
- "TGyCmyXtY3zYlXe9Ev2uP216UvqTZNF6lcBMJr7Dy4buBgM8c7V8tqadXW3ZhuY3stjRlezsPhhJuLF8"+
- "iuIk9tj6MCLjH/nGf9EfW5GkNgtHPzP8vAK0OhS7N06MAatJHe8+kLP8pDIQpSHxOCTRYfOkMqBfvekg"+
- "8xZUazjZuCuVksfMXK2lilAAZg5CAQ/YThSQLRbyspC76c3zYDP+R1lCgAf56dJ+KhBa/7reRwXaIU5X"+
- "HUyfr1q1e5Gj10/VrGJT3Q3PuREeuW60C4Ub8wdJHjfj3/f87N6o4jpJg6LoPk2gOPSUIYEUu1164KEp"+
- "sxeaJYVf0bOVBCuBWp1uJvYtYCACA6JpiUo1LjXh3bsLNrv1e+PjV6aczyee745fuEhpWCRygoGNIiQG"+
- "ZhXo8ysa51DmC6W7fDiDb6ik4vMOu66K94CtDWgkULAQFgCXiieMQEKbucAqps7+iyhBd5xdw0JGTkoD"+
- "9pDLxqgnpYEQ420xC8wh0bJmfi75SrY6k8EImIciPePYHiE5BjsGG+GlFzTnrpoQF2LJQbq4XzpN68hF"+
- "qZkReH4pu/v5QsHVuAgDjZhQmofaco2hW0/GkzUup1w2VPF+JIW2e3wBQQGabxS4xXxCgZtZ3eMzTgqz"+
- "Wi2OwZOCZHtvkRSAJATuYOv0ISiAw/IWu0fzthGQb2NtA5o7cvP6buNBVY1A02g3hdr+KEgwBseYgMTV"+
- "nJQK6EhvhVJEACdl6zWTiBIYPsfVG+7hzt3gs7j4dpzMc+xd4eTjzp0PqrDyopPKQPBJZWB3isgSPpp5"+
- "tgRy7xoJUP1ZZaAbKQH/Delav3JpHZDTG2iT/wt1UbE1dIlRu2lT4kWpVmeTJBZPd+gdFfct192xkZGR"+
- "9FuXR+RWKDME/DMAQYPVbJS69p0VRbt4QVtiFOlXtBz4pTEf7G0PyTMFLDuy71LpE1Gn6zLwD05uEMvq"+
- "6skxj3euZrZrWRQQ02YVmhvcCGxRl+sQBakxUz4kKB/uitdaEEnSD2A5/4GHp3d15eGkie6L0VKWREiP"+
- "re3+PAmI093LRrh/xVccmKlDU2+tltnsZiEAo8YLbIKFUe2uqS6Wl7TUlEkSWV4l4IoYL6NmgSztljq+"+
- "yTA08ObVOPJq5veglrqOOZrESKWoBNHSb7x0t7FHzvWq6Uei7Hj3VP4n9keY/zYJnB6J/p4ETkfAr23j"+
- "76cDEBJAwUB83UZIAJUAAD9DAsAzJCAImD+RwMRvJID+D0rgyncJyP1GAiI/JfBTAv+ZBPoZnjfFIXra"+
- "3l+TQNx81R9KwOF3EqhcNiNyN1LjSXYLR0pg7ywJHO7vdSHzAb3YJMksrnJkwkrnRRKtkGsELgdIRPjm"+
- "g/Gw9e7odqTklDIXBl0luzI/fdm/IOi+0okEIk5JIBkhgcoTCeT+KgG72XMEphZoyMKABRivRXTwa2jX"+
- "iyzNHLMeq7jH3V8OJ61cxsrcL13eP1gWtrXloe/n3zwOOFfGtSsaaJbBAdT5AQG4loGvbt3alq+g1is0"+
- "JY5185VCIiASgYDdmrEFd3jl1z4Pm/VEW4QIwhfktshuDK+0yBN8KV08vJJRWi1Ty2Y8RB4vmFpGxiaw"+
- "yVzCilMmswlgJ8FjCK3oMzcASyIzAmDFQO5hEF5HPwkk/fVqUA+qcufqJjXZ8/I42YZUZEqASbY4M6GC"+
- "tOtD1huCPD/zAHvDR4pqd189pW/6ktwcbPVORBP89FF/a/qYfZoaS39IMTD6UoYOZk85k4CTad8rNoy7"+
- "n4k0aOQ6IRdl28PaC5lhkntKNor55L3kJazXTzICJO0+AwT9Kb9jgFB1y0pia/n9ZeI6xF+vMO0zxpEB"+
- "N+EaSVXyNvPBL3UBm4mkr78wwP07A14iGZCMrAtcgmIj6wJ61G/1UASfEMkswMxaBYU+TXQdUKakUFVh"+
- "+9avrWhsKCIzAsWj8d6xECiFBIkag/aDqSnQHzvgA+7DVErEMyF/5AB9pWYIaduUwgFB95WPbdJ87bAE"+
- "R6ACXr05cMHP1mnlqLVcd/Rle+WiIt3mYMrY12u7KT0UdVadimBty7bG827X/V866uVHib7w9Az11uxQ"+
- "76EqBPrVFRdL29guCPY45bw1rLRnFiUxMepJdXj2kK38NjNTJeMEToBtADTqWkx2ZvUMTeKr+2FCtrLM"+
- "RWSKT10v6rFHHtocMRHsxejn3gurn1oWHy28NfaUwC+o5GvNvT1ga/CkbqLSZ+0eGE6m5pqX/OOi6l+W"+
- "CPhS7XarmsRCW+ogWsQZ1zB46BJswEDIUnh6cfNhtKZQfuMT4HvQ0vWrnnMHm8BZN3RFU7VV6ku9duC9"+
- "SaLsd9dSqzwMHAD/NgacHob+HgNOB8Cvbe3/ZgDvjwxAxURO4oA+NELE9PojA9DPZMDiCQOmfsMAjH+Q"+
- "AdDvDFD4DQNEfzLgJwP+MwY8biPYj/s7CYHwM6oC2j0/JAQyyxAMGMNNSqFfrHPjEe/pWYlKw4/NAwm2"+
- "N+WGE83nduLUh3zczje7QBIawyLIKG9H+Z5G/Yug24G5hhk3g6AuLnJ9ABHYsPbtixBBpSxLLWIndvaX"+
- "TUm4t4nxveZfvmIaEduMckObOu+WFxVjfEcht96ONnl4+O7FhZiSC+TNCQ5sspWy6HI9pikzsLgdwCWO"+
- "LcFzYZLvRYdPHDDMYmQGfdVjeiDKD96/t/Fcymr12vXLdyOMBzE3rKEvp60+cU6nCsHPu1E6X2iEB46l"+
- "5eLEMsUytIMttCw1NvmKnYs94OqXjeVm5k3pVSLbXEOJLjCT5u2VeVUeD3vY2uxuJPV2W29ZH6d9WyBA"+
- "tLNvxIJx8Hz5iFJlZJgpD367Ap2FkNVWBofAQ4bpE/UQFy1eNv1caD9BojU/dg7SAlil4mxWS6GsV641"+
- "20N8J+6nZhhWaKguL96klsdNuM4VxzsUxzBSqzwq6gQqhCjiDVjLboCvMIH1VTs7nY/8AnxCzimcZAPM"+
- "iK2xHnDJqCGzAZZRKr/LBsRRnM4GpPidzgbEo/+QDXj2JMTKjLXuvv6j1+JfgRzmntj6AiRj4JyCpxDf"+
- "pN2FeoU7UIo+IbsHNTUC7b8y4DfZAPRv2QByiSjm79mA0tr7i4sYNr6ptl/zhmpIRvR0cQp2rsDQQ7vR"+
- "+1tjOt/O7rq0jiZDu5TOjOGMJL/0P10oeCodkMhrgeWU5+s/ihtUMdPYzdQTHrT2Eqqwv2OlrQwv7bg2"+
- "tR5mtqVXYcyJrAxAaJEMcOp/GiJa4Vkd7oNgQJM2ggF+xRCloiJTQTZHBAMa7MmaWF6yJIuujXOknawU"+
- "DPusyFoQOyq9rpwYQn7fZVinYnC3Nkh2kjVZeeux67MbR3V7kfxzuveM99mOPLJcblfq2bxnwTNst7Hd"+
- "b2MEXbjrwnXcn+/bRCpdLeiRkK0JX/E38LaHUGP4kfKtjwW8tLQO231jLhO6rnjzmTYGCvW2NnKlINZh"+
- "cCB/3NETFhXebfFUqfFlHsEwRXIMV4KlQNBDcedVzI8JWS1Cyjr1XIfo/zYInB6I/h4ETofA34IA9EcI"+
- "oGECuhEv3od4K2ctFMQ4EwI/VgYw/0EI8AF+VgZ+QuC/BgGe5ra+P68M/HahoMwL61FJBY0+Mh2QttMI"+
- "JiR4QJLf2TgJOkFCfIuJ1idw2vfLiJn0VFDJY2MfdIKxnb4XPDseUx48Rr3/FAQIhdRlZLnLs2/q8xMq"+
- "WlnVkcFfDpPgzshXk2ZpZ/kytyR8rwy8ElTKzmh6ugv2c5ItUWD5lg7wg7kufK3rpS2J3JguW6KPKiac"+
- "HHsd2cRPfYDLb947Lk7gZ+GC4eHSSZOSpyyjymYYGpldboruhWaJ+Zrv1pBYBZOeDTkx2e3QNJ3kGOWn"+
- "CwNHE0dGW3XVEw22wnyV3ZWHgQtSW1l7Ie3DK+EJ4M1elgNLCROj6Kc9JiPkjwRTa5nZ+DeZIzvhNztc"+
- "IdRh9Gahzn1WMyPAGD5jaeBIGikU2NJljiMZk0iTYQ9qthHvU+HSvpj7Gc5OkB0gnwqWS7wjF2mlx7qW"+
- "ejVIA3zh/jI0yyWUkjiUk83Y+NpxU/P1tlAW8okwvMc8wVD/tkeZbPNX7Z5d6XrKE+5xlgU8v6UEuHpF"+
- "f5MSMOX48rHxlS/uHh8qXt4b0/XNFyz2hQYvJN4p3ajgidFr4ZRfSPNEpSir9y9KDrYOVdO4CW7qdt/K"+
- "+WYBiMi6TViJ81ZbTD33t0UCQOQiARRdLO2m/BbqGy+fo0caYztLvt5inEq5VDSzV+2TRLc0Vn9ne12i"+
- "4lY8ar4nviaKEVyUl4u5tPzLIU0JNEfhE8lZUWw72xT81yoD4mVICkRB6fG/U6DsfynQeUIBLWX30o6a"+
- "qfVQileiZT0plgOsMk1JVdN2CfnpkWQBVrsO532MLkWjW8bOkRKMN3JX12sVVynXye/ds7yIGShNwoNT"+
- "Xq4rH9RlyfEo4WmYXEGsLK6pyocQ0sRtfp2yVpeJCKy30uPKz8NE3gkeTx5h6XziEObeJvWsj6opUHpX"+
- "8xQ7myirkq/lAxH1K0x3m6MMPnT0z1rPCPVfsKmaXnpHCiG43wKLSH2fpttVq3G3Nl4LWyr/SHo+Lwvi"+
- "p9IQmzVDjm0LdSLqeHM8ILiJRsdoNYS93WyEhi7IOdKXZLTCvCLifxTMEi+snNzAtfevk8DpkejvSeB0"+
- "BPza/oPKABD5z4SARKQEELP1WQsFMc+QwP8ATkmhK404AAA=";
-
- byte[] dgBytes = decompress(data);
- List dgRecords = RecordFactory.createRecords(new ByteArrayInputStream(dgBytes));
- assertEquals(14, dgRecords.size());
-
- int[] expectedSids = {
- DrawingRecord.sid, ObjRecord.sid,
- DrawingRecord.sid, ObjRecord.sid,
- DrawingRecord.sid, ObjRecord.sid,
- DrawingRecord.sid, ObjRecord.sid,
- ContinueRecord.sid, ObjRecord.sid,
- ContinueRecord.sid, ObjRecord.sid,
- ContinueRecord.sid, ObjRecord.sid
- };
-
- int[] actualSids = dgRecords.stream().mapToInt(Record::getSid).toArray();
- assertArrayEquals(expectedSids, actualSids, "unexpected record.sid");
-
- DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord());
-
- // create a dummy sheet consisting of our test data
- InternalSheet sheet = InternalSheet.createSheet();
- List records = sheet.getRecords();
- records.clear();
- records.addAll(dgRecords);
- records.add(EOFRecord.instance);
-
- sheet.aggregateDrawingRecords(drawingManager, false);
- assertEquals(2, records.size(), "drawing was not fully aggregated");
- assertTrue(records.get(0) instanceof EscherAggregate, "expected EscherAggregate");
- assertTrue(records.get(1) instanceof EOFRecord, "expected EOFRecord");
-
- EscherAggregate agg = (EscherAggregate) records.get(0);
-
- byte[] dgBytesAfterSave = agg.serialize();
- assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save");
- assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data brefpore and after save is different");
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.java
deleted file mode 100644
index 7dfcd66940..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.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.hssf.model;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.ddf.EscherDgRecord;
-import org.apache.poi.ddf.EscherDggRecord;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-final class TestDrawingManager2 {
- private DrawingManager2 drawingManager2;
- private EscherDggRecord dgg;
-
- @BeforeEach
- void setUp() {
- dgg = new EscherDggRecord();
- dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[0] );
- drawingManager2 = new DrawingManager2( dgg );
- }
-
- @Test
- void testCreateDgRecord() {
- EscherDgRecord dgRecord1 = drawingManager2.createDgRecord();
- assertEquals( 1, dgRecord1.getDrawingGroupId() );
- assertEquals( -1, dgRecord1.getLastMSOSPID() );
-
- EscherDgRecord dgRecord2 = drawingManager2.createDgRecord();
- assertEquals( 2, dgRecord2.getDrawingGroupId() );
- assertEquals( -1, dgRecord2.getLastMSOSPID() );
-
- assertEquals( 2, dgg.getDrawingsSaved( ) );
- assertEquals( 2, dgg.getFileIdClusters().length );
- assertEquals( 3, dgg.getNumIdClusters() );
- assertEquals( 0, dgg.getNumShapesSaved() );
- }
-
- @Test
- void testCreateDgRecordOld() {
- // converted from TestDrawingManager(1)
- EscherDggRecord dgg = new EscherDggRecord();
- dgg.setDrawingsSaved( 0 );
- dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[]{} );
- DrawingManager2 dm = new DrawingManager2( dgg );
-
- EscherDgRecord dgRecord = dm.createDgRecord();
- assertEquals( -1, dgRecord.getLastMSOSPID() );
- assertEquals( 0, dgRecord.getNumShapes() );
- assertEquals( 1, dm.getDgg().getDrawingsSaved() );
- assertEquals( 1, dm.getDgg().getFileIdClusters().length );
- assertEquals( 1, dm.getDgg().getFileIdClusters()[0].getDrawingGroupId() );
- assertEquals( 0, dm.getDgg().getFileIdClusters()[0].getNumShapeIdsUsed() );
- }
-
- @Test
- void testAllocateShapeId() {
- EscherDgRecord dgRecord1 = drawingManager2.createDgRecord();
- assertEquals( 1, dgg.getDrawingsSaved() );
- EscherDgRecord dgRecord2 = drawingManager2.createDgRecord();
- assertEquals( 2, dgg.getDrawingsSaved() );
-
- assertEquals( 1024, drawingManager2.allocateShapeId( dgRecord1 ) );
- assertEquals( 1024, dgRecord1.getLastMSOSPID() );
- assertEquals( 1025, dgg.getShapeIdMax() );
- assertEquals( 1, dgg.getFileIdClusters()[0].getDrawingGroupId() );
- assertEquals( 1, dgg.getFileIdClusters()[0].getNumShapeIdsUsed() );
- assertEquals( 1, dgRecord1.getNumShapes() );
- assertEquals( 1025, drawingManager2.allocateShapeId( dgRecord1 ) );
- assertEquals( 1025, dgRecord1.getLastMSOSPID() );
- assertEquals( 1026, dgg.getShapeIdMax() );
- assertEquals( 1026, drawingManager2.allocateShapeId( dgRecord1 ) );
- assertEquals( 1026, dgRecord1.getLastMSOSPID() );
- assertEquals( 1027, dgg.getShapeIdMax() );
- assertEquals( 2048, drawingManager2.allocateShapeId( dgRecord2 ) );
- assertEquals( 2048, dgRecord2.getLastMSOSPID() );
- assertEquals( 2049, dgg.getShapeIdMax() );
-
- for (int i = 0; i < 1021; i++)
- {
- drawingManager2.allocateShapeId( dgRecord1 );
- assertEquals( 2049, dgg.getShapeIdMax() );
- }
- assertEquals( 3072, drawingManager2.allocateShapeId( dgRecord1 ) );
- assertEquals( 3073, dgg.getShapeIdMax() );
-
- assertEquals( 2, dgg.getDrawingsSaved() );
- assertEquals( 4, dgg.getNumIdClusters() );
- assertEquals( 1026, dgg.getNumShapesSaved() );
- }
-
- @Test
- void testFindNewDrawingGroupId() {
- // converted from TestDrawingManager(1)
- EscherDggRecord dgg = new EscherDggRecord();
- dgg.setDrawingsSaved( 1 );
- dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[]{
- new EscherDggRecord.FileIdCluster( 2, 10 )} );
- DrawingManager2 dm = new DrawingManager2( dgg );
- assertEquals( 1, dm.findNewDrawingGroupId() );
- dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[]{
- new EscherDggRecord.FileIdCluster( 1, 10 ),
- new EscherDggRecord.FileIdCluster( 2, 10 )} );
- assertEquals( 3, dm.findNewDrawingGroupId() );
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java
deleted file mode 100644
index 22cd1ee11c..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java
+++ /dev/null
@@ -1,853 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.model;
-
-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.assertTrue;
-
-import java.io.IOException;
-import java.util.List;
-
-import org.apache.poi.ddf.EscherBoolProperty;
-import org.apache.poi.ddf.EscherContainerRecord;
-import org.apache.poi.ddf.EscherDgRecord;
-import org.apache.poi.ddf.EscherOptRecord;
-import org.apache.poi.ddf.EscherProperty;
-import org.apache.poi.ddf.EscherPropertyTypes;
-import org.apache.poi.ddf.EscherRecord;
-import org.apache.poi.ddf.EscherSimpleProperty;
-import org.apache.poi.ddf.EscherSpRecord;
-import org.apache.poi.ddf.EscherTextboxRecord;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.CommonObjectDataSubRecord;
-import org.apache.poi.hssf.record.EscherAggregate;
-import org.apache.poi.hssf.record.ObjRecord;
-import org.apache.poi.hssf.usermodel.HSSFAnchor;
-import org.apache.poi.hssf.usermodel.HSSFChildAnchor;
-import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
-import org.apache.poi.hssf.usermodel.HSSFComment;
-import org.apache.poi.hssf.usermodel.HSSFPatriarch;
-import org.apache.poi.hssf.usermodel.HSSFPicture;
-import org.apache.poi.hssf.usermodel.HSSFPolygon;
-import org.apache.poi.hssf.usermodel.HSSFRichTextString;
-import org.apache.poi.hssf.usermodel.HSSFShape;
-import org.apache.poi.hssf.usermodel.HSSFShapeGroup;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFSimpleShape;
-import org.apache.poi.hssf.usermodel.HSSFTestHelper;
-import org.apache.poi.hssf.usermodel.HSSFTextbox;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.util.HexDump;
-import org.junit.jupiter.api.Test;
-
-
-/**
- * Test escher drawing
- *
- * optionally the system setting "poi.deserialize.escher" can be set to {@code true}
- */
-class TestDrawingShapes {
- /**
- * HSSFShape tree bust be built correctly
- * Check file with such records structure:
- * -patriarch
- * --shape
- * --group
- * ---group
- * ----shape
- * ----shape
- * ---shape
- * ---group
- * ----shape
- * ----shape
- */
- @Test
- void testDrawingGroups() throws IOException {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls");
- HSSFSheet sheet = wb.getSheet("groups");
- HSSFPatriarch patriarch = sheet.getDrawingPatriarch();
- assertEquals(patriarch.getChildren().size(), 2);
- HSSFShapeGroup group = (HSSFShapeGroup) patriarch.getChildren().get(1);
- assertEquals(3, group.getChildren().size());
- HSSFShapeGroup group1 = (HSSFShapeGroup) group.getChildren().get(0);
- assertEquals(2, group1.getChildren().size());
- group1 = (HSSFShapeGroup) group.getChildren().get(2);
- assertEquals(2, group1.getChildren().size());
- wb.close();
- }
-
- @Test
- void testHSSFShapeCompatibility() {
- HSSFSimpleShape shape = new HSSFSimpleShape(null, new HSSFClientAnchor());
- shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
- assertEquals(0x08000040, shape.getLineStyleColor());
- assertEquals(0x08000009, shape.getFillColor());
- assertEquals(HSSFShape.LINEWIDTH_DEFAULT, shape.getLineWidth());
- assertEquals(HSSFShape.LINESTYLE_SOLID, shape.getLineStyle());
- assertFalse(shape.isNoFill());
-
- EscherOptRecord opt = shape.getOptRecord();
-
- assertEquals(7, opt.getEscherProperties().size());
- assertNotEquals(((EscherSimpleProperty) opt.lookup(EscherPropertyTypes.GROUPSHAPE__FLAGS)).getPropertyValue(), 0);
- assertTrue(((EscherBoolProperty) opt.lookup(EscherPropertyTypes.LINESTYLE__NOLINEDRAWDASH)).isTrue());
- assertEquals(0x00000004, ((EscherSimpleProperty) opt.lookup(EscherPropertyTypes.GEOMETRY__SHAPEPATH)).getPropertyValue());
- assertNull(opt.lookup(EscherPropertyTypes.TEXT__SIZE_TEXT_TO_FIT_SHAPE));
- }
-
- @Test
- void testDefaultPictureSettings() {
- HSSFPicture picture = new HSSFPicture(null, new HSSFClientAnchor());
- assertEquals(picture.getLineWidth(), HSSFShape.LINEWIDTH_DEFAULT);
- assertEquals(picture.getFillColor(), HSSFShape.FILL__FILLCOLOR_DEFAULT);
- assertEquals(picture.getLineStyle(), HSSFShape.LINESTYLE_NONE);
- assertEquals(picture.getLineStyleColor(), HSSFShape.LINESTYLE__COLOR_DEFAULT);
- assertFalse(picture.isNoFill());
- assertEquals(picture.getPictureIndex(), -1);//not set yet
- }
-
- /**
- * No NullPointerException should appear
- */
- @Test
- void testDefaultSettingsWithEmptyContainer() {
- EscherContainerRecord container = new EscherContainerRecord();
- EscherOptRecord opt = new EscherOptRecord();
- opt.setRecordId(EscherOptRecord.RECORD_ID);
- container.addChildRecord(opt);
- ObjRecord obj = new ObjRecord();
- CommonObjectDataSubRecord cod = new CommonObjectDataSubRecord();
- cod.setObjectType(HSSFSimpleShape.OBJECT_TYPE_PICTURE);
- obj.addSubRecord(cod);
- HSSFPicture picture = new HSSFPicture(container, obj);
-
- assertEquals(picture.getLineWidth(), HSSFShape.LINEWIDTH_DEFAULT);
- assertEquals(picture.getFillColor(), HSSFShape.FILL__FILLCOLOR_DEFAULT);
- assertEquals(picture.getLineStyle(), HSSFShape.LINESTYLE_DEFAULT);
- assertEquals(picture.getLineStyleColor(), HSSFShape.LINESTYLE__COLOR_DEFAULT);
- assertEquals(picture.isNoFill(), HSSFShape.NO_FILL_DEFAULT);
- assertEquals(picture.getPictureIndex(), -1);//not set yet
- }
-
- /**
- * create a rectangle, save the workbook, read back and verify that all shape properties are there
- */
- @Test
- void testReadWriteRectangle() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet();
-
- HSSFPatriarch drawing = sheet.createDrawingPatriarch();
- HSSFClientAnchor anchor = new HSSFClientAnchor(10, 10, 50, 50, (short) 2, 2, (short) 4, 4);
- anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE);
- assertEquals(AnchorType.MOVE_DONT_RESIZE, anchor.getAnchorType());
- anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE);
- assertEquals(AnchorType.MOVE_DONT_RESIZE, anchor.getAnchorType());
-
- HSSFSimpleShape rectangle = drawing.createSimpleShape(anchor);
- rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE);
- rectangle.setLineWidth(10000);
- rectangle.setFillColor(777);
- assertEquals(rectangle.getFillColor(), 777);
- assertEquals(10000, rectangle.getLineWidth());
- rectangle.setLineStyle(10);
- assertEquals(10, rectangle.getLineStyle());
- assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_SQUARE);
- rectangle.setLineStyleColor(1111);
- rectangle.setNoFill(true);
- rectangle.setWrapText(HSSFSimpleShape.WRAP_NONE);
- rectangle.setString(new HSSFRichTextString("teeeest"));
- assertEquals(rectangle.getLineStyleColor(), 1111);
- EscherContainerRecord escherContainer = HSSFTestHelper.getEscherContainer(rectangle);
- assertNotNull(escherContainer);
- EscherRecord childById = escherContainer.getChildById(EscherOptRecord.RECORD_ID);
- assertNotNull(childById);
- EscherProperty lookup = ((EscherOptRecord) childById).lookup(EscherPropertyTypes.TEXT__TEXTID);
- assertNotNull(lookup);
- assertEquals(((EscherSimpleProperty) lookup).getPropertyValue(), "teeeest".hashCode());
- assertTrue(rectangle.isNoFill());
- assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_NONE);
- assertEquals(rectangle.getString().getString(), "teeeest");
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- drawing = sheet.getDrawingPatriarch();
- assertEquals(1, drawing.getChildren().size());
-
- HSSFSimpleShape rectangle2 =
- (HSSFSimpleShape) drawing.getChildren().get(0);
- assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE,
- rectangle2.getShapeType());
- assertEquals(10000, rectangle2.getLineWidth());
- assertEquals(10, rectangle2.getLineStyle());
- assertEquals(anchor, rectangle2.getAnchor());
- assertEquals(rectangle2.getLineStyleColor(), 1111);
- assertEquals(rectangle2.getFillColor(), 777);
- assertTrue(rectangle2.isNoFill());
- assertEquals(rectangle2.getString().getString(), "teeeest");
- assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_NONE);
-
- rectangle2.setFillColor(3333);
- rectangle2.setLineStyle(9);
- rectangle2.setLineStyleColor(4444);
- rectangle2.setNoFill(false);
- rectangle2.setLineWidth(77);
- rectangle2.getAnchor().setDx1(2);
- rectangle2.getAnchor().setDx2(3);
- rectangle2.getAnchor().setDy1(4);
- rectangle2.getAnchor().setDy2(5);
- rectangle.setWrapText(HSSFSimpleShape.WRAP_BY_POINTS);
- rectangle2.setString(new HSSFRichTextString("test22"));
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sheet = wb3.getSheetAt(0);
- drawing = sheet.getDrawingPatriarch();
- assertEquals(1, drawing.getChildren().size());
- rectangle2 = (HSSFSimpleShape) drawing.getChildren().get(0);
- assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, rectangle2.getShapeType());
- assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_BY_POINTS);
- assertEquals(77, rectangle2.getLineWidth());
- assertEquals(9, rectangle2.getLineStyle());
- assertEquals(rectangle2.getLineStyleColor(), 4444);
- assertEquals(rectangle2.getFillColor(), 3333);
- assertEquals(rectangle2.getAnchor().getDx1(), 2);
- assertEquals(rectangle2.getAnchor().getDx2(), 3);
- assertEquals(rectangle2.getAnchor().getDy1(), 4);
- assertEquals(rectangle2.getAnchor().getDy2(), 5);
- assertFalse(rectangle2.isNoFill());
- assertEquals(rectangle2.getString().getString(), "test22");
-
- HSSFSimpleShape rect3 = drawing.createSimpleShape(new HSSFClientAnchor());
- rect3.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE);
- HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3);
- wb3.close();
-
- drawing = wb4.getSheetAt(0).getDrawingPatriarch();
- assertEquals(drawing.getChildren().size(), 2);
- wb4.close();
- }
-
- @Test
- void testReadExistingImage() throws IOException {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls");
- HSSFSheet sheet = wb.getSheet("pictures");
- HSSFPatriarch drawing = sheet.getDrawingPatriarch();
- assertEquals(1, drawing.getChildren().size());
- HSSFPicture picture = (HSSFPicture) drawing.getChildren().get(0);
-
- assertEquals(picture.getPictureIndex(), 2);
- assertEquals(picture.getLineStyleColor(), HSSFShape.LINESTYLE__COLOR_DEFAULT);
- assertEquals(picture.getFillColor(), 0x5DC943);
- assertEquals(picture.getLineWidth(), HSSFShape.LINEWIDTH_DEFAULT);
- assertEquals(picture.getLineStyle(), HSSFShape.LINESTYLE_DEFAULT);
- assertFalse(picture.isNoFill());
-
- picture.setPictureIndex(2);
- assertEquals(picture.getPictureIndex(), 2);
- wb.close();
- }
-
-
- /* assert shape properties when reading shapes from a existing workbook */
- @Test
- void testReadExistingRectangle() throws IOException {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls");
- HSSFSheet sheet = wb.getSheet("rectangles");
- HSSFPatriarch drawing = sheet.getDrawingPatriarch();
- assertEquals(1, drawing.getChildren().size());
-
- HSSFSimpleShape shape = (HSSFSimpleShape) drawing.getChildren().get(0);
- assertFalse(shape.isNoFill());
- assertEquals(shape.getLineStyle(), HSSFShape.LINESTYLE_DASHDOTGEL);
- assertEquals(shape.getLineStyleColor(), 0x616161);
- assertEquals(shape.getFillColor(), 0x2CE03D, HexDump.toHex(shape.getFillColor()));
- assertEquals(shape.getLineWidth(), HSSFShape.LINEWIDTH_ONE_PT * 2);
- assertEquals(shape.getString().getString(), "POItest");
- assertEquals(shape.getRotationDegree(), 27);
- wb.close();
- }
-
- @Test
- void testShapeIds() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet1 = wb1.createSheet();
- HSSFPatriarch patriarch1 = sheet1.createDrawingPatriarch();
- for (int i = 0; i < 2; i++) {
- patriarch1.createSimpleShape(new HSSFClientAnchor());
- }
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet1 = wb2.getSheetAt(0);
- patriarch1 = sheet1.getDrawingPatriarch();
-
- EscherAggregate agg1 = HSSFTestHelper.getEscherAggregate(patriarch1);
- // last shape ID cached in EscherDgRecord
- EscherDgRecord dg1 = agg1.getEscherContainer().getChildById(EscherDgRecord.RECORD_ID);
- assertNotNull(dg1);
- assertEquals(1026, dg1.getLastMSOSPID());
-
- // iterate over shapes and check shapeId
- EscherContainerRecord spgrContainer =
- agg1.getEscherContainer().getChildContainers().get(0);
- // root spContainer + 2 spContainers for shapes
- assertEquals(3, spgrContainer.getChildCount());
-
- EscherSpRecord sp0 =
- ((EscherContainerRecord) spgrContainer.getChild(0)).getChildById(EscherSpRecord.RECORD_ID);
- assertNotNull(sp0);
- assertEquals(1024, sp0.getShapeId());
-
- EscherSpRecord sp1 =
- ((EscherContainerRecord) spgrContainer.getChild(1)).getChildById(EscherSpRecord.RECORD_ID);
- assertNotNull(sp1);
- assertEquals(1025, sp1.getShapeId());
-
- EscherSpRecord sp2 =
- ((EscherContainerRecord) spgrContainer.getChild(2)).getChildById(EscherSpRecord.RECORD_ID);
- assertNotNull(sp2);
- assertEquals(1026, sp2.getShapeId());
- wb2.close();
- }
-
- /**
- * Test get new id for shapes from existing file
- * File already have for 1 shape on each sheet, because document must contain EscherDgRecord for each sheet
- */
- @Test
- void testAllocateNewIds() throws IOException {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("empty.xls");
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFPatriarch patriarch = sheet.getDrawingPatriarch();
-
- // 2048 - main SpContainer id
- // 2049 - existing shape id
- assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 2050);
- assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 2051);
- assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 2052);
-
- sheet = wb.getSheetAt(1);
- patriarch = sheet.getDrawingPatriarch();
-
- // 3072 - main SpContainer id
- // 3073 - existing shape id
- assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 3074);
- assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 3075);
- assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 3076);
-
-
- sheet = wb.getSheetAt(2);
- patriarch = sheet.getDrawingPatriarch();
-
- assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1026);
- assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1027);
- assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1028);
- wb.close();
- }
-
- @Test
- void testOpt() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- // create a sheet with a text box
- HSSFSheet sheet = wb.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor());
- EscherOptRecord opt1 = HSSFTestHelper.getOptRecord(textbox);
- EscherOptRecord opt2 = HSSFTestHelper.getEscherContainer(textbox).getChildById(EscherOptRecord.RECORD_ID);
- assertSame(opt1, opt2);
- wb.close();
- }
-
- @Test
- void testCorrectOrderInOptRecord() throws IOException{
- HSSFWorkbook wb = new HSSFWorkbook();
-
- HSSFSheet sheet = wb.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor());
- EscherOptRecord opt = HSSFTestHelper.getOptRecord(textbox);
-
- String opt1Str = opt.toXml();
-
- textbox.setFillColor(textbox.getFillColor());
- EscherContainerRecord container = HSSFTestHelper.getEscherContainer(textbox);
- EscherOptRecord optRecord = container.getChildById(EscherOptRecord.RECORD_ID);
- assertNotNull(optRecord);
- assertEquals(opt1Str, optRecord.toXml());
- textbox.setLineStyle(textbox.getLineStyle());
- assertEquals(opt1Str, optRecord.toXml());
- textbox.setLineWidth(textbox.getLineWidth());
- assertEquals(opt1Str, optRecord.toXml());
- textbox.setLineStyleColor(textbox.getLineStyleColor());
- assertEquals(opt1Str, optRecord.toXml());
- wb.close();
- }
-
- @Test
- void testDgRecordNumShapes() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- EscherAggregate aggregate = HSSFTestHelper.getEscherAggregate(patriarch);
- EscherDgRecord dgRecord = (EscherDgRecord) aggregate.getEscherRecord(0).getChild(0);
- assertEquals(dgRecord.getNumShapes(), 1);
- wb.close();
- }
-
- @Test
- void testTextForSimpleShape() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- HSSFSimpleShape shape = patriarch.createSimpleShape(new HSSFClientAnchor());
- shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE);
-
- EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch);
- assertEquals(agg.getShapeToObjMapping().size(), 2);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- shape = (HSSFSimpleShape) patriarch.getChildren().get(0);
-
- agg = HSSFTestHelper.getEscherAggregate(patriarch);
- assertEquals(agg.getShapeToObjMapping().size(), 2);
-
- shape.setString(new HSSFRichTextString("string1"));
- assertEquals(shape.getString().getString(), "string1");
-
- assertNotNull(HSSFTestHelper.getEscherContainer(shape).getChildById(EscherTextboxRecord.RECORD_ID));
- assertEquals(agg.getShapeToObjMapping().size(), 2);
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
-
- HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3);
- wb3.close();
- sheet = wb4.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- shape = (HSSFSimpleShape) patriarch.getChildren().get(0);
-
- assertNotNull(HSSFTestHelper.getTextObjRecord(shape));
- assertEquals(shape.getString().getString(), "string1");
- assertNotNull(HSSFTestHelper.getEscherContainer(shape).getChildById(EscherTextboxRecord.RECORD_ID));
- assertEquals(agg.getShapeToObjMapping().size(), 2);
- wb4.close();
- }
-
- @Test
- void testRemoveShapes() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor());
- rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE);
-
- int idx = wb1.addPicture(new byte[]{1,2,3}, Workbook.PICTURE_TYPE_JPEG);
- patriarch.createPicture(new HSSFClientAnchor(), idx);
-
- patriarch.createCellComment(new HSSFClientAnchor());
-
- HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor());
- polygon.setPoints(new int[]{1,2}, new int[]{2,3});
-
- patriarch.createTextbox(new HSSFClientAnchor());
-
- HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor());
- group.createTextbox(new HSSFChildAnchor());
- group.createPicture(new HSSFChildAnchor(), idx);
-
- assertEquals(patriarch.getChildren().size(), 6);
- assertEquals(group.getChildren().size(), 2);
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
-
- assertEquals(patriarch.getChildren().size(), 6);
-
- group = (HSSFShapeGroup) patriarch.getChildren().get(5);
- group.removeShape(group.getChildren().get(0));
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sheet = wb3.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
-
- group = (HSSFShapeGroup) patriarch.getChildren().get(5);
- patriarch.removeShape(group);
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
-
- HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3);
- wb3.close();
- sheet = wb4.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 5);
-
- HSSFShape shape = patriarch.getChildren().get(0);
- patriarch.removeShape(shape);
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 4);
-
- HSSFWorkbook wb5 = HSSFTestDataSamples.writeOutAndReadBack(wb4);
- wb4.close();
- sheet = wb5.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 4);
-
- HSSFPicture picture = (HSSFPicture) patriarch.getChildren().get(0);
- patriarch.removeShape(picture);
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 3);
-
- HSSFWorkbook wb6 = HSSFTestDataSamples.writeOutAndReadBack(wb5);
- wb5.close();
- sheet = wb6.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 3);
-
- HSSFComment comment = (HSSFComment) patriarch.getChildren().get(0);
- patriarch.removeShape(comment);
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 2);
-
- HSSFWorkbook wb7 = HSSFTestDataSamples.writeOutAndReadBack(wb6);
- wb6.close();
- sheet = wb7.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 2);
-
- polygon = (HSSFPolygon) patriarch.getChildren().get(0);
- patriarch.removeShape(polygon);
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 1);
-
- HSSFWorkbook wb8 = HSSFTestDataSamples.writeOutAndReadBack(wb7);
- wb7.close();
- sheet = wb8.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 1);
-
- HSSFTextbox textbox = (HSSFTextbox) patriarch.getChildren().get(0);
- patriarch.removeShape(textbox);
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 0);
-
- HSSFWorkbook wb9 = HSSFTestDataSamples.writeOutAndReadBack(wb8);
- wb8.close();
- sheet = wb9.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 0);
- wb9.close();
- }
-
- @Test
- void testShapeFlip() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor());
- rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE);
-
- assertFalse(rectangle.isFlipVertical());
- assertFalse(rectangle.isFlipHorizontal());
-
- rectangle.setFlipVertical(true);
- assertTrue(rectangle.isFlipVertical());
- rectangle.setFlipHorizontal(true);
- assertTrue(rectangle.isFlipHorizontal());
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0);
-
- assertTrue(rectangle.isFlipHorizontal());
- rectangle.setFlipHorizontal(false);
- assertFalse(rectangle.isFlipHorizontal());
-
- assertTrue(rectangle.isFlipVertical());
- rectangle.setFlipVertical(false);
- assertFalse(rectangle.isFlipVertical());
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sheet = wb3.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0);
-
- assertFalse(rectangle.isFlipVertical());
- assertFalse(rectangle.isFlipHorizontal());
- wb3.close();
- }
-
- @Test
- void testRotation() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor(0,0,100,100, (short) 0,0,(short)5,5));
- rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE);
-
- assertEquals(rectangle.getRotationDegree(), 0);
- rectangle.setRotationDegree((short) 45);
- assertEquals(rectangle.getRotationDegree(), 45);
- rectangle.setFlipHorizontal(true);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
- rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0);
- assertEquals(rectangle.getRotationDegree(), 45);
- rectangle.setRotationDegree((short) 30);
- assertEquals(rectangle.getRotationDegree(), 30);
-
- patriarch.setCoordinates(0, 0, 10, 10);
- rectangle.setString(new HSSFRichTextString("1234"));
- wb2.close();
- }
-
- @SuppressWarnings("unused")
- @Test
- void testShapeContainerImplementsIterable() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- HSSFSheet sheet = wb.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- patriarch.createSimpleShape(new HSSFClientAnchor());
- patriarch.createSimpleShape(new HSSFClientAnchor());
-
- int i=2;
-
- for (HSSFShape shape: patriarch){
- i--;
- }
- assertEquals(i, 0);
- wb.close();
- }
-
- @Test
- void testClearShapesForPatriarch() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- patriarch.createSimpleShape(new HSSFClientAnchor());
- patriarch.createSimpleShape(new HSSFClientAnchor());
- patriarch.createCellComment(new HSSFClientAnchor());
-
- EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch);
-
- assertEquals(agg.getShapeToObjMapping().size(), 6);
- assertEquals(agg.getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 3);
-
- patriarch.clear();
-
- assertEquals(agg.getShapeToObjMapping().size(), 0);
- assertEquals(agg.getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 0);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- assertEquals(agg.getShapeToObjMapping().size(), 0);
- assertEquals(agg.getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 0);
- wb2.close();
- }
-
- @Test
- void testBug45312() throws Exception {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- {
- HSSFClientAnchor a1 = new HSSFClientAnchor();
- a1.setAnchor( (short)1, 1, 0, 0, (short) 1, 1, 512, 100);
- HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1);
- shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
- }
- {
- HSSFClientAnchor a1 = new HSSFClientAnchor();
- a1.setAnchor( (short)1, 1, 512, 0, (short) 1, 1, 1024, 100);
- HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1);
- shape1.setFlipVertical(true);
- shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
- }
-
- {
- HSSFClientAnchor a1 = new HSSFClientAnchor();
- a1.setAnchor( (short)2, 2, 0, 0, (short) 2, 2, 512, 100);
- HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1);
- shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
- }
- {
- HSSFClientAnchor a1 = new HSSFClientAnchor();
- a1.setAnchor( (short)2, 2, 0, 100, (short) 2, 2, 512, 200);
- HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1);
- shape1.setFlipHorizontal(true);
- shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
- }
-
- checkWorkbookBack(wb);
- }
- }
-
- private void checkWorkbookBack(HSSFWorkbook wb) throws IOException {
- HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
- assertNotNull(wbBack);
-
- HSSFSheet sheetBack = wbBack.getSheetAt(0);
- assertNotNull(sheetBack);
-
- HSSFPatriarch patriarchBack = sheetBack.getDrawingPatriarch();
- assertNotNull(patriarchBack);
-
- List children = patriarchBack.getChildren();
- assertEquals(4, children.size());
- HSSFShape hssfShape = children.get(0);
- assertTrue(hssfShape instanceof HSSFSimpleShape);
- HSSFAnchor anchor = hssfShape.getAnchor();
- assertTrue(anchor instanceof HSSFClientAnchor);
- assertEquals(0, anchor.getDx1());
- assertEquals(512, anchor.getDx2());
- assertEquals(0, anchor.getDy1());
- assertEquals(100, anchor.getDy2());
- HSSFClientAnchor cAnchor = (HSSFClientAnchor) anchor;
- assertEquals(1, cAnchor.getCol1());
- assertEquals(1, cAnchor.getCol2());
- assertEquals(1, cAnchor.getRow1());
- assertEquals(1, cAnchor.getRow2());
-
- hssfShape = children.get(1);
- assertTrue(hssfShape instanceof HSSFSimpleShape);
- anchor = hssfShape.getAnchor();
- assertTrue(anchor instanceof HSSFClientAnchor);
- assertEquals(512, anchor.getDx1());
- assertEquals(1024, anchor.getDx2());
- assertEquals(0, anchor.getDy1());
- assertEquals(100, anchor.getDy2());
- cAnchor = (HSSFClientAnchor) anchor;
- assertEquals(1, cAnchor.getCol1());
- assertEquals(1, cAnchor.getCol2());
- assertEquals(1, cAnchor.getRow1());
- assertEquals(1, cAnchor.getRow2());
-
- hssfShape = children.get(2);
- assertTrue(hssfShape instanceof HSSFSimpleShape);
- anchor = hssfShape.getAnchor();
- assertTrue(anchor instanceof HSSFClientAnchor);
- assertEquals(0, anchor.getDx1());
- assertEquals(512, anchor.getDx2());
- assertEquals(0, anchor.getDy1());
- assertEquals(100, anchor.getDy2());
- cAnchor = (HSSFClientAnchor) anchor;
- assertEquals(2, cAnchor.getCol1());
- assertEquals(2, cAnchor.getCol2());
- assertEquals(2, cAnchor.getRow1());
- assertEquals(2, cAnchor.getRow2());
-
- hssfShape = children.get(3);
- assertTrue(hssfShape instanceof HSSFSimpleShape);
- anchor = hssfShape.getAnchor();
- assertTrue(anchor instanceof HSSFClientAnchor);
- assertEquals(0, anchor.getDx1());
- assertEquals(512, anchor.getDx2());
- assertEquals(100, anchor.getDy1());
- assertEquals(200, anchor.getDy2());
- cAnchor = (HSSFClientAnchor) anchor;
- assertEquals(2, cAnchor.getCol1());
- assertEquals(2, cAnchor.getCol2());
- assertEquals(2, cAnchor.getRow1());
- assertEquals(2, cAnchor.getRow2());
-
- wbBack.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.java b/src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.java
deleted file mode 100644
index efd3f5feff..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.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.hssf.model;
-
-import static org.apache.poi.ddf.DefaultEscherRecordFactory.isContainer;
-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 java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.List;
-import java.util.Random;
-
-import org.apache.poi.ddf.EscherContainerRecord;
-import org.apache.poi.ddf.EscherTextboxRecord;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.EscherAggregate;
-import org.apache.poi.hssf.record.Record;
-import org.apache.poi.hssf.record.RecordBase;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFTestHelper;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.junit.jupiter.api.Test;
-
-class TestEscherRecordFactory {
-
- private static byte[] toByteArray(List records) {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- for (RecordBase rb : records) {
- Record r = (org.apache.poi.hssf.record.Record) rb;
- try {
- out.write(r.serialize());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return out.toByteArray();
- }
-
- @Test
- void testDetectContainer() {
- Random rnd = new Random();
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.DG_CONTAINER));
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.SOLVER_CONTAINER));
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.SP_CONTAINER));
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.DGG_CONTAINER));
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.BSTORE_CONTAINER));
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.SPGR_CONTAINER));
-
- for (short i=EscherContainerRecord.DGG_CONTAINER; i<= EscherContainerRecord.SOLVER_CONTAINER; i++){
- assertTrue(isContainer(Integer.valueOf(rnd.nextInt(Short.MAX_VALUE)).shortValue(), i));
- }
-
- assertFalse(isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue()));
- assertFalse(isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.SOLVER_CONTAINER + 1).shortValue()));
-
- assertTrue(isContainer((short) 0x000F, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue()));
- assertTrue(isContainer((short) 0xFFFF, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue()));
- assertFalse(isContainer((short) 0x000C, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue()));
- assertFalse(isContainer((short) 0xCCCC, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue()));
- assertFalse(isContainer((short) 0x000F, EscherTextboxRecord.RECORD_ID));
- assertFalse(isContainer((short) 0xCCCC, EscherTextboxRecord.RECORD_ID));
- }
-
- @Test
- void testDgContainerMustBeRootOfHSSFSheetEscherRecords() {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("47251.xls");
- HSSFSheet sh = wb.getSheetAt(0);
- InternalSheet ish = HSSFTestHelper.getSheetForTest(sh);
- List records = ish.getRecords();
- // records to be aggregated
- List dgRecords = records.subList(19, 23);
- byte[] dgBytes = toByteArray(dgRecords);
- sh.getDrawingPatriarch();
- EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid);
- assertNotNull(agg);
- assertTrue(agg.getEscherRecords().get(0) instanceof EscherContainerRecord);
- assertEquals(EscherContainerRecord.DG_CONTAINER, agg.getEscherRecords().get(0).getRecordId());
- assertEquals((short) 0x0, agg.getEscherRecords().get(0).getOptions());
- agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid);
- assertNotNull(agg);
- byte[] dgBytesAfterSave = agg.serialize();
- assertEquals(dgBytes.length, dgBytesAfterSave.length, "different size of drawing data before and after save");
- assertArrayEquals(dgBytes, dgBytesAfterSave, "drawing data before and after save is different");
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java
deleted file mode 100644
index 0e8964daee..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java
+++ /dev/null
@@ -1,1581 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.model;
-
-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.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import java.io.IOException;
-import java.util.Locale;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.NameRecord;
-import org.apache.poi.hssf.record.common.UnicodeString;
-import org.apache.poi.hssf.usermodel.FormulaExtractor;
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
-import org.apache.poi.hssf.usermodel.HSSFName;
-import org.apache.poi.hssf.usermodel.HSSFRow;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.hssf.usermodel.TestHSSFName;
-import org.apache.poi.ss.formula.FormulaParseException;
-import org.apache.poi.ss.formula.FormulaParser;
-import org.apache.poi.ss.formula.FormulaType;
-import org.apache.poi.ss.formula.constant.ErrorConstant;
-import org.apache.poi.ss.formula.ptg.*;
-import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues;
-import org.apache.poi.ss.usermodel.FormulaError;
-import org.apache.poi.ss.usermodel.FormulaEvaluator;
-import org.apache.poi.ss.usermodel.Name;
-import org.apache.poi.util.HexRead;
-import org.apache.poi.util.LittleEndianByteArrayInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test the low level formula parser functionality. High level tests are to
- * be done via usermodel/HSSFCell.setFormulaValue().
- */
-final class TestFormulaParser {
-
- /**
- * @return parsed token array already confirmed not null
- */
- /* package */ static Ptg[] parseFormula(String formula) {
- Ptg[] result = HSSFFormulaParser.parse(formula, null);
- assertNotNull(result, "Ptg array should not be null");
- return result;
- }
- private static String toFormulaString(Ptg[] ptgs) {
- return HSSFFormulaParser.toFormulaString(null, ptgs);
- }
-
- @Test
- void testSimpleFormula() {
- confirmTokenClasses("2+2",IntPtg.class, IntPtg.class, AddPtg.class);
- }
-
- @Test
- void testFormulaWithSpace1() {
- confirmTokenClasses(" 2 + 2 ",IntPtg.class, IntPtg.class, AddPtg.class);
- }
-
- @Test
- void testFormulaWithSpace2() {
- Ptg[] ptgs = parseFormula("2+ sum( 3 , 4) ");
- assertEquals(5, ptgs.length);
- }
-
- @Test
- void testFormulaWithSpaceNRef() {
- Ptg[] ptgs = parseFormula("sum( A2:A3 )");
- assertEquals(2, ptgs.length);
- }
-
- @Test
- void testFormulaWithString() {
- Ptg[] ptgs = parseFormula("\"hello\" & \"world\" ");
- assertEquals(3, ptgs.length);
- }
-
- @Test
- void testTRUE() {
- Ptg[] ptgs = parseFormula("TRUE");
- assertEquals(1, ptgs.length);
- BoolPtg flag = (BoolPtg) ptgs[0];
- assertTrue(flag.getValue());
- }
-
- @Test
- void testSumIf() {
- Ptg[] ptgs = parseFormula("SUMIF(A1:A5,\">4000\",B1:B5)");
- assertEquals(4, ptgs.length);
- }
-
- /**
- * Bug Reported by xt-jens.riis@nokia.com (Jens Riis)
- * Refers to Bug #17582
- *
- */
- @Test
- void testNonAlphaFormula() {
- Ptg[] ptgs = parseFormula("\"TOTAL[\"&F3&\"]\"");
- confirmTokenClasses(ptgs, StringPtg.class, RefPtg.class, ConcatPtg.class, StringPtg.class, ConcatPtg.class);
- assertEquals("TOTAL[", ((StringPtg)ptgs[0]).getValue());
- }
-
- @Test
- void testMacroFunction() throws IOException {
- // testNames.xls contains a VB function called 'myFunc'
- final String testFile = "testNames.xls";
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(testFile)) {
- HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(wb);
-
- //Expected ptg stack: [NamePtg(myFunc), StringPtg(arg), (additional operands go here...), FunctionPtg(myFunc)]
- Ptg[] ptg = FormulaParser.parse("myFunc(\"arg\")", book, FormulaType.CELL, -1);
- assertEquals(3, ptg.length);
-
- // the name gets encoded as the first operand on the stack
- NamePtg tname = (NamePtg) ptg[0];
- assertEquals("myFunc", tname.toFormulaString(book));
-
- // 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]; //FuncVarPtg
- assertTrue(tfunc.isExternalFunction());
-
- // confirm formula parsing is case-insensitive
- FormulaParser.parse("mYfUnC(\"arg\")", book, 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()", book, FormulaType.CELL, -1);
- FormulaParser.parse("myFunc(\"arg\", 0, TRUE)", book, 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\")", book, FormulaType.CELL, -1);
-
- // Verify that myFunc and yourFunc were successfully added to Workbook names
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb)) {
- // HSSFWorkbook/EXCEL97-specific side-effects user-defined function names must be added to Workbook's defined names in order to be saved.
- HSSFName myFunc = wb2.getName("myFunc");
- assertNotNull(myFunc);
- assertEqualsIgnoreCase("myFunc", myFunc.getNameName());
- HSSFName yourFunc = wb2.getName("yourFunc");
- assertNotNull(yourFunc);
- assertEqualsIgnoreCase("yourFunc", yourFunc.getNameName());
-
- // 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 = HSSFTestDataSamples.getSampleFile(testFile);
- final File reSavedFile = new File(fileIn.getParentFile(), fileIn.getName().replace(".xls", "-saved.xls"));
- FileOutputStream fos = new FileOutputStream(reSavedFile);
- wb2.write(fos);
- fos.close();
- */
- }
- }
- }
-
- private static void assertEqualsIgnoreCase(String expected, String actual) {
- assertEquals(expected.toLowerCase(Locale.ROOT), actual.toLowerCase(Locale.ROOT));
- }
-
- @Test
- void testEmbeddedSlash() {
- confirmTokenClasses("HYPERLINK(\"http://www.jakarta.org\",\"Jakarta\")",
- StringPtg.class, StringPtg.class, FuncVarPtg.class);
- }
-
- @Test
- void testConcatenate() {
- confirmTokenClasses("CONCATENATE(\"first\",\"second\")",
- StringPtg.class, StringPtg.class, FuncVarPtg.class);
- }
-
- @Test
- void testWorksheetReferences() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
-
- HSSFSheet sheet1 = wb.createSheet("NoQuotesNeeded");
- sheet1.createRow(0).createCell(0).setCellValue("NoQuotesNeeded");
- HSSFSheet sheet2 = wb.createSheet("Quotes Needed Here $@");
- sheet2.createRow(0).createCell(0).setCellValue("Quotes Needed Here $@");
-
- HSSFSheet sheet = wb.createSheet("Test");
- HSSFRow row = sheet.createRow(0);
-
- FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
- HSSFCell cell;
- String act;
-
- cell = row.createCell(0);
- cell.setCellFormula("NoQuotesNeeded!A1");
- act = evaluator.evaluate(cell).getStringValue();
- assertEquals("NoQuotesNeeded", act);
-
- cell = row.createCell(1);
- cell.setCellFormula("'Quotes Needed Here $@'!A1");
- act = evaluator.evaluate(cell).getStringValue();
- assertEquals("Quotes Needed Here $@", act);
- }
- }
-
- @Test
- void testUnaryMinus() {
- confirmTokenClasses("-A1", RefPtg.class, UnaryMinusPtg.class);
- }
-
- @Test
- void testUnaryPlus() {
- confirmTokenClasses("+A1", RefPtg.class, UnaryPlusPtg.class);
- }
-
- /**
- * There may be multiple ways to encode an expression involving {@link UnaryPlusPtg}
- * or {@link UnaryMinusPtg}. These may be perfectly equivalent from a formula
- * evaluation perspective, or formula rendering. However, differences in the way
- * POI encodes formulas may cause unnecessary confusion. These non-critical tests
- * check that POI follows the same encoding rules as Excel.
- */
- @Test
- void testExactEncodingOfUnaryPlusAndMinus() {
- // as tested in Excel:
- confirmUnary("-3", -3, NumberPtg.class);
- confirmUnary("--4", -4, NumberPtg.class, UnaryMinusPtg.class);
- confirmUnary("+++5", 5, IntPtg.class, UnaryPlusPtg.class, UnaryPlusPtg.class);
- confirmUnary("++-6", -6, NumberPtg.class, UnaryPlusPtg.class, UnaryPlusPtg.class);
-
- // Spaces muck things up a bit. It would be clearer why the following cases are
- // reasonable if POI encoded tAttrSpace in the right places.
- // Otherwise these differences look capricious.
- confirmUnary("+ 12", 12, IntPtg.class, UnaryPlusPtg.class);
- confirmUnary("- 13", 13, IntPtg.class, UnaryMinusPtg.class);
- }
-
- private static void confirmUnary(String formulaText, double val, Class>...expectedTokenTypes) {
- Ptg[] ptgs = parseFormula(formulaText);
- confirmTokenClasses(ptgs, expectedTokenTypes);
- Ptg ptg0 = ptgs[0];
- if (ptg0 instanceof IntPtg) {
- IntPtg intPtg = (IntPtg) ptg0;
- assertEquals((int)val, intPtg.getValue());
- } else if (ptg0 instanceof NumberPtg) {
- NumberPtg numberPtg = (NumberPtg) ptg0;
- assertEquals(val, numberPtg.getValue(), 0.0);
- } else {
- fail("bad ptg0 " + ptg0);
- }
- }
-
- @Test
- void testLeadingSpaceInString() {
- String value = " hi ";
- Ptg[] ptgs = parseFormula("\"" + value + "\"");
- confirmTokenClasses(ptgs, StringPtg.class);
- assertEquals(((StringPtg) ptgs[0]).getValue(), value, "ptg0 contains exact value");
- }
-
- @Test
- void testLookupAndMatchFunctionArgs() {
- Ptg[] ptgs = parseFormula("lookup(A1, A3:A52, B3:B52)");
- confirmTokenClasses(ptgs, RefPtg.class, AreaPtg.class, AreaPtg.class, FuncVarPtg.class);
- assertEquals(ptgs[0].getPtgClass(), Ptg.CLASS_VALUE, "ptg0 has Value class");
-
- ptgs = parseFormula("match(A1, A3:A52)");
- confirmTokenClasses(ptgs, RefPtg.class, AreaPtg.class, FuncVarPtg.class);
- assertEquals(ptgs[0].getPtgClass(), Ptg.CLASS_VALUE, "ptg0 has Value class");
- }
-
- /** bug 33160*/
- @Test
- void testLargeInt() {
- confirmTokenClasses("40", IntPtg.class);
- confirmTokenClasses("40000", IntPtg.class);
- }
-
- /** bug 33160 */
- @Test
- void testSimpleLongFormula() {
- confirmTokenClasses("40000/2", IntPtg.class, IntPtg.class, DividePtg.class);
- }
-
- /** bug 35027, underscore in sheet name */
- @Test
- void testUnderscore() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet1 = wb.createSheet("Cash_Flow");
- sheet1.createRow(0).createCell(0).setCellValue("Cash_Flow");
-
- HSSFSheet sheet = wb.createSheet("Test");
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell;
-
- cell = row.createCell(0);
- cell.setCellFormula("Cash_Flow!A1");
-
- FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
- String act = evaluator.evaluate(cell).getStringValue();
- assertEquals("Cash_Flow", act);
- }
- }
-
- /** bug 49725, defined names with underscore */
- @Test
- void testNamesWithUnderscore() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook(); //or new XSSFWorkbook();
- HSSFSheet sheet = wb.createSheet("NamesWithUnderscore");
-
- HSSFName nm;
-
- nm = wb.createName();
- nm.setNameName("DA6_LEO_WBS_Number");
- nm.setRefersToFormula("33");
-
- nm = wb.createName();
- nm.setNameName("DA6_LEO_WBS_Name");
- nm.setRefersToFormula("33");
-
- nm = wb.createName();
- nm.setNameName("A1_");
- nm.setRefersToFormula("22");
-
- nm = wb.createName();
- nm.setNameName("_A1");
- nm.setRefersToFormula("11");
-
- nm = wb.createName();
- nm.setNameName("A_1");
- nm.setRefersToFormula("44");
-
- nm = wb.createName();
- nm.setNameName("A_1_");
- nm.setRefersToFormula("44");
-
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell = row.createCell(0);
-
- cell.setCellFormula("DA6_LEO_WBS_Number*2");
- assertEquals("DA6_LEO_WBS_Number*2", cell.getCellFormula());
-
- cell.setCellFormula("(A1_*_A1+A_1)/A_1_");
- assertEquals("(A1_*_A1+A_1)/A_1_", cell.getCellFormula());
-
- cell.setCellFormula("INDEX(DA6_LEO_WBS_Name,MATCH($A3,DA6_LEO_WBS_Number,0))");
- assertEquals("INDEX(DA6_LEO_WBS_Name,MATCH($A3,DA6_LEO_WBS_Number,0))", cell.getCellFormula());
-
- wb.close();
- }
-
- // bug 38396 : Formula with exponential numbers not parsed correctly.
- @Test
- void testExponentialParsing() {
- confirmTokenClasses("1.3E21/2", NumberPtg.class, IntPtg.class, DividePtg.class);
- confirmTokenClasses("1322E21/2", NumberPtg.class, IntPtg.class, DividePtg.class);
- confirmTokenClasses("1.3E1/2", NumberPtg.class, IntPtg.class, DividePtg.class);
- }
-
- @Test
- void testExponentialInSheet() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- wb.createSheet("Cash_Flow");
-
- HSSFSheet sheet = wb.createSheet("Test");
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell = row.createCell(0);
- String formula;
-
- cell.setCellFormula("1.3E21/3");
- formula = cell.getCellFormula();
- assertEquals("1.3E+21/3", formula);
-
- cell.setCellFormula("-1.3E21/3");
- formula = cell.getCellFormula();
- assertEquals("-1.3E+21/3", formula);
-
- cell.setCellFormula("1322E21/3");
- formula = cell.getCellFormula();
- assertEquals("1.322E+24/3", formula);
-
- cell.setCellFormula("-1322E21/3");
- formula = cell.getCellFormula();
- assertEquals("-1.322E+24/3", formula);
-
- cell.setCellFormula("1.3E1/3");
- formula = cell.getCellFormula();
- assertEquals("13/3", formula);
-
- cell.setCellFormula("-1.3E1/3");
- formula = cell.getCellFormula();
- assertEquals("-13/3", formula);
-
- cell.setCellFormula("1.3E-4/3");
- formula = cell.getCellFormula();
- assertEquals("0.00013/3", formula);
-
- cell.setCellFormula("-1.3E-4/3");
- formula = cell.getCellFormula();
- assertEquals("-0.00013/3", formula);
-
- cell.setCellFormula("13E-15/3");
- formula = cell.getCellFormula();
- assertEquals("0.000000000000013/3", formula);
-
- cell.setCellFormula("-13E-15/3");
- formula = cell.getCellFormula();
- assertEquals("-0.000000000000013/3", formula);
-
- cell.setCellFormula("1.3E3/3");
- formula = cell.getCellFormula();
- assertEquals("1300/3", formula);
-
- cell.setCellFormula("-1.3E3/3");
- formula = cell.getCellFormula();
- assertEquals("-1300/3", formula);
-
- cell.setCellFormula("1300000000000000/3");
- formula = cell.getCellFormula();
- assertEquals("1300000000000000/3", formula);
-
- cell.setCellFormula("-1300000000000000/3");
- formula = cell.getCellFormula();
- assertEquals("-1300000000000000/3", formula);
-
- cell.setCellFormula("-10E-1/3.1E2*4E3/3E4");
- formula = cell.getCellFormula();
- assertEquals("-1/310*4000/30000", formula);
-
- wb.close();
- }
-
- @Test
- void testNumbers() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- wb.createSheet("Cash_Flow");
-
- HSSFSheet sheet = wb.createSheet("Test");
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell = row.createCell(0);
- String formula;
-
- // starts from decimal point
-
- cell.setCellFormula(".1");
- formula = cell.getCellFormula();
- assertEquals("0.1", formula);
-
- cell.setCellFormula("+.1");
- formula = cell.getCellFormula();
- assertEquals("0.1", formula);
-
- cell.setCellFormula("-.1");
- formula = cell.getCellFormula();
- assertEquals("-0.1", formula);
-
- // has exponent
-
- cell.setCellFormula("10E1");
- formula = cell.getCellFormula();
- assertEquals("100", formula);
-
- cell.setCellFormula("10E+1");
- formula = cell.getCellFormula();
- assertEquals("100", formula);
-
- cell.setCellFormula("10E-1");
- formula = cell.getCellFormula();
- assertEquals("1", formula);
-
- wb.close();
- }
-
- @Test
- void testRanges() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- wb.createSheet("Cash_Flow");
-
- HSSFSheet sheet = wb.createSheet("Test");
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell = row.createCell(0);
- String formula;
-
- cell.setCellFormula("A1.A2");
- formula = cell.getCellFormula();
- assertEquals("A1:A2", formula);
-
- cell.setCellFormula("A1..A2");
- formula = cell.getCellFormula();
- assertEquals("A1:A2", formula);
-
- cell.setCellFormula("A1...A2");
- formula = cell.getCellFormula();
- assertEquals("A1:A2", formula);
-
- wb.close();
- }
-
- @Test
- void testMultiSheetReference() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- wb.createSheet("Cash_Flow");
- wb.createSheet("Test Sheet");
-
- HSSFSheet sheet = wb.createSheet("Test");
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell = row.createCell(0);
- String formula;
-
-
- // References to a single cell:
-
- // One sheet
- cell.setCellFormula("Cash_Flow!A1");
- formula = cell.getCellFormula();
- assertEquals("Cash_Flow!A1", formula);
-
- // Then the other
- cell.setCellFormula("'Test Sheet'!A1");
- formula = cell.getCellFormula();
- assertEquals("'Test Sheet'!A1", formula);
-
- // Now both
- cell.setCellFormula("Cash_Flow:'Test Sheet'!A1");
- formula = cell.getCellFormula();
- assertEquals("Cash_Flow:'Test Sheet'!A1", formula);
-
-
- // References to a range (area) of cells:
-
- // One sheet
- cell.setCellFormula("Cash_Flow!A1:B2");
- formula = cell.getCellFormula();
- assertEquals("Cash_Flow!A1:B2", formula);
-
- // Then the other
- cell.setCellFormula("'Test Sheet'!A1:B2");
- formula = cell.getCellFormula();
- assertEquals("'Test Sheet'!A1:B2", formula);
-
- // Now both
- cell.setCellFormula("Cash_Flow:'Test Sheet'!A1:B2");
- formula = cell.getCellFormula();
- assertEquals("Cash_Flow:'Test Sheet'!A1:B2", formula);
-
- wb.close();
- }
-
- /**
- * Test for bug observable at svn revision 618865 (5-Feb-2008)
- * a formula consisting of a single no-arg function got rendered without the function braces
- */
- @Test
- void testToFormulaStringZeroArgFunction() throws IOException {
- HSSFWorkbook book = new HSSFWorkbook();
-
- Ptg[] ptgs = {
- FuncPtg.create(10),
- };
- assertEquals("NA()", HSSFFormulaParser.toFormulaString(book, ptgs));
-
- book.close();
- }
-
- @Test
- void testPercent() {
-
- confirmTokenClasses("5%", IntPtg.class, PercentPtg.class);
- // spaces OK
- confirmTokenClasses(" 250 % ", IntPtg.class, PercentPtg.class);
- // double percent OK
- confirmTokenClasses("12345.678%%", NumberPtg.class, PercentPtg.class, PercentPtg.class);
-
- // percent of a bracketed expression
- confirmTokenClasses("(A1+35)%*B1%", RefPtg.class, IntPtg.class, AddPtg.class, ParenthesisPtg.class,
- PercentPtg.class, RefPtg.class, PercentPtg.class, MultiplyPtg.class);
-
- // percent of a text quantity
- confirmTokenClasses("\"8.75\"%", StringPtg.class, PercentPtg.class);
-
- // percent to the power of
- confirmTokenClasses("50%^3", IntPtg.class, PercentPtg.class, IntPtg.class, PowerPtg.class);
-
- // things that parse OK but would *evaluate* to an error
- confirmTokenClasses("\"abc\"%", StringPtg.class, PercentPtg.class);
- confirmTokenClasses("#N/A%", ErrPtg.class, PercentPtg.class);
- }
-
- /**
- * Tests combinations of various operators in the absence of brackets
- */
- @Test
- void testPrecedenceAndAssociativity() {
-
- // TRUE=TRUE=2=2 evaluates to FALSE
- confirmTokenClasses("TRUE=TRUE=2=2", BoolPtg.class, BoolPtg.class, EqualPtg.class,
- IntPtg.class, EqualPtg.class, IntPtg.class, EqualPtg.class);
-
- // 2^3^2 evaluates to 64 not 512
- confirmTokenClasses("2^3^2", IntPtg.class, IntPtg.class, PowerPtg.class,
- IntPtg.class, PowerPtg.class);
-
- // "abc" & 2 + 3 & "def" evaluates to "abc5def"
- confirmTokenClasses("\"abc\"&2+3&\"def\"", StringPtg.class, IntPtg.class, IntPtg.class,
- AddPtg.class, ConcatPtg.class, StringPtg.class, ConcatPtg.class);
-
- // (1 / 2) - (3 * 4)
- confirmTokenClasses("1/2-3*4", IntPtg.class, IntPtg.class, DividePtg.class,
- IntPtg.class, IntPtg.class, MultiplyPtg.class, SubtractPtg.class);
-
- // 2 * (2^2)
- // NOT: (2 *2) ^ 2 -> int int multiply int power
- confirmTokenClasses("2*2^2", IntPtg.class, IntPtg.class, IntPtg.class, PowerPtg.class, MultiplyPtg.class);
-
- // 2^200% -> 2 not 1.6E58
- confirmTokenClasses("2^200%", IntPtg.class, IntPtg.class, PercentPtg.class, PowerPtg.class);
- }
-
- /* package */ static Ptg[] confirmTokenClasses(String formula, Class>...expectedClasses) {
- Ptg[] ptgs = parseFormula(formula);
- confirmTokenClasses(ptgs, expectedClasses);
- return ptgs;
- }
-
- private static void confirmTokenClasses(Ptg[] ptgs, Class>...expectedClasses) {
- assertEquals(expectedClasses.length, ptgs.length);
- for (int i = 0; i < expectedClasses.length; i++) {
- assertEquals(expectedClasses[i], ptgs[i].getClass(),
- "difference at token[" + i + "]: expected ("
- + expectedClasses[i].getName() + ") but got ("
- + ptgs[i].getClass().getName() + ")");
- }
- }
-
- @Test
- void testPower() {
- confirmTokenClasses("2^5", IntPtg.class, IntPtg.class, PowerPtg.class);
- }
-
- private static Ptg parseSingleToken(String formula, Class extends Ptg> ptgClass) {
- Ptg[] ptgs = parseFormula(formula);
- assertEquals(1, ptgs.length);
- Ptg result = ptgs[0];
- assertEquals(ptgClass, result.getClass());
- return result;
- }
-
- @Test
- void testParseNumber() {
- IntPtg ip;
-
- // bug 33160
- ip = (IntPtg) parseSingleToken("40", IntPtg.class);
- assertEquals(40, ip.getValue());
- ip = (IntPtg) parseSingleToken("40000", IntPtg.class);
- assertEquals(40000, ip.getValue());
-
- // check the upper edge of the IntPtg range:
- ip = (IntPtg) parseSingleToken("65535", IntPtg.class);
- assertEquals(65535, ip.getValue());
- NumberPtg np = (NumberPtg) parseSingleToken("65536", NumberPtg.class);
- assertEquals(65536, np.getValue(), 0);
-
- np = (NumberPtg) parseSingleToken("65534.6", NumberPtg.class);
- assertEquals(65534.6, np.getValue(), 0);
- }
-
- @Test
- void testMissingArgs() {
- confirmTokenClasses("if(A1, ,C1)",
- RefPtg.class,
- AttrPtg.class, // tAttrIf
- MissingArgPtg.class,
- AttrPtg.class, // tAttrSkip
- RefPtg.class,
- AttrPtg.class, // tAttrSkip
- FuncVarPtg.class
- );
-
- confirmTokenClasses("counta( , A1:B2, )", MissingArgPtg.class, AreaPtg.class, MissingArgPtg.class,
- FuncVarPtg.class);
- }
-
- @Test
- void testParseErrorLiterals() {
-
- confirmParseErrorLiteral(ErrPtg.NULL_INTERSECTION, "#NULL!");
- confirmParseErrorLiteral(ErrPtg.DIV_ZERO, "#DIV/0!");
- confirmParseErrorLiteral(ErrPtg.VALUE_INVALID, "#VALUE!");
- confirmParseErrorLiteral(ErrPtg.REF_INVALID, "#REF!");
- confirmParseErrorLiteral(ErrPtg.NAME_INVALID, "#NAME?");
- confirmParseErrorLiteral(ErrPtg.NUM_ERROR, "#NUM!");
- confirmParseErrorLiteral(ErrPtg.N_A, "#N/A");
- parseFormula("HLOOKUP(F7,#REF!,G7,#REF!)");
- }
-
- private static void confirmParseErrorLiteral(ErrPtg expectedToken, String formula) {
- assertEquals(expectedToken, parseSingleToken(formula, ErrPtg.class));
- }
-
- /**
- * To aid readability the parameters have been encoded with single quotes instead of double
- * quotes. This method converts single quotes to double quotes before performing the parse
- * and result check.
- */
- private static void confirmStringParse(String singleQuotedValue) {
- // formula: internal quotes become double double, surround with double quotes
- String formula = '"' + singleQuotedValue.replaceAll("'", "\"\"") + '"';
- String expectedValue = singleQuotedValue.replace('\'', '"');
-
- StringPtg sp = (StringPtg) parseSingleToken(formula, StringPtg.class);
- assertEquals(expectedValue, sp.getValue());
- }
-
- @Test
- void testParseStringLiterals_bug28754() throws IOException {
-
- StringPtg sp;
- try {
- sp = (StringPtg) parseSingleToken("\"test\"\"ing\"", StringPtg.class);
- } catch (RuntimeException e) {
- if(e.getMessage().startsWith("Cannot Parse")) {
- fail("Identified bug 28754a");
- }
- throw e;
- }
- assertEquals("test\"ing", sp.getValue());
-
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- wb.setSheetName(0, "Sheet1");
-
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell = row.createCell(0);
- cell.setCellFormula("right(\"test\"\"ing\", 3)");
- String actualCellFormula = cell.getCellFormula();
- assertNotEquals("RIGHT(\"test\"ing\",3)", actualCellFormula, "Identified bug 28754b");
- assertEquals("RIGHT(\"test\"\"ing\",3)", actualCellFormula);
- }
- }
-
- @Test
- void testParseStringLiterals() {
- confirmStringParse("goto considered harmful");
-
- confirmStringParse("goto 'considered' harmful");
-
- confirmStringParse("");
- confirmStringParse("'");
- confirmStringParse("''");
- confirmStringParse("' '");
- confirmStringParse(" ' ");
- }
-
- @Test
- void testParseSumIfSum() {
- String formulaString;
- Ptg[] ptgs;
- ptgs = parseFormula("sum(5, 2, if(3>2, sum(A1:A2), 6))");
- formulaString = toFormulaString(ptgs);
- assertEquals("SUM(5,2,IF(3>2,SUM(A1:A2),6))", formulaString);
-
- ptgs = parseFormula("if(1<2,sum(5, 2, if(3>2, sum(A1:A2), 6)),4)");
- formulaString = toFormulaString(ptgs);
- assertEquals("IF(1<2,SUM(5,2,IF(3>2,SUM(A1:A2),6)),4)", formulaString);
- }
-
- @Test
- void testParserErrors() {
- parseExpectedException(" 12 . 345 ");
- parseExpectedException("1 .23 ");
-
- parseExpectedException("sum(#NAME)");
- parseExpectedException("1 + #N / A * 2");
- parseExpectedException("#value?");
- parseExpectedException("#DIV/ 0+2");
-
-
- parseExpectedException("IF(TRUE)");
- parseExpectedException("countif(A1:B5, C1, D1)");
-
- parseExpectedException("(");
- parseExpectedException(")");
- parseExpectedException("+");
- parseExpectedException("42+");
-
- parseExpectedException("IF(");
- }
-
- private static void parseExpectedException(String formula) {
- FormulaParseException e = assertThrows(FormulaParseException.class, () -> parseFormula(formula));
- assertNotNull(e.getMessage());
- }
-
- @Test
- void testSetFormulaWithRowBeyond32768_Bug44539() throws IOException {
-
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet();
- wb.setSheetName(0, "Sheet1");
-
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell = row.createCell(0);
- cell.setCellFormula("SUM(A32769:A32770)");
- assertNotEquals("SUM(A-32767:A-32766)", cell.getCellFormula(), "Identified bug 44539");
- assertEquals("SUM(A32769:A32770)", cell.getCellFormula());
-
- wb.close();
- }
-
- @Test
- void testSpaceAtStartOfFormula() {
- // Simulating cell formula of "= 4" (note space)
- // The same Ptg array can be observed if an excel file is saved with that exact formula
-
- AttrPtg spacePtg = AttrPtg.createSpace(AttrPtg.SpaceType.SPACE_BEFORE, 1);
- Ptg[] ptgs = { spacePtg, new IntPtg(4), };
- String formulaString;
- try {
- formulaString = toFormulaString(ptgs);
- } catch (IllegalStateException e) {
- if(e.getMessage().equalsIgnoreCase("too much stuff left on the stack")) {
- fail("Identified bug 44609");
- }
- // else some unexpected error
- throw e;
- }
- // FormulaParser strips spaces anyway
- assertEquals("4", formulaString);
-
- ptgs = new Ptg[] { new IntPtg(3), spacePtg, new IntPtg(4), spacePtg, AddPtg.instance, };
- formulaString = toFormulaString(ptgs);
- assertEquals("3+4", formulaString);
- }
-
- /**
- * Checks some internal error detecting logic ('stack underflow error' in toFormulaString)
- */
- @Test
- void testTooFewOperandArgs() {
- // Simulating badly encoded cell formula of "=/1"
- // Not sure if Excel could ever produce this
- Ptg[] ptgs = {
- // Excel would probably have put tMissArg here
- new IntPtg(1),
- DividePtg.instance,
- };
- IllegalStateException e = assertThrows(IllegalStateException.class, () -> toFormulaString(ptgs));
- assertTrue(e.getMessage().startsWith("Too few arguments supplied to operation"));
- }
-
- /**
- * Make sure that POI uses the right Func Ptg when encoding formulas. Functions with variable
- * number of args should get FuncVarPtg, functions with fixed args should get FuncPtg.
- *
- * Prior to the fix for bug 44675 POI would encode FuncVarPtg for all functions. In many cases
- * Excel tolerates the wrong Ptg and evaluates the formula OK (e.g. SIN), but in some cases
- * (e.g. COUNTIF) Excel fails to evaluate the formula, giving '#VALUE!' instead.
- */
- @Test
- void testFuncPtgSelection() {
-
- Ptg[] ptgs = parseFormula("countif(A1:A2, 1)");
- assertEquals(3, ptgs.length);
- assertFalse(ptgs[2] instanceof FuncVarPtg, "Identified bug 44675");
- confirmTokenClasses(ptgs, AreaPtg.class, IntPtg.class, FuncPtg.class);
-
- confirmTokenClasses("sin(1)", IntPtg.class, FuncPtg.class);
- }
-
- @Test
- void testWrongNumberOfFunctionArgs() throws IOException {
- confirmArgCountMsg("sin()", "Too few arguments to function 'SIN'. Expected 1 but got 0.");
- confirmArgCountMsg("countif(1, 2, 3, 4)", "Too many arguments to function 'COUNTIF'. Expected 2 but got 4.");
- confirmArgCountMsg("index(1, 2, 3, 4, 5, 6)", "Too many arguments to function 'INDEX'. At most 4 were expected but got 6.");
- confirmArgCountMsg("vlookup(1, 2)", "Too few arguments to function 'VLOOKUP'. At least 3 were expected but got 2.");
- }
-
- private static void confirmArgCountMsg(String formula, String expectedMessage) throws IOException {
- try (HSSFWorkbook book = new HSSFWorkbook()) {
- FormulaParseException e = assertThrows(FormulaParseException.class, () -> HSSFFormulaParser.parse(formula, book));
- confirmParseException(e, expectedMessage);
- }
- }
-
- @Test
- void testParseErrorExpectedMsg() {
- FormulaParseException e;
- e = assertThrows(FormulaParseException.class, () -> parseFormula("round(3.14;2)"));
- confirmParseException(e, "Parse error near char 10 ';' in specified formula 'round(3.14;2)'. Expected ',' or ')'");
-
- e = assertThrows(FormulaParseException.class, () -> parseFormula(" =2+2"));
- confirmParseException(e, "The specified formula ' =2+2' starts with an equals sign which is not allowed.");
- }
-
- /**
- * this function name has a dot in it.
- */
- @Test
- void testParseErrorTypeFunction() {
-
- Ptg[] ptgs;
- try {
- ptgs = parseFormula("error.type(A1)");
- } catch (IllegalArgumentException e) {
- if (e.getMessage().equals("Invalid Formula cell reference: 'error'")) {
- fail("Identified bug 45334");
- }
- throw e;
- }
- confirmTokenClasses(ptgs, RefPtg.class, FuncPtg.class);
- assertEquals("ERROR.TYPE", ((FuncPtg) ptgs[1]).getName());
- }
-
- @Test
- void testNamedRangeThatLooksLikeCell() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet("Sheet1");
- HSSFName name = wb.createName();
- name.setRefersToFormula("Sheet1!B1");
- name.setNameName("pfy1");
-
- Ptg[] ptgs;
- try {
- ptgs = HSSFFormulaParser.parse("count(pfy1)", wb);
- } catch (IllegalArgumentException e) {
- if (e.getMessage().equals("Specified colIx (1012) is out of range")) {
- fail("Identified bug 45354");
- }
- throw e;
- }
- confirmTokenClasses(ptgs, NamePtg.class, FuncVarPtg.class);
-
- HSSFCell cell = sheet.createRow(0).createCell(0);
- cell.setCellFormula("count(pfy1)");
- assertEquals("COUNT(pfy1)", cell.getCellFormula());
- FormulaParseException e = assertThrows(FormulaParseException.class, () -> cell.setCellFormula("count(pf1)"));
- confirmParseException(e, "Specified named range 'pf1' does not exist in the current workbook.");
- cell.setCellFormula("count(fp1)"); // plain cell ref, col is in range
- }
- }
-
- @Test
- void testParseAreaRefHighRow_bug45358() throws IOException {
- Ptg[] ptgs;
- AreaI aptg;
-
- HSSFWorkbook book = new HSSFWorkbook();
- book.createSheet("Sheet1");
-
- ptgs = HSSFFormulaParser.parse("Sheet1!A10:A40000", book);
- aptg = (AreaI) ptgs[0];
- assertNotEquals(-25537, aptg.getLastRow(), "Identified bug 45358");
- assertEquals(39999, aptg.getLastRow());
-
- ptgs = HSSFFormulaParser.parse("Sheet1!A10:A65536", book);
- aptg = (AreaI) ptgs[0];
- assertEquals(65535, aptg.getLastRow());
-
- // plain area refs should be ok too
- ptgs = parseFormula("A10:A65536");
- aptg = (AreaI) ptgs[0];
- assertEquals(65535, aptg.getLastRow());
-
- book.close();
- }
-
- @Test
- void testParseArray() {
- Ptg[] ptgs;
- ptgs = parseFormula("mode({1,2,2,#REF!;FALSE,3,3,2})");
- confirmTokenClasses(ptgs, ArrayPtg.class, FuncVarPtg.class);
- assertEquals("{1,2,2,#REF!;FALSE,3,3,2}", ptgs[0].toFormulaString());
-
- ArrayPtg aptg = (ArrayPtg) ptgs[0];
- Object[][] values = aptg.getTokenArrayValues();
- assertEquals(ErrorConstant.valueOf(FormulaError.REF.getCode()), values[0][3]);
- assertEquals(Boolean.FALSE, values[1][0]);
- }
-
- @Test
- void testParseStringElementInArray() {
- Ptg[] ptgs;
- ptgs = parseFormula("MAX({\"5\"},3)");
- confirmTokenClasses(ptgs, ArrayPtg.class, IntPtg.class, FuncVarPtg.class);
- Object element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0];
- // this would cause ClassCastException below
- assertFalse(element instanceof UnicodeString, "Wrong encoding of array element value");
- assertEquals(String.class, element.getClass());
-
- // make sure the formula encodes OK
- int encSize = Ptg.getEncodedSize(ptgs);
- byte[] data = new byte[encSize];
- Ptg.serializePtgs(ptgs, data, 0);
- byte[] expData = HexRead.readFromString(
- "20 00 00 00 00 00 00 00 " // tArray
- + "1E 03 00 " // tInt(3)
- + "42 02 07 00 " // tFuncVar(MAX) 2-arg
- + "00 00 00 " // Array data: 1 col, 1 row
- + "02 01 00 00 35" // elem (type=string, len=1, "5")
- );
- assertArrayEquals(expData, data);
- int initSize = Ptg.getEncodedSizeWithoutArrayData(ptgs);
- Ptg[] ptgs2 = Ptg.readTokens(initSize, new LittleEndianByteArrayInputStream(data));
- confirmTokenClasses(ptgs2, ArrayPtg.class, IntPtg.class, FuncVarPtg.class);
- }
-
- @Test
- void testParseArrayNegativeElement() {
- Ptg[] ptgs;
- try {
- ptgs = parseFormula("{-42}");
- } catch (FormulaParseException e) {
- if (e.getMessage().equals("Parse error near char 1 '-' in specified formula '{-42}'. Expected Integer")) {
- fail("Identified bug - failed to parse negative array element.");
- }
- throw e;
- }
- confirmTokenClasses(ptgs, ArrayPtg.class);
- Object element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0];
-
- assertEquals(-42.0, (Double) element, 0.0);
-
- // Should be able to handle whitespace between unary minus and digits (Excel
- // accepts this formula after presenting the user with a confirmation dialog).
- ptgs = parseFormula("{- 5}");
- element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0];
- assertEquals(-5.0, (Double) element, 0.0);
- }
-
- @Test
- void testRangeOperator() throws IOException {
-
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet();
- HSSFCell cell = sheet.createRow(0).createCell(0);
-
- wb.setSheetName(0, "Sheet1");
- cell.setCellFormula("Sheet1!B$4:Sheet1!$C1"); // explicit range ':' operator
- assertEquals("Sheet1!B$4:Sheet1!$C1", cell.getCellFormula());
-
- cell.setCellFormula("Sheet1!B$4:$C1"); // plain area ref
- assertEquals("Sheet1!B1:$C$4", cell.getCellFormula()); // note - area ref is normalised
-
- cell.setCellFormula("Sheet1!$C1...B$4"); // different syntax for plain area ref
- assertEquals("Sheet1!B1:$C$4", cell.getCellFormula());
-
- // with funny sheet name
- wb.setSheetName(0, "A1...A2");
- cell.setCellFormula("A1...A2!B1");
- assertEquals("A1...A2!B1", cell.getCellFormula());
-
- wb.close();
- }
-
- @Test
- void testBooleanNamedSheet() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet("true");
- HSSFCell cell = sheet.createRow(0).createCell(0);
- cell.setCellFormula("'true'!B2");
-
- assertEquals("'true'!B2", cell.getCellFormula());
-
- wb.close();
- }
-
- @Test
- void testParseExternalWorkbookReference() throws IOException {
- HSSFWorkbook wbA = HSSFTestDataSamples.openSampleWorkbook("multibookFormulaA.xls");
- HSSFCell cell = wbA.getSheetAt(0).getRow(0).getCell(0);
-
- // make sure formula in sample is as expected
- assertEquals("[multibookFormulaB.xls]BSheet1!B1", cell.getCellFormula());
- Ptg[] expectedPtgs = FormulaExtractor.getPtgs(cell);
- confirmSingle3DRef(expectedPtgs, 1);
-
- // now try (re-)parsing the formula
- Ptg[] actualPtgs = HSSFFormulaParser.parse("[multibookFormulaB.xls]BSheet1!B1", wbA);
- confirmSingle3DRef(actualPtgs, 1); // externalSheetIndex 1 -> BSheet1
-
- // try parsing a formula pointing to a different external sheet
- Ptg[] otherPtgs = HSSFFormulaParser.parse("[multibookFormulaB.xls]AnotherSheet!B1", wbA);
- confirmSingle3DRef(otherPtgs, 0); // externalSheetIndex 0 -> AnotherSheet
-
- // try setting the same formula in a cell
- cell.setCellFormula("[multibookFormulaB.xls]AnotherSheet!B1");
- assertEquals("[multibookFormulaB.xls]AnotherSheet!B1", cell.getCellFormula());
-
- wbA.close();
- }
-
- private static void confirmSingle3DRef(Ptg[] ptgs, int expectedExternSheetIndex) {
- assertEquals(1, ptgs.length);
- Ptg ptg0 = ptgs[0];
- assertTrue(ptg0 instanceof Ref3DPtg);
- assertEquals(expectedExternSheetIndex, ((Ref3DPtg)ptg0).getExternSheetIndex());
- }
-
- @Test
- void testUnion() throws IOException {
- String formula = "Sheet1!$B$2:$C$3,OFFSET(Sheet1!$E$2:$E$4,1,Sheet1!$A$1),Sheet1!$D$6";
- HSSFWorkbook wb = new HSSFWorkbook();
- wb.createSheet("Sheet1");
- Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1);
-
- confirmTokenClasses(ptgs,
- // TODO - AttrPtg.class, // Excel prepends this
- MemFuncPtg.class,
- Area3DPtg.class,
- Area3DPtg.class,
- IntPtg.class,
- Ref3DPtg.class,
- FuncVarPtg.class,
- UnionPtg.class,
- Ref3DPtg.class,
- UnionPtg.class
- );
- MemFuncPtg mf = (MemFuncPtg)ptgs[0];
- assertEquals(45, mf.getLenRefSubexpression());
-
- // We don't check the type of the operands.
- confirmTokenClasses("1,2", MemAreaPtg.class, IntPtg.class, IntPtg.class, UnionPtg.class);
-
- wb.close();
- }
-
- @Test
- void testIntersection() throws IOException {
- String formula = "Sheet1!$B$2:$C$3 OFFSET(Sheet1!$E$2:$E$4, 1,Sheet1!$A$1) Sheet1!$D$6";
- HSSFWorkbook wb = new HSSFWorkbook();
- wb.createSheet("Sheet1");
- Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1);
-
- confirmTokenClasses(ptgs,
- // TODO - AttrPtg.class, // Excel prepends this
- MemFuncPtg.class,
- Area3DPtg.class,
- Area3DPtg.class,
- IntPtg.class,
- Ref3DPtg.class,
- FuncVarPtg.class,
- IntersectionPtg.class,
- Ref3DPtg.class,
- IntersectionPtg.class
- );
- MemFuncPtg mf = (MemFuncPtg)ptgs[0];
- assertEquals(45, mf.getLenRefSubexpression());
-
- // This used to be an error but now parses. Union has the same behaviour.
- confirmTokenClasses("1 2", MemAreaPtg.class, IntPtg.class, IntPtg.class, IntersectionPtg.class);
-
- wb.close();
- }
-
- @Test
- void testComparisonInParen() {
- confirmTokenClasses("(A1 > B2)",
- RefPtg.class,
- RefPtg.class,
- GreaterThanPtg.class,
- ParenthesisPtg.class
- );
- }
-
- @Test
- void testUnionInParen() {
- confirmTokenClasses("(A1:B2,B2:C3)",
- MemAreaPtg.class,
- AreaPtg.class,
- AreaPtg.class,
- UnionPtg.class,
- ParenthesisPtg.class
- );
- }
-
- @Test
- void testIntersectionInParen() {
- confirmTokenClasses("(A1:B2 B2:C3)",
- MemAreaPtg.class,
- AreaPtg.class,
- AreaPtg.class,
- IntersectionPtg.class,
- ParenthesisPtg.class
- );
- }
-
- // https://bz.apache.org/bugzilla/show_bug.cgi?id=60980
- @Test
- void testIntersectionInFunctionArgs() {
- confirmTokenClasses("SUM(A1:B2 B2:C3)",
- MemAreaPtg.class,
- AreaPtg.class,
- AreaPtg.class,
- IntersectionPtg.class,
- AttrPtg.class
- );
- }
-
- @Test
- void testIntersectionNamesInFunctionArgs() {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- HSSFName name1 = wb.createName();
- name1.setNameName("foo1");
- name1.setRefersToFormula("A1:A3");
-
- HSSFName name2 = wb.createName();
- name2.setNameName("foo2");
- name2.setRefersToFormula("A1:B3");
-
- Ptg[] ptgs = FormulaParser.parse("SUM(foo1 foo2)", HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1);
-
- confirmTokenClasses(ptgs,
- MemFuncPtg.class,
- NamePtg.class,
- NamePtg.class,
- IntersectionPtg.class,
- AttrPtg.class
- );
- }
-
- @Test
- void testRange_bug46643() throws IOException {
- String formula = "Sheet1!A1:Sheet1!B3";
- HSSFWorkbook wb = new HSSFWorkbook();
- wb.createSheet("Sheet1");
- Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1, -1);
-
- if (ptgs.length == 3) {
- confirmTokenClasses(ptgs, Ref3DPtg.class, Ref3DPtg.class, RangePtg.class);
- fail("Identified bug 46643");
- }
-
- confirmTokenClasses(ptgs,
- MemFuncPtg.class,
- Ref3DPtg.class,
- Ref3DPtg.class,
- RangePtg.class
- );
- MemFuncPtg mf = (MemFuncPtg)ptgs[0];
- assertEquals(15, mf.getLenRefSubexpression());
- wb.close();
- }
-
- /** Named ranges with backslashes, e.g. 'POI\\2009' */
- @Test
- void testBackSlashInNames() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- HSSFName name = wb.createName();
- name.setNameName("POI\\2009");
- name.setRefersToFormula("Sheet1!$A$1");
-
- HSSFSheet sheet = wb.createSheet();
- HSSFRow row = sheet.createRow(0);
-
- HSSFCell cell_C1 = row.createCell(2);
- cell_C1.setCellFormula("POI\\2009");
- assertEquals("POI\\2009", cell_C1.getCellFormula());
-
- HSSFCell cell_D1 = row.createCell(2);
- cell_D1.setCellFormula("NOT(POI\\2009=\"3.5-final\")");
- assertEquals("NOT(POI\\2009=\"3.5-final\")", cell_D1.getCellFormula());
-
- wb.close();
- }
-
- /**
- * See the related/similar test: {@link BaseTestBugzillaIssues#bug42448()}
- */
- @Test
- void testParseAbnormalSheetNamesAndRanges_bug42448() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- wb.createSheet("A");
- try {
- HSSFFormulaParser.parse("SUM(A!C7:A!C67)", wb);
- } catch (StringIndexOutOfBoundsException e) {
- fail("Identified bug 42448");
- }
- // the exact example from the bugzilla description:
- HSSFFormulaParser.parse("SUMPRODUCT(A!C7:A!C67, B8:B68) / B69", wb);
-
- wb.close();
- }
-
- @Test
- void testRangeFuncOperand_bug46951() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- Ptg[] ptgs;
- try {
- ptgs = HSSFFormulaParser.parse("SUM(C1:OFFSET(C1,0,B1))", wb);
- } catch (RuntimeException e) {
- if (e.getMessage().equals("Specified named range 'OFFSET' does not exist in the current workbook.")) {
- fail("Identified bug 46951");
- }
- throw e;
- }
- confirmTokenClasses(ptgs,
- MemFuncPtg.class, // [len=23]
- RefPtg.class, // [C1]
- RefPtg.class, // [C1]
- IntPtg.class, // [0]
- RefPtg.class, // [B1]
- FuncVarPtg.class, // [OFFSET nArgs=3]
- RangePtg.class, //
- AttrPtg.class // [sum ]
- );
- }
- }
-
- @Test
- void testUnionOfFullCollFullRowRef() throws IOException {
- parseFormula("3:4");
- Ptg[] ptgs = parseFormula("$Z:$AC");
- confirmTokenClasses(ptgs, AreaPtg.class);
- parseFormula("B:B");
-
- ptgs = parseFormula("$11:$13");
- confirmTokenClasses(ptgs, AreaPtg.class);
-
- ptgs = parseFormula("$A:$A,$1:$4");
- confirmTokenClasses(ptgs, MemAreaPtg.class,
- AreaPtg.class,
- AreaPtg.class,
- UnionPtg.class
- );
-
- HSSFWorkbook wb = new HSSFWorkbook();
- wb.createSheet("Sheet1");
- ptgs = HSSFFormulaParser.parse("Sheet1!$A:$A,Sheet1!$1:$4", wb);
- confirmTokenClasses(ptgs, MemFuncPtg.class,
- Area3DPtg.class,
- Area3DPtg.class,
- UnionPtg.class
- );
-
- ptgs = HSSFFormulaParser.parse("'Sheet1'!$A:$A,'Sheet1'!$1:$4", wb);
- confirmTokenClasses(ptgs,
- MemFuncPtg.class,
- Area3DPtg.class,
- Area3DPtg.class,
- UnionPtg.class
- );
-
- wb.close();
- }
-
- @Test
- void testExplicitRangeWithTwoSheetNames() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- wb.createSheet("Sheet1");
- Ptg[] ptgs = HSSFFormulaParser.parse("Sheet1!F1:Sheet1!G2", wb);
- confirmTokenClasses(ptgs,
- MemFuncPtg.class,
- Ref3DPtg.class,
- Ref3DPtg.class,
- RangePtg.class
- );
- MemFuncPtg mf;
- mf = (MemFuncPtg)ptgs[0];
- assertEquals(15, mf.getLenRefSubexpression());
- wb.close();
- }
-
- /**
- * Checks that the area-ref and explicit range operators get the right associativity
- * and that the {@link MemFuncPtg} / {@link MemAreaPtg} is added correctly
- */
- @Test
- void testComplexExplicitRangeEncodings() {
-
- Ptg[] ptgs;
- ptgs = parseFormula("SUM(OFFSET(A1,0,0):B2:C3:D4:E5:OFFSET(F6,1,1):G7)");
- confirmTokenClasses(ptgs,
- // AttrPtg.class, // [volatile ] // POI doesn't do this yet (Apr 2009)
- MemFuncPtg.class, // len 57
- RefPtg.class, // [A1]
- IntPtg.class, // [0]
- IntPtg.class, // [0]
- FuncVarPtg.class, // [OFFSET nArgs=3]
- AreaPtg.class, // [B2:C3]
- RangePtg.class,
- AreaPtg.class, // [D4:E5]
- RangePtg.class,
- RefPtg.class, // [F6]
- IntPtg.class, // [1]
- IntPtg.class, // [1]
- FuncVarPtg.class, // [OFFSET nArgs=3]
- RangePtg.class,
- RefPtg.class, // [G7]
- RangePtg.class,
- AttrPtg.class // [sum ]
- );
-
- MemFuncPtg mf = (MemFuncPtg)ptgs[0];
- assertEquals(57, mf.getLenRefSubexpression());
- assertEquals("D4:E5", ptgs[7].toFormulaString());
- assertTrue(((AttrPtg)ptgs[16]).isSum());
-
- ptgs = parseFormula("SUM(A1:B2:C3:D4)");
- confirmTokenClasses(ptgs,
- // AttrPtg.class, // [volatile ] // POI doesn't do this yet (Apr 2009)
- MemAreaPtg.class, // len 19
- AreaPtg.class, // [A1:B2]
- AreaPtg.class, // [C3:D4]
- RangePtg.class,
- AttrPtg.class // [sum ]
- );
- MemAreaPtg ma = (MemAreaPtg)ptgs[0];
- assertEquals(19, ma.getLenRefSubexpression());
- }
-
-
- /**
- * Mostly confirming that erroneous conditions are detected. Actual error message wording is not critical.
- *
- */
- @Test
- void testEdgeCaseParserErrors() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- wb.createSheet("Sheet1");
-
- confirmParseError(wb, "A1:ROUND(B1,1)", "The RHS of the range operator ':' at position 3 is not a proper reference.");
-
- confirmParseError(wb, "Sheet1!!!", "Parse error near char 7 '!' in specified formula 'Sheet1!!!'. Expected number, string, defined name, or data table");
- confirmParseError(wb, "Sheet1!.Name", "Parse error near char 7 '.' in specified formula 'Sheet1!.Name'. Expected number, string, defined name, or data table");
- confirmParseError(wb, "Sheet1!Sheet1", "Specified name 'Sheet1' for sheet Sheet1 not found");
- confirmParseError(wb, "Sheet1!F:Sheet1!G", "'Sheet1!F' is not a proper reference.");
- confirmParseError(wb, "Sheet1!F..foobar", "Complete area reference expected after sheet name at index 11.");
- confirmParseError(wb, "Sheet1!A .. B", "Dotted range (full row or column) expression 'A .. B' must not contain whitespace.");
- confirmParseError(wb, "Sheet1!A...B", "Dotted range (full row or column) expression 'A...B' must have exactly 2 dots.");
- confirmParseError(wb, "Sheet1!A foobar", "Second part of cell reference expected after sheet name at index 10.");
-
- confirmParseError(wb, "foobar", "Specified named range 'foobar' does not exist in the current workbook.");
- confirmParseError(wb, "A1:1", "The RHS of the range operator ':' at position 3 is not a proper reference.");
- wb.close();
- }
-
- private static void confirmParseError(HSSFWorkbook wb, String formula, String expectedMessage) {
- FormulaParseException e = assertThrows(FormulaParseException.class, () -> HSSFFormulaParser.parse(formula, wb));
- confirmParseException(e, expectedMessage);
- }
-
- /**
- * In bug 47078, POI had trouble evaluating a defined name flagged as 'complex'.
- * POI should also be able to parse such defined names.
- */
- @Test
- void testParseComplexName() throws IOException {
-
- // Mock up a spreadsheet to match the critical details of the sample
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- wb.createSheet("Sheet1");
- HSSFName definedName = wb.createName();
- definedName.setNameName("foo");
- definedName.setRefersToFormula("Sheet1!B2");
-
- // Set the complex flag - POI doesn't usually manipulate this flag
- NameRecord nameRec = TestHSSFName.getNameRecord(definedName);
- nameRec.setOptionFlag((short) 0x10); // 0x10 -> complex
-
- Ptg[] result;
- try {
- result = HSSFFormulaParser.parse("1+foo", wb);
- } catch (FormulaParseException e) {
- if (e.getMessage().equals("Specified name 'foo' is not a range as expected.")) {
- fail("Identified bug 47078c");
- }
- throw e;
- }
- confirmTokenClasses(result, IntPtg.class, NamePtg.class, AddPtg.class);
- }
- }
-
- /**
- * Zero is not a valid row number so cell references like 'A0' are not valid.
- * Actually, they should be treated like defined names.
- *
- * In addition, leading zeros (on the row component) should be removed from cell
- * references during parsing.
- */
- @Test
- void testZeroRowRefs() throws IOException {
- String badCellRef = "B0"; // bad because zero is not a valid row number
- String leadingZeroCellRef = "B000001"; // this should get parsed as "B1"
- HSSFWorkbook wb = new HSSFWorkbook();
-
- FormulaParseException e = assertThrows(FormulaParseException.class, () -> HSSFFormulaParser.parse(badCellRef, wb),
- "Identified bug 47312b - Shouldn't be able to parse cell ref '" + badCellRef + "'.");
- confirmParseException(e, "Specified named range '" + badCellRef + "' does not exist in the current workbook.");
-
- Ptg[] ptgs;
- try {
- ptgs = HSSFFormulaParser.parse(leadingZeroCellRef, wb);
- assertEquals("B1", ptgs[0].toFormulaString());
- } catch (FormulaParseException e2) {
- confirmParseException(e2, "Specified named range '" + leadingZeroCellRef + "' does not exist in the current workbook.");
- // close but no cigar
- fail("Identified bug 47312c - '" + leadingZeroCellRef + "' should parse as 'B1'.");
- }
-
- // create a defined name called 'B0' and try again
- Name n = wb.createName();
- n.setNameName("B0");
- n.setRefersToFormula("1+1");
- ptgs = HSSFFormulaParser.parse("B0", wb);
- confirmTokenClasses(ptgs, NamePtg.class);
-
- wb.close();
- }
-
- private static void confirmParseException(FormulaParseException e, String expMsg) {
- assertEquals(expMsg, e.getMessage());
- }
-
- @Test
- void test57196_Formula() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- Ptg[] ptgs = HSSFFormulaParser.parse("DEC2HEX(HEX2DEC(O8)-O2+D2)", wb, FormulaType.CELL, -1);
- assertNotNull(ptgs, "Ptg array should not be null");
-
- confirmTokenClasses(ptgs,
- NameXPtg.class, // ??
- NameXPtg.class, // ??
- RefPtg.class, // O8
- FuncVarPtg.class, // HEX2DEC
- RefPtg.class, // O2
- SubtractPtg.class,
- RefPtg.class, // D2
- AddPtg.class,
- FuncVarPtg.class // DEC2HEX
- );
-
- RefPtg o8 = (RefPtg) ptgs[2];
- FuncVarPtg hex2Dec = (FuncVarPtg) ptgs[3];
- RefPtg o2 = (RefPtg) ptgs[4];
- RefPtg d2 = (RefPtg) ptgs[6];
- FuncVarPtg dec2Hex = (FuncVarPtg) ptgs[8];
-
- assertEquals("O8", o8.toFormulaString());
- assertEquals(255, hex2Dec.getFunctionIndex());
- //assertEquals("", hex2Dec.toString());
- assertEquals("O2", o2.toFormulaString());
- assertEquals("D2", d2.toFormulaString());
- assertEquals(255, dec2Hex.getFunctionIndex());
-
- wb.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java
deleted file mode 100644
index 8b41f96879..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.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.hssf.model;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
-import org.apache.poi.hssf.usermodel.HSSFName;
-import org.apache.poi.hssf.usermodel.HSSFRow;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.ss.formula.ptg.AttrPtg;
-import org.apache.poi.ss.formula.ptg.NamePtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.usermodel.CellType;
-import org.apache.poi.ss.usermodel.CellValue;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test the low level formula parser functionality,
- * but using parts which need to use
- * HSSFFormulaEvaluator.
- */
-final class TestFormulaParserEval {
-
- @Test
- void testWithNamedRange() {
- HSSFWorkbook workbook = new HSSFWorkbook();
-
- HSSFSheet s = workbook.createSheet("Foo");
- s.createRow(0).createCell(0).setCellValue(1.1);
- s.createRow(1).createCell(0).setCellValue(2.3);
- s.createRow(2).createCell(2).setCellValue(3.1);
-
- HSSFName name = workbook.createName();
- name.setNameName("testName");
- name.setRefersToFormula("A1:A2");
-
- confirmParseFormula(workbook);
-
- // Now make it a single cell
- name.setRefersToFormula("C3");
- confirmParseFormula(workbook);
-
- // And make it non-contiguous
- // using area unions
- name.setRefersToFormula("A1:A2,C3");
-
- confirmParseFormula(workbook);
- }
-
- /**
- * Makes sure that a formula referring to the named range parses properly
- */
- private static void confirmParseFormula(HSSFWorkbook workbook) {
- Ptg[] ptgs = HSSFFormulaParser.parse("SUM(testName)", workbook);
- assertEquals(2, ptgs.length, "two tokens expected, got " + ptgs.length);
- assertEquals(NamePtg.class, ptgs[0].getClass());
- assertEquals(AttrPtg.class, ptgs[1].getClass());
- }
-
- @Test
- void testEvaluateFormulaWithRowBeyond32768_Bug44539() {
-
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet();
- wb.setSheetName(0, "Sheet1");
-
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell = row.createCell(0);
- cell.setCellFormula("SUM(A32769:A32770)");
-
- // put some values in the cells to make the evaluation more interesting
- sheet.createRow(32768).createCell(0).setCellValue(31);
- sheet.createRow(32769).createCell(0).setCellValue(11);
-
- HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
- // Check for: Found reference to named range "A", but that named range wasn't defined!
- CellValue result= fe.evaluate(cell);
- assertEquals(CellType.NUMERIC, result.getCellType());
- assertEquals(42.0, result.getNumberValue(), 0.0);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java
deleted file mode 100644
index f9c06bbedb..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.model;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import org.apache.poi.ss.formula.ptg.AddPtg;
-import org.apache.poi.ss.formula.ptg.AttrPtg;
-import org.apache.poi.ss.formula.ptg.BoolPtg;
-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.LessEqualPtg;
-import org.apache.poi.ss.formula.ptg.LessThanPtg;
-import org.apache.poi.ss.formula.ptg.MultiplyPtg;
-import org.apache.poi.ss.formula.ptg.NotEqualPtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.formula.ptg.RefPtg;
-import org.apache.poi.ss.formula.ptg.StringPtg;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests FormulaParser specifically with respect to IF() functions
- */
-final class TestFormulaParserIf {
- private static Ptg[] parseFormula(String formula) {
- return TestFormulaParser.parseFormula(formula);
- }
-
- private static Ptg[] confirmTokenClasses(String formula, Class>[] expectedClasses) {
- return TestFormulaParser.confirmTokenClasses(formula, expectedClasses);
- }
-
- private static void confirmAttrData(Ptg[] ptgs, int i, int expectedData) {
- Ptg ptg = ptgs[i];
- assertTrue(ptg instanceof AttrPtg, "Token[" + i + "] was not AttrPtg as expected");
- AttrPtg attrPtg = (AttrPtg) ptg;
- assertEquals(expectedData, attrPtg.getData());
- }
-
- @Test
- void testSimpleIf() {
-
- Class>[] expClss = {
- RefPtg.class,
- AttrPtg.class, // tAttrIf
- IntPtg.class,
- AttrPtg.class, // tAttrSkip
- IntPtg.class,
- AttrPtg.class, // tAttrSkip
- FuncVarPtg.class,
- };
-
- Ptg[] ptgs = confirmTokenClasses("if(A1,1,2)", expClss);
-
- confirmAttrData(ptgs, 1, 7);
- confirmAttrData(ptgs, 3, 10);
- confirmAttrData(ptgs, 5, 3);
- }
-
- @Test
- void testSimpleIfNoFalseParam() {
-
- Class>[] expClss = {
- RefPtg.class,
- AttrPtg.class, // tAttrIf
- RefPtg.class,
- AttrPtg.class, // tAttrSkip
- FuncVarPtg.class,
- };
-
- Ptg[] ptgs = confirmTokenClasses("if(A1,B1)", expClss);
-
- confirmAttrData(ptgs, 1, 9);
- confirmAttrData(ptgs, 3, 3);
- }
-
- @Test
- void testIfWithLargeParams() {
-
- Class>[] expClss = {
- RefPtg.class,
- AttrPtg.class, // tAttrIf
-
- RefPtg.class,
- IntPtg.class,
- MultiplyPtg.class,
- RefPtg.class,
- IntPtg.class,
- AddPtg.class,
- FuncPtg.class,
- AttrPtg.class, // tAttrSkip
-
- RefPtg.class,
- RefPtg.class,
- FuncPtg.class,
-
- AttrPtg.class, // tAttrSkip
- FuncVarPtg.class,
- };
-
- Ptg[] ptgs = confirmTokenClasses("if(A1,round(B1*100,C1+2),round(B1,C1))", expClss);
-
- confirmAttrData(ptgs, 1, 25);
- confirmAttrData(ptgs, 9, 20);
- confirmAttrData(ptgs, 13, 3);
- }
-
- @Test
- void testNestedIf() {
-
- Class>[] expClss = {
- RefPtg.class,
- AttrPtg.class, // A tAttrIf
- RefPtg.class,
- AttrPtg.class, // B tAttrIf
- IntPtg.class,
- AttrPtg.class, // B tAttrSkip
- IntPtg.class,
- AttrPtg.class, // B tAttrSkip
- FuncVarPtg.class,
- AttrPtg.class, // A tAttrSkip
- RefPtg.class,
- AttrPtg.class, // C tAttrIf
- IntPtg.class,
- AttrPtg.class, // C tAttrSkip
- IntPtg.class,
- AttrPtg.class, // C tAttrSkip
- FuncVarPtg.class,
- AttrPtg.class, // A tAttrSkip
- FuncVarPtg.class,
- };
-
- Ptg[] ptgs = confirmTokenClasses("if(A1,if(B1,1,2),if(C1,3,4))", expClss);
- confirmAttrData(ptgs, 1, 31);
- confirmAttrData(ptgs, 3, 7);
- confirmAttrData(ptgs, 5, 10);
- confirmAttrData(ptgs, 7, 3);
- confirmAttrData(ptgs, 9, 34);
- confirmAttrData(ptgs, 11, 7);
- confirmAttrData(ptgs, 13, 10);
- confirmAttrData(ptgs, 15, 3);
- confirmAttrData(ptgs, 17, 3);
- }
-
- @Test
- void testEmbeddedIf() {
- Ptg[] ptgs = parseFormula("IF(3>=1,\"*\",IF(4<>1,\"first\",\"second\"))");
- assertEquals(17, ptgs.length);
-
- assertEquals(AttrPtg.class, ptgs[5].getClass(), "6th Ptg is not a goto (Attr) ptg");
- assertEquals(NotEqualPtg.class, ptgs[8].getClass(), "9th Ptg is not a not equal ptg");
- assertEquals(FuncVarPtg.class, ptgs[14].getClass(), "15th Ptg is not the inner IF variable function ptg");
- }
-
- @Test
- void testSimpleLogical() {
- Ptg[] ptgs = parseFormula("IF(A1
- * TODO get OOO documentation updated to reflect this (that EXTERNALBOOK is optional).
- *
- * It's not clear what exact steps need to be taken in Excel to create such a workbook
- */
- @Test
- void testLinkTableWithoutExternalBookRecord_bug45046() {
- // Bug 45046 b: DEFINEDNAME is part of LinkTable
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex45046-21984.xls");
- // some other sanity checks
- assertEquals(3, wb.getNumberOfSheets());
- String formula = wb.getSheetAt(0).getRow(4).getCell(13).getCellFormula();
-
- // The reported symptom of this bugzilla is an earlier bug (already fixed)
- // This is observable in version 3.0
- assertNotEquals("ipcSummenproduktIntern($P5,N$6,$A$9,N$5)", formula);
-
- assertEquals("ipcSummenproduktIntern($C5,N$2,$A$9,N$1)", formula);
- }
-
- @Test
- void testMultipleExternSheetRecords_bug45698() {
- // Bug: Extern sheet is part of LinkTable
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex45698-22488.xls");
- // some other sanity checks
- assertEquals(7, wb.getNumberOfSheets());
- }
-
- @Test
- void testExtraSheetRefs_bug45978() {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex45978-extraLinkTableSheets.xls");
- /*
- ex45978-extraLinkTableSheets.xls is a cut-down version of attachment 22561.
- The original file produces the same error.
-
- This bug was caused by a combination of invalid sheet indexes in the EXTERNSHEET
- record, and eager initialisation of the extern sheet references. Note - the workbook
- has 2 sheets, but the EXTERNSHEET record refers to sheet indexes 0, 1 and 2.
-
- Offset 0x3954 (14676)
- recordid = 0x17, size = 32
- [EXTERNSHEET]
- numOfRefs = 5
- refrec #0: extBook=0 firstSheet=0 lastSheet=0
- refrec #1: extBook=1 firstSheet=2 lastSheet=2
- refrec #2: extBook=2 firstSheet=1 lastSheet=1
- refrec #3: extBook=0 firstSheet=-1 lastSheet=-1
- refrec #4: extBook=0 firstSheet=1 lastSheet=1
- [/EXTERNSHEET]
-
- As it turns out, the formula in question doesn't even use externSheetIndex #1 - it
- uses #4, which resolves to sheetIndex 1 -> 'Data'.
-
- It is not clear exactly what externSheetIndex #4 would refer to. Excel seems to
- display such a formula as "''!$A2", but then complains of broken link errors.
- */
-
- HSSFCell cell = wb.getSheetAt(0).getRow(1).getCell(1);
- // Bug: IndexOutOfBoundsException - Index: 2, Size: 2
- String cellFormula = cell.getCellFormula();
- assertEquals("Data!$A2", cellFormula);
- }
-
- /**
- * This problem was visible in POI svn r763332
- * when reading the workbook of attachment 23468 from bugzilla 47001
- */
- @Test
- void testMissingExternSheetRecord_bug47001b() {
-
- Record[] recs = {
- SupBookRecord.createAddInFunctions(),
- new SSTRecord(),
- };
- List recList = Arrays.asList(recs);
- WorkbookRecordList wrl = new WorkbookRecordList();
-
- // Bug 47001b: Expected an EXTERNSHEET record but got (org.apache.poi.hssf.record.SSTRecord)
- LinkTable lt = new LinkTable(recList, 0, wrl, Collections.emptyMap());
- assertNotNull(lt);
- }
-
- @Test
- void testNameCommentRecordBetweenNameRecords() {
-
- final Record[] recs = {
- new NameRecord(),
- new NameCommentRecord("name1", "comment1"),
- new NameRecord(),
- new NameCommentRecord("name2", "comment2"),
-
- };
- final List recList = Arrays.asList(recs);
- final WorkbookRecordList wrl = new WorkbookRecordList();
- final Map commentRecords = new LinkedHashMap<>();
-
- final LinkTable lt = new LinkTable(recList, 0, wrl, commentRecords);
- assertNotNull(lt);
-
- assertEquals(2, commentRecords.size());
- assertSame(recs[1], commentRecords.get("name1")); //== is intentionally not .equals()!
- assertSame(recs[3], commentRecords.get("name2")); //== is intentionally not .equals()!
-
- assertEquals(2, lt.getNumNames());
- }
-
- @Test
- void testAddNameX(){
- WorkbookRecordList wrl = new WorkbookRecordList();
- wrl.add(0, new BOFRecord());
- wrl.add(1, new CountryRecord());
- wrl.add(2, EOFRecord.instance);
-
- int numberOfSheets = 3;
- LinkTable tbl = new LinkTable(numberOfSheets, wrl);
- // creation of a new LinkTable insert two new records: SupBookRecord followed by ExternSheetRecord
- // assure they are in place:
- // [BOFRecord]
- // [CountryRecord]
- // [SUPBOOK Internal References nSheets= 3]
- // [EXTERNSHEET]
- // [EOFRecord]
-
- assertEquals(5, wrl.getRecords().size());
- assertTrue(wrl.get(2) instanceof SupBookRecord);
- SupBookRecord sup1 = (SupBookRecord)wrl.get(2);
- assertEquals(numberOfSheets, sup1.getNumberOfSheets());
- assertTrue(wrl.get(3) instanceof ExternSheetRecord);
- ExternSheetRecord extSheet = (ExternSheetRecord)wrl.get(3);
- assertEquals(0, extSheet.getNumOfRefs());
-
- assertNull(tbl.getNameXPtg("ISODD", -1));
- assertEquals(5, wrl.getRecords().size()); //still have five records
-
- NameXPtg namex1 = tbl.addNameXPtg("ISODD"); // adds two new rercords
- assertEquals(0, namex1.getSheetRefIndex());
- assertEquals(0, namex1.getNameIndex());
- NameXPtg act = tbl.getNameXPtg("ISODD", -1);
- assertNotNull(act);
- assertEquals(namex1.toString(), act.toString());
-
- // Can only find on the right sheet ref, if restricting
- act = tbl.getNameXPtg("ISODD", 0);
- assertNotNull(act);
- assertEquals(namex1.toString(), act.toString());
- assertNull(tbl.getNameXPtg("ISODD", 1));
- assertNull(tbl.getNameXPtg("ISODD", 2));
-
- // assure they are in place:
- // [BOFRecord]
- // [CountryRecord]
- // [SUPBOOK Internal References nSheets= 3]
- // [SUPBOOK Add-In Functions nSheets= 1]
- // [EXTERNALNAME .name = ISODD]
- // [EXTERNSHEET]
- // [EOFRecord]
-
- assertEquals(7, wrl.getRecords().size());
- assertTrue(wrl.get(3) instanceof SupBookRecord);
- SupBookRecord sup2 = (SupBookRecord)wrl.get(3);
- assertTrue(sup2.isAddInFunctions());
- assertTrue(wrl.get(4) instanceof ExternalNameRecord);
- ExternalNameRecord ext1 = (ExternalNameRecord)wrl.get(4);
- assertEquals("ISODD", ext1.getText());
- assertTrue(wrl.get(5) instanceof ExternSheetRecord);
- assertEquals(1, extSheet.getNumOfRefs());
-
- //check that
- assertEquals(0, tbl.resolveNameXIx(namex1.getSheetRefIndex(), namex1.getNameIndex()));
- assertEquals("ISODD", tbl.resolveNameXText(namex1.getSheetRefIndex(), namex1.getNameIndex(), null));
-
- assertNull(tbl.getNameXPtg("ISEVEN", -1));
- NameXPtg namex2 = tbl.addNameXPtg("ISEVEN"); // adds two new rercords
- assertEquals(0, namex2.getSheetRefIndex());
- assertEquals(1, namex2.getNameIndex()); // name index increased by one
- act = tbl.getNameXPtg("ISEVEN", -1);
- assertNotNull(act);
- assertEquals(namex2.toString(), act.toString());
- assertEquals(8, wrl.getRecords().size());
- // assure they are in place:
- // [BOFRecord]
- // [CountryRecord]
- // [SUPBOOK Internal References nSheets= 3]
- // [SUPBOOK Add-In Functions nSheets= 1]
- // [EXTERNALNAME .name = ISODD]
- // [EXTERNALNAME .name = ISEVEN]
- // [EXTERNSHEET]
- // [EOFRecord]
- assertTrue(wrl.get(3) instanceof SupBookRecord);
- assertTrue(wrl.get(4) instanceof ExternalNameRecord);
- assertTrue(wrl.get(5) instanceof ExternalNameRecord);
- assertEquals("ISODD", ((ExternalNameRecord)wrl.get(4)).getText());
- assertEquals("ISEVEN", ((ExternalNameRecord)wrl.get(5)).getText());
- assertTrue(wrl.get(6) instanceof ExternSheetRecord);
- assertTrue(wrl.get(7) instanceof EOFRecord);
-
- assertEquals(0, tbl.resolveNameXIx(namex2.getSheetRefIndex(), namex2.getNameIndex()));
- assertEquals("ISEVEN", tbl.resolveNameXText(namex2.getSheetRefIndex(), namex2.getNameIndex(), null));
-
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestOperandClassTransformer.java b/src/testcases/org/apache/poi/hssf/model/TestOperandClassTransformer.java
deleted file mode 100644
index f36ee053a8..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestOperandClassTransformer.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.model;
-
-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 org.apache.poi.ss.formula.eval.BlankEval;
-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.EvalFactory;
-import org.apache.poi.ss.formula.functions.MatrixFunction;
-import org.apache.poi.ss.formula.ptg.AbstractFunctionPtg;
-import org.apache.poi.ss.formula.ptg.FuncVarPtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests specific formula examples in OperandClassTransformer.
- */
-final class TestOperandClassTransformer {
-
- private static Ptg[] parseFormula(String formula) {
- Ptg[] result = HSSFFormulaParser.parse(formula, null);
- assertNotNull(result, "Ptg array should not be null");
- return result;
- }
-
- @Test
- void testMdeterm() {
- String formula = "MDETERM(ABS(A1))";
- Ptg[] ptgs = parseFormula(formula);
-
- confirmTokenClass(ptgs, 0, Ptg.CLASS_ARRAY);
- confirmFuncClass(ptgs, 1, "ABS", Ptg.CLASS_ARRAY);
- confirmFuncClass(ptgs, 2, "MDETERM", Ptg.CLASS_VALUE);
- }
-
- @Test
- void testMdetermReturnsValueInvalidOnABlankCell() {
- ValueEval matrixRef = EvalFactory.createAreaEval("A1:B2",
- new ValueEval[]{
- BlankEval.instance,
- new NumberEval(1),
- new NumberEval(2),
- new NumberEval(3)
- }
- );
- ValueEval result = MatrixFunction.MDETERM.evaluate(new ValueEval[]{matrixRef} , 0, 0);
- assertEquals(ErrorEval.VALUE_INVALID, result);
- }
-
- /**
- * In the example: INDEX(PI(),1)
, Excel encodes PI() as 'array'. It is not clear
- * what rule justifies this. POI currently encodes it as 'value' which Excel(2007) seems to
- * tolerate. Changing the metadata for INDEX to have first parameter as 'array' class breaks
- * other formulas involving INDEX. It seems like a special case needs to be made. Perhaps an
- * important observation is that INDEX is one of very few functions that returns 'reference' type.
- *
- * This test has been added but disabled in order to document this issue.
- */
- @Test
- @Disabled
- void testIndexPi1() {
- String formula = "INDEX(PI(),1)";
- Ptg[] ptgs = parseFormula(formula);
-
- confirmFuncClass(ptgs, 1, "PI", Ptg.CLASS_ARRAY); // fails as of POI 3.1
- confirmFuncClass(ptgs, 2, "INDEX", Ptg.CLASS_VALUE);
- }
-
- /**
- * Even though count expects args of type R, because A1 is a direct operand of a
- * value operator it must get type V
- */
- @Test
- void testDirectOperandOfValueOperator() {
- String formula = "COUNT(A1*1)";
- Ptg[] ptgs = parseFormula(formula);
- assertNotEquals(Ptg.CLASS_REF, ptgs[0].getPtgClass());
- confirmTokenClass(ptgs, 0, Ptg.CLASS_VALUE);
- confirmTokenClass(ptgs, 3, Ptg.CLASS_VALUE);
- }
-
- /**
- * A cell ref passed to a function expecting type V should be converted to type V
- */
- @Test
- void testRtoV() {
-
- String formula = "lookup(A1, A3:A52, B3:B52)";
- Ptg[] ptgs = parseFormula(formula);
- confirmTokenClass(ptgs, 0, Ptg.CLASS_VALUE);
- }
-
- @Test
- void testComplexIRR_bug45041() {
- String formula = "(1+IRR(SUMIF(A:A,ROW(INDIRECT(MIN(A:A)&\":\"&MAX(A:A))),B:B),0))^365-1";
- Ptg[] ptgs = parseFormula(formula);
-
- FuncVarPtg rowFunc = (FuncVarPtg) ptgs[10];
- FuncVarPtg sumifFunc = (FuncVarPtg) ptgs[12];
- assertEquals("ROW", rowFunc.getName());
- assertEquals("SUMIF", sumifFunc.getName());
-
- assertNotEquals(Ptg.CLASS_VALUE, rowFunc.getPtgClass());
- assertNotEquals(Ptg.CLASS_VALUE, sumifFunc.getPtgClass());
- confirmTokenClass(ptgs, 1, Ptg.CLASS_REF);
- confirmTokenClass(ptgs, 2, Ptg.CLASS_REF);
- confirmFuncClass(ptgs, 3, "MIN", Ptg.CLASS_VALUE);
- confirmTokenClass(ptgs, 6, Ptg.CLASS_REF);
- confirmFuncClass(ptgs, 7, "MAX", Ptg.CLASS_VALUE);
- confirmFuncClass(ptgs, 9, "INDIRECT", Ptg.CLASS_REF);
- confirmFuncClass(ptgs, 10, "ROW", Ptg.CLASS_ARRAY);
- confirmTokenClass(ptgs, 11, Ptg.CLASS_REF);
- confirmFuncClass(ptgs, 12, "SUMIF", Ptg.CLASS_ARRAY);
- confirmFuncClass(ptgs, 14, "IRR", Ptg.CLASS_VALUE);
- }
-
- private void confirmFuncClass(Ptg[] ptgs, int i, String expectedFunctionName, byte operandClass) {
- confirmTokenClass(ptgs, i, operandClass);
- AbstractFunctionPtg afp = (AbstractFunctionPtg) ptgs[i];
- assertEquals(expectedFunctionName, afp.getName());
- }
-
- private void confirmTokenClass(Ptg[] ptgs, int i, byte operandClass) {
- Ptg ptg = ptgs[i];
- assertFalse(ptg.isBaseToken(), "ptg[" + i + "] is a base token");
- assertEquals(operandClass, ptg.getPtgClass());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestRVA.java b/src/testcases/org/apache/poi/hssf/model/TestRVA.java
deleted file mode 100644
index 488a9e6fc5..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestRVA.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.model;
-
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Stream;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.usermodel.FormulaExtractor;
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFRow;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.ss.formula.ptg.AttrPtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.usermodel.CellType;
-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 'operand class' transformation performed by
- * OperandClassTransformer by comparing its results with those
- * directly produced by Excel (in a sample spreadsheet).
- */
-final class TestRVA {
-
- private static final String NEW_LINE = System.getProperty("line.separator");
- private static POIFSFileSystem poifs;
- private static HSSFWorkbook workbook;
-
-
- @AfterAll
- public static void closeResource() throws Exception {
- workbook.close();
- poifs.close();
- }
-
- public static Stream data() throws Exception {
- poifs = new POIFSFileSystem(HSSFTestDataSamples.getSampleFile("testRVA.xls"), true);
- workbook = new HSSFWorkbook(poifs);
- HSSFSheet sheet = workbook.getSheetAt(0);
-
- List data = new ArrayList<>();
-
- for (int rowIdx = 0; true; rowIdx++) {
- HSSFRow row = sheet.getRow(rowIdx);
- if (row == null) {
- break;
- }
- HSSFCell cell = row.getCell(0);
- if (cell == null || cell.getCellType() == CellType.BLANK) {
- break;
- }
-
- String formula = cell.getCellFormula();
- data.add(Arguments.of(cell,formula));
- }
-
- return data.stream();
- }
-
- @ParameterizedTest
- @MethodSource("data")
- void confirmCell(HSSFCell formulaCell, String formula) {
- Ptg[] excelPtgs = FormulaExtractor.getPtgs(formulaCell);
- Ptg[] poiPtgs = HSSFFormulaParser.parse(formula, workbook);
- int nExcelTokens = excelPtgs.length;
- int nPoiTokens = poiPtgs.length;
- if (nExcelTokens != nPoiTokens) {
- assertTrue(nExcelTokens == nPoiTokens + 1 && excelPtgs[0].getClass() == AttrPtg.class,
- "Expected " + nExcelTokens + " tokens but got " + nPoiTokens);
-
- // compensate for missing tAttrVolatile, which belongs in any formula
- // involving OFFSET() et al. POI currently does not insert where required
- Ptg[] temp = new Ptg[nExcelTokens];
- temp[0] = excelPtgs[0];
- System.arraycopy(poiPtgs, 0, temp, 1, nPoiTokens);
- poiPtgs = temp;
- }
- boolean hasMismatch = false;
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < nExcelTokens; i++) {
- Ptg poiPtg = poiPtgs[i];
- Ptg excelPtg = excelPtgs[i];
- if (excelPtg.getClass() != poiPtg.getClass()) {
- hasMismatch = true;
- sb.append(" mismatch token type[").append(i).append("] ").append(getShortClassName(excelPtg)).append(" ").append(excelPtg.getRVAType()).append(" - ").append(getShortClassName(poiPtg)).append(" ").append(poiPtg.getRVAType());
- sb.append(NEW_LINE);
- continue;
- }
- if (poiPtg.isBaseToken()) {
- continue;
- }
- sb.append(" token[").append(i).append("] ").append(excelPtg).append(" ").append(excelPtg.getRVAType());
-
- if (excelPtg.getPtgClass() != poiPtg.getPtgClass()) {
- hasMismatch = true;
- sb.append(" - was ").append(poiPtg.getRVAType());
- }
- sb.append(NEW_LINE);
- }
- assertFalse(hasMismatch);
- }
-
- private String getShortClassName(Object o) {
- String cn = o.getClass().getName();
- int pos = cn.lastIndexOf('.');
- return cn.substring(pos + 1);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java b/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java
deleted file mode 100644
index fde901216b..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.model;
-
-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.util.Arrays;
-
-import org.apache.poi.hssf.record.NumberRecord;
-import org.apache.poi.hssf.record.Record;
-import org.apache.poi.hssf.record.RowRecord;
-import org.apache.poi.hssf.record.UnknownRecord;
-import org.apache.poi.hssf.record.WindowTwoRecord;
-import org.apache.poi.hssf.record.pivottable.ViewDefinitionRecord;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link RowBlocksReader}
- *
- * @author Josh Micich
- */
-final class TestRowBlocksReader {
- @Test
- void testAbnormalPivotTableRecords_bug46280() {
- int SXVIEW_SID = ViewDefinitionRecord.sid;
- Record[] inRecs = {
- new RowRecord(0),
- new NumberRecord(),
- // normally MSODRAWING(0x00EC) would come here before SXVIEW
- new UnknownRecord(SXVIEW_SID, "dummydata (SXVIEW: View Definition)".getBytes(LocaleUtil.CHARSET_1252)),
- new WindowTwoRecord(),
- };
- RecordStream rs = new RecordStream(Arrays.asList(inRecs), 0);
- RowBlocksReader rbr = new RowBlocksReader(rs);
- assertNotEquals(WindowTwoRecord.class, rs.peekNextClass(),
- "Should have stopped at the SXVIEW record - Identified bug 46280b");
-
- RecordStream rbStream = rbr.getPlainRecordStream();
- assertEquals(inRecs[0], rbStream.getNext());
- assertEquals(inRecs[1], rbStream.getNext());
- assertFalse(rbStream.hasNext());
- assertTrue(rs.hasNext());
- assertEquals(inRecs[2], rs.getNext());
- assertEquals(inRecs[3], rs.getNext());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestSheet.java b/src/testcases/org/apache/poi/hssf/model/TestSheet.java
deleted file mode 100644
index aef0c5e40b..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestSheet.java
+++ /dev/null
@@ -1,784 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.model;
-
-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.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.poi.ddf.EscherDggRecord;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.*;
-import org.apache.poi.hssf.record.aggregates.ConditionalFormattingTable;
-import org.apache.poi.hssf.record.aggregates.PageSettingsBlock;
-import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor;
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFRichTextString;
-import org.apache.poi.hssf.usermodel.HSSFRow;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.ss.SpreadsheetVersion;
-import org.apache.poi.ss.formula.FormulaShifter;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Unit test for the {@link InternalSheet} class.
- */
-final class TestSheet {
- private static InternalSheet createSheet(List inRecs) {
- return InternalSheet.createSheet(new RecordStream(inRecs, 0));
- }
-
- @Test
- void testCreateSheet() {
- // Check we're adding row and cell aggregates
- List records = new ArrayList<>();
- records.add(BOFRecord.createSheetBOF());
- records.add( new DimensionsRecord() );
- records.add(createWindow2Record());
- records.add(EOFRecord.instance);
- InternalSheet sheet = createSheet(records);
-
- List outRecs = new ArrayList<>();
- sheet.visitContainedRecords(outRecs::add, 0);
-
- Iterator iter = outRecs.iterator();
- assertTrue(iter.next() instanceof BOFRecord );
- assertTrue(iter.next() instanceof IndexRecord);
- assertTrue(iter.next() instanceof DimensionsRecord);
- assertTrue(iter.next() instanceof WindowTwoRecord );
- assertTrue(iter.next() instanceof EOFRecord);
- }
-
- private static org.apache.poi.hssf.record.Record createWindow2Record() {
- WindowTwoRecord result = new WindowTwoRecord();
- result.setOptions(( short ) 0x6b6);
- result.setTopRow(( short ) 0);
- result.setLeftCol(( short ) 0);
- result.setHeaderColor(0x40);
- result.setPageBreakZoom(( short ) 0);
- result.setNormalZoom(( short ) 0);
- return result;
- }
-
- private static final class MergedCellListener implements RecordVisitor {
-
- private int _count;
- public MergedCellListener() {
- _count = 0;
- }
- @Override
- public void visitRecord(org.apache.poi.hssf.record.Record r) {
- if (r instanceof MergeCellsRecord) {
- _count++;
- }
- }
- public int getCount() {
- return _count;
- }
- }
-
- @Test
- void testAddMergedRegion() {
- InternalSheet sheet = InternalSheet.createSheet();
- final int regionsToAdd = 4096;
-
- //simple test that adds a load of regions
- for (int n = 0; n < regionsToAdd; n++)
- {
- int index = sheet.addMergedRegion(0, (short) 0, 1, (short) 1);
- assertEquals(index, n, "Merged region index expected to be " + n + " got " + index);
- }
-
- //test all the regions were indeed added
- assertEquals(sheet.getNumMergedRegions(), regionsToAdd);
-
- //test that the regions were spread out over the appropriate number of records
- MergedCellListener mcListener = new MergedCellListener();
- sheet.visitContainedRecords(mcListener, 0);
- int recordsAdded = mcListener.getCount();
- int recordsExpected = regionsToAdd/1027;
- //noinspection ConstantConditions
- if ((regionsToAdd % 1027) != 0) {
- recordsExpected++;
- }
- assertEquals(recordsAdded, recordsExpected,
- "The " + regionsToAdd + " merged regions should have been spread out over "
- + recordsExpected + " records, not " + recordsAdded);
- // Check we can't add one with invalid date
- IllegalArgumentException e;
- e = assertThrows(IllegalArgumentException.class, () -> sheet.addMergedRegion(10, (short)10, 9, (short)12));
- assertEquals("The 'to' row (9) must not be less than the 'from' row (10)", e.getMessage());
-
- e = assertThrows(IllegalArgumentException.class, () -> sheet.addMergedRegion(10, (short)10, 12, (short)9));
- assertEquals("The 'to' col (9) must not be less than the 'from' col (10)", e.getMessage());
- }
-
- @Test
- void testRemoveMergedRegion() {
- InternalSheet sheet = InternalSheet.createSheet();
- int regionsToAdd = 4096;
-
- for (int n = 0; n < regionsToAdd; n++) {
- sheet.addMergedRegion(n, 0, n, 1);
- }
-
- int nSheetRecords = sheet.getRecords().size();
-
- //remove a third from the beginning
- for (int n = 0; n < regionsToAdd/3; n++)
- {
- sheet.removeMergedRegion(0);
- //assert they have been deleted
- assertEquals(regionsToAdd - n - 1, sheet.getNumMergedRegions(), "Num of regions");
- }
-
- // merge records are removed from within the MergedCellsTable,
- // so the sheet record count should not change
- assertEquals(nSheetRecords, sheet.getRecords().size(), "Sheet Records");
- }
-
- /**
- * Bug: 22922 (Reported by Xuemin Guan)
- *
- * Remove mergedregion fails when a sheet loses records after an initial CreateSheet
- * fills up the records.
- *
- */
- @Test
- void testMovingMergedRegion() {
- List records = new ArrayList<>();
-
- CellRangeAddress[] cras = {
- new CellRangeAddress(0, 1, 0, 2),
- };
- MergeCellsRecord merged = new MergeCellsRecord(cras, 0, cras.length);
- records.add(BOFRecord.createSheetBOF());
- records.add(new DimensionsRecord());
- records.add(new RowRecord(0));
- records.add(new RowRecord(1));
- records.add(new RowRecord(2));
- records.add(createWindow2Record());
- records.add(EOFRecord.instance);
- records.add(merged);
-
- InternalSheet sheet = createSheet(records);
- sheet.getRecords().remove(0); // TODO - what does this line do?
-
- //stub object to throw off list INDEX operations
- sheet.removeMergedRegion(0);
- assertEquals(0, sheet.getNumMergedRegions(), "Should be no more merged regions");
- }
-
- // @Test
- // void testGetMergedRegionAt() {
- // TODO
- // }
-
- // @Test
- // void testGetNumMergedRegions() {
- // TODO
- // }
-
- /**
- * Makes sure all rows registered for this sheet are aggregated, they were being skipped
- *
- */
- @Test
- void testRowAggregation() {
- List records = new ArrayList<>();
-
- records.add(InternalSheet.createBOF());
- records.add(new DimensionsRecord());
- records.add(new RowRecord(0));
- records.add(new RowRecord(1));
- FormulaRecord formulaRecord = new FormulaRecord();
- formulaRecord.setCachedResultTypeString();
- records.add(formulaRecord);
- records.add(new StringRecord());
- records.add(new RowRecord(2));
- records.add(createWindow2Record());
- records.add(EOFRecord.instance);
-
- InternalSheet sheet = createSheet(records);
- assertNotNull(sheet.getRow(2), "Row [2] was skipped");
- }
-
- /**
- * Make sure page break functionality works (in memory)
- *
- */
- @Test
- void testRowPageBreaks() {
- short colFrom = 0;
- short colTo = 255;
-
- InternalSheet worksheet = InternalSheet.createSheet();
- PageSettingsBlock sheet = worksheet.getPageSettings();
- sheet.setRowBreak(0, colFrom, colTo);
-
- assertTrue(sheet.isRowBroken(0), "no row break at 0");
- assertEquals(1, sheet.getNumRowBreaks(), "1 row break available");
-
- sheet.setRowBreak(0, colFrom, colTo);
- sheet.setRowBreak(0, colFrom, colTo);
-
- assertTrue(sheet.isRowBroken(0), "no row break at 0");
- assertEquals(1, sheet.getNumRowBreaks(), "1 row break available");
-
- sheet.setRowBreak(10, colFrom, colTo);
- sheet.setRowBreak(11, colFrom, colTo);
-
- assertTrue(sheet.isRowBroken(10), "no row break at 10");
- assertTrue(sheet.isRowBroken(11), "no row break at 11");
- assertEquals(3, sheet.getNumRowBreaks(), "3 row break available");
-
-
- boolean is10 = false;
- boolean is0 = false;
- boolean is11 = false;
-
- int[] rowBreaks = sheet.getRowBreaks();
- for (int main : rowBreaks) {
- assertTrue(main == 0 || main == 10 || main == 11, "Invalid page break");
- if (main == 0) is0 = true;
- if (main == 10) is10 = true;
- if (main == 11) is11 = true;
- }
-
- assertTrue(is0 && is10 && is11, "one of the breaks didnt make it");
-
- sheet.removeRowBreak(11);
- assertFalse(sheet.isRowBroken(11), "row should be removed");
-
- sheet.removeRowBreak(0);
- assertFalse(sheet.isRowBroken(0), "row should be removed");
-
- sheet.removeRowBreak(10);
- assertFalse(sheet.isRowBroken(10), "row should be removed");
-
- assertEquals(0, sheet.getNumRowBreaks(), "no more breaks");
- }
-
- /**
- * Make sure column pag breaks works properly (in-memory)
- *
- */
- @Test
- void testColPageBreaks() {
- short rowFrom = 0;
- short rowTo = (short)65535;
-
- InternalSheet worksheet = InternalSheet.createSheet();
- PageSettingsBlock sheet = worksheet.getPageSettings();
- sheet.setColumnBreak((short)0, rowFrom, rowTo);
-
- assertTrue(sheet.isColumnBroken(0), "no col break at 0");
- assertEquals(1, sheet.getNumColumnBreaks(), "1 col break available");
-
- sheet.setColumnBreak((short)0, rowFrom, rowTo);
-
- assertTrue(sheet.isColumnBroken(0), "no col break at 0");
- assertEquals(1, sheet.getNumColumnBreaks(), "1 col break available");
-
- sheet.setColumnBreak((short)1, rowFrom, rowTo);
- sheet.setColumnBreak((short)10, rowFrom, rowTo);
- sheet.setColumnBreak((short)15, rowFrom, rowTo);
-
- assertTrue(sheet.isColumnBroken(1), "no col break at 1");
- assertTrue(sheet.isColumnBroken(10), "no col break at 10");
- assertTrue(sheet.isColumnBroken(15), "no col break at 15");
- assertEquals(4, sheet.getNumColumnBreaks(), "4 col break available");
-
- boolean is10 = false;
- boolean is0 = false;
- boolean is1 = false;
- boolean is15 = false;
-
- int[] colBreaks = sheet.getColumnBreaks();
- for (int main : colBreaks) {
- assertTrue(main == 0 || main == 1 || main == 10 || main == 15, "Invalid page break");
- if (main == 0) is0 = true;
- if (main == 1) is1 = true;
- if (main == 10) is10= true;
- if (main == 15) is15 = true;
- }
-
- assertTrue(is0 && is1 && is10 && is15, "one of the breaks didnt make it");
-
- sheet.removeColumnBreak(15);
- assertFalse(sheet.isColumnBroken(15), "column break should not be there");
-
- sheet.removeColumnBreak(0);
- assertFalse(sheet.isColumnBroken(0), "column break should not be there");
-
- sheet.removeColumnBreak(1);
- assertFalse(sheet.isColumnBroken(1), "column break should not be there");
-
- sheet.removeColumnBreak(10);
- assertFalse(sheet.isColumnBroken(10), "column break should not be there");
-
- assertEquals(0, sheet.getNumColumnBreaks(), "no more breaks");
- }
-
- /**
- * test newly added method Sheet.getXFIndexForColAt(..)
- * works as designed.
- */
- @Test
- void testXFIndexForColumn() {
- final short TEST_IDX = 10;
- final short DEFAULT_IDX = 0xF; // 15
- InternalSheet sheet = InternalSheet.createSheet();
-
- // without ColumnInfoRecord
- int xfindex = sheet.getXFIndexForColAt((short) 0);
- assertEquals(DEFAULT_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 1);
- assertEquals(DEFAULT_IDX, xfindex);
-
- ColumnInfoRecord nci = new ColumnInfoRecord();
- sheet._columnInfos.insertColumn(nci);
-
- // single column ColumnInfoRecord
- nci.setFirstColumn((short) 2);
- nci.setLastColumn((short) 2);
- nci.setXFIndex(TEST_IDX);
- xfindex = sheet.getXFIndexForColAt((short) 0);
- assertEquals(DEFAULT_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 1);
- assertEquals(DEFAULT_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 2);
- assertEquals(TEST_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 3);
- assertEquals(DEFAULT_IDX, xfindex);
-
- // ten column ColumnInfoRecord
- nci.setFirstColumn((short) 2);
- nci.setLastColumn((short) 11);
- nci.setXFIndex(TEST_IDX);
- xfindex = sheet.getXFIndexForColAt((short) 1);
- assertEquals(DEFAULT_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 2);
- assertEquals(TEST_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 6);
- assertEquals(TEST_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 11);
- assertEquals(TEST_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 12);
- assertEquals(DEFAULT_IDX, xfindex);
-
- // single column ColumnInfoRecord starting at index 0
- nci.setFirstColumn((short) 0);
- nci.setLastColumn((short) 0);
- nci.setXFIndex(TEST_IDX);
- xfindex = sheet.getXFIndexForColAt((short) 0);
- assertEquals(TEST_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 1);
- assertEquals(DEFAULT_IDX, xfindex);
-
- // ten column ColumnInfoRecord starting at index 0
- nci.setFirstColumn((short) 0);
- nci.setLastColumn((short) 9);
- nci.setXFIndex(TEST_IDX);
- xfindex = sheet.getXFIndexForColAt((short) 0);
- assertEquals(TEST_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 7);
- assertEquals(TEST_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 9);
- assertEquals(TEST_IDX, xfindex);
- xfindex = sheet.getXFIndexForColAt((short) 10);
- assertEquals(DEFAULT_IDX, xfindex);
- }
-
- /**
- * Prior to bug 45066, POI would get the estimated sheet size wrong
- * when an UncalcedRecord was present.
- */
- @Test
- void testUncalcSize_bug45066() {
-
- List records = new ArrayList<>();
- records.add(BOFRecord.createSheetBOF());
- records.add(new UncalcedRecord());
- records.add(new DimensionsRecord());
- records.add(createWindow2Record());
- records.add(EOFRecord.instance);
- InternalSheet sheet = createSheet(records);
-
- // The original bug was due to different logic for collecting records for sizing and
- // serialization. The code has since been refactored into a single method for visiting
- // all contained records. Now this test is much less interesting
- int[] totalSize = { 0 };
- byte[] buf = new byte[100];
-
- sheet.visitContainedRecords(r -> {
- int estimatedSize = r.getRecordSize();
- int serializedSize = r.serialize(0, buf);
- assertEquals(estimatedSize, serializedSize, "serialized size mismatch for record (" + r.getClass().getName() + ")");
- totalSize[0] += estimatedSize;
- }, 0);
- assertEquals(90, totalSize[0]);
- }
-
- /**
- * Prior to bug 45145 RowRecordsAggregate and ValueRecordsAggregate could
- * sometimes occur in reverse order. This test reproduces one of those situations and makes
- * sure that RRA comes before VRA.
- *
- * The code here represents a normal POI use case where a spreadsheet is created from scratch.
- */
- @Test
- void testRowValueAggregatesOrder_bug45145() {
-
- InternalSheet sheet = InternalSheet.createSheet();
-
- RowRecord rr = new RowRecord(5);
- sheet.addRow(rr);
-
- CellValueRecordInterface cvr = new BlankRecord();
- cvr.setColumn((short)0);
- cvr.setRow(5);
- sheet.addValueRecord(5, cvr);
-
-
- int dbCellRecordPos = getDbCellRecordPos(sheet);
- // The overt symptom of the bug
- // DBCELL record pos is calculated wrong if VRA comes before RRA
- assertNotEquals (252, dbCellRecordPos);
-
-// if (false) {
-// // make sure that RRA and VRA are in the right place
-// // (Aug 2008) since the VRA is now part of the RRA, there is much less chance that
-// // they could get out of order. Still, one could write serialize the sheet here,
-// // and read back with EventRecordFactory to make sure...
-// }
- assertEquals(242, dbCellRecordPos);
- }
-
- /**
- * @return the value calculated for the position of the first DBCELL record for this sheet.
- * That value is found on the IndexRecord.
- */
- private static int getDbCellRecordPos(InternalSheet sheet) {
-
- MyIndexRecordListener myIndexListener = new MyIndexRecordListener();
- sheet.visitContainedRecords(myIndexListener, 0);
- IndexRecord indexRecord = myIndexListener.getIndexRecord();
- return indexRecord.getDbcellAt(0);
- }
-
- private static final class MyIndexRecordListener implements RecordVisitor {
-
- private IndexRecord _indexRecord;
- public MyIndexRecordListener() {
- // no-arg constructor
- }
- public IndexRecord getIndexRecord() {
- return _indexRecord;
- }
- @Override
- public void visitRecord(org.apache.poi.hssf.record.Record r) {
- if (r instanceof IndexRecord) {
- if (_indexRecord != null) {
- throw new RuntimeException("too many index records");
- }
- _indexRecord = (IndexRecord)r;
- }
- }
- }
-
- /**
- * Checks for bug introduced around r682282-r683880 that caused a second GUTS records
- * which in turn got the dimensions record out of alignment
- */
- @Test
- void testGutsRecord_bug45640() {
-
- InternalSheet sheet = InternalSheet.createSheet();
- sheet.addRow(new RowRecord(0));
- sheet.addRow(new RowRecord(1));
- sheet.groupRowRange( 0, 1, true );
- assertNotNull(sheet.toString());
- List recs = sheet.getRecords();
- long count = recs.stream().filter(r -> r instanceof GutsRecord).count();
- assertNotEquals(2, count);
- assertEquals(1, count);
- }
-
- @Test
- void testMisplacedMergedCellsRecords_bug45699() throws Exception {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex45698-22488.xls")) {
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFRow row = sheet.getRow(3);
- HSSFCell cell = row.getCell(4);
- assertNotNull(cell, "Identified bug 45699");
- assertEquals("Informations", cell.getRichStringCellValue().getString());
- }
- }
- /**
- * In 3.1, setting margins between creating first row and first cell caused an exception.
- */
- @Test
- void testSetMargins_bug45717() throws Exception {
- HSSFWorkbook workbook = new HSSFWorkbook();
- HSSFSheet sheet = workbook.createSheet("Vorschauliste");
- HSSFRow row = sheet.createRow(0);
-
- sheet.setMargin(HSSFSheet.LeftMargin, 0.3);
- try {
- row.createCell(0);
- } catch (IllegalStateException e) {
- if (e.getMessage().equals("Cannot create value records before row records exist")) {
- fail("Identified bug 45717");
- }
- throw e;
- } finally {
- workbook.close();
- }
- }
-
- /**
- * Some apps seem to write files with missing DIMENSION records.
- * Excel(2007) tolerates this, so POI should too.
- */
- @Test
- void testMissingDims() {
-
- int rowIx = 5;
- int colIx = 6;
- NumberRecord nr = new NumberRecord();
- nr.setRow(rowIx);
- nr.setColumn((short) colIx);
- nr.setValue(3.0);
-
- List inRecs = new ArrayList<>();
- inRecs.add(BOFRecord.createSheetBOF());
- inRecs.add(new RowRecord(rowIx));
- inRecs.add(nr);
- inRecs.add(createWindow2Record());
- inRecs.add(EOFRecord.instance);
- InternalSheet sheet = createSheet(inRecs);
-
- List outRecs = new ArrayList<>();
- sheet.visitContainedRecords(outRecs::add, rowIx);
- assertEquals(8, outRecs.size());
- DimensionsRecord dims = (DimensionsRecord) outRecs.get(5);
- assertEquals(rowIx, dims.getFirstRow());
- assertEquals(rowIx, dims.getLastRow());
- assertEquals(colIx, dims.getFirstCol());
- assertEquals(colIx, dims.getLastCol());
- }
-
- /**
- * Prior to the fix for bug 46547, shifting formulas would have the side-effect
- * of creating a {@link ConditionalFormattingTable}. There was no impairment to
- * functionality since empty record aggregates are equivalent to missing record
- * aggregates. However, since this unnecessary creation helped expose bug 46547b,
- * and since there is a slight performance hit the fix was made to avoid it.
- */
- @Test
- void testShiftFormulasAddCondFormat_bug46547() {
- // Create a sheet with data validity (similar to bugzilla attachment id=23131).
- InternalSheet sheet = InternalSheet.createSheet();
-
- List sheetRecs = sheet.getRecords();
- assertEquals(23, sheetRecs.size());
-
- FormulaShifter shifter = FormulaShifter.createForRowShift(0, "", 0, 0, 1, SpreadsheetVersion.EXCEL97);
- sheet.updateFormulasAfterCellShift(shifter, 0);
- assertFalse(sheetRecs.size() == 24 && sheetRecs.get(22) instanceof ConditionalFormattingTable);
- assertEquals(23, sheetRecs.size());
- }
- /**
- * Bug 46547 happened when attempting to add conditional formatting to a sheet
- * which already had data validity constraints.
- */
- @Test
- void testAddCondFormatAfterDataValidation_bug46547() {
- // Create a sheet with data validity (similar to bugzilla attachment id=23131).
- InternalSheet sheet = InternalSheet.createSheet();
- sheet.getOrCreateDataValidityTable();
-
- // attempt to add conditional formatting
- ConditionalFormattingTable cft = sheet.getConditionalFormattingTable();
- assertNotNull(cft);
- }
-
- @Test
- void testCloneMulBlank_bug46776() {
- org.apache.poi.hssf.record.Record[] recs = {
- InternalSheet.createBOF(),
- new DimensionsRecord(),
- new RowRecord(1),
- new MulBlankRecord(1, 3, new short[] { 0x0F, 0x0F, 0x0F, } ),
- new RowRecord(2),
- createWindow2Record(),
- EOFRecord.instance,
- };
-
- InternalSheet sheet = createSheet(Arrays.asList(recs));
-
- InternalSheet sheet2 = sheet.cloneSheet();
-
- List clonedRecs = new ArrayList<>();
- sheet2.visitContainedRecords(clonedRecs::add, 0);
- // +2 for INDEX and DBCELL
- assertEquals(recs.length+2, clonedRecs.size());
- }
-
- @Test
- void testCreateAggregate() {
- String msoDrawingRecord1 =
- "0F 00 02 F0 20 01 00 00 10 00 08 F0 08 00 00 00 \n" +
- "03 00 00 00 02 04 00 00 0F 00 03 F0 08 01 00 00 \n" +
- "0F 00 04 F0 28 00 00 00 01 00 09 F0 10 00 00 00 \n" +
- "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \n" +
- "02 00 0A F0 08 00 00 00 00 04 00 00 05 00 00 00 \n" +
- "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 \n" +
- "01 04 00 00 00 0A 00 00 73 00 0B F0 2A 00 00 00 \n" +
- "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 \n" +
- "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 \n" +
- "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 \n" +
- "00 00 00 00 01 00 54 00 05 00 45 00 01 00 88 03 \n" +
- "05 00 94 00 00 00 11 F0 00 00 00 00";
-
- String msoDrawingRecord2 =
- "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 " +
- "02 04 00 00 80 0A 00 00 73 00 0B F0 2A 00 00 00 " +
- "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 " +
- "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 " +
- "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 " +
- "00 00 00 00 01 00 8D 03 05 00 E4 00 03 00 4D 03 " +
- "0B 00 0C 00 00 00 11 F0 00 00 00 00";
-
- DrawingRecord d1 = new DrawingRecord();
- d1.setData( HexRead.readFromString( msoDrawingRecord1 ) );
-
- ObjRecord r1 = new ObjRecord();
-
- DrawingRecord d2 = new DrawingRecord();
- d2.setData( HexRead.readFromString( msoDrawingRecord2 ) );
-
- TextObjectRecord r2 = new TextObjectRecord();
- r2.setStr(new HSSFRichTextString("Aggregated"));
- NoteRecord n2 = new NoteRecord();
-
- List recordStream = new ArrayList<>();
- recordStream.add(InternalSheet.createBOF());
- recordStream.add( d1 );
- recordStream.add( r1 );
- recordStream.add(createWindow2Record());
- recordStream.add(EOFRecord.instance);
-
- confirmAggregatedRecords(recordStream);
-
-
- recordStream = new ArrayList<>();
- recordStream.add(InternalSheet.createBOF());
- recordStream.add( d1 );
- recordStream.add( r1 );
- recordStream.add( d2 );
- recordStream.add( r2 );
- recordStream.add(createWindow2Record());
- recordStream.add(EOFRecord.instance);
-
- confirmAggregatedRecords(recordStream);
-
- recordStream = new ArrayList<>();
- recordStream.add(InternalSheet.createBOF());
- recordStream.add( d1 );
- recordStream.add( r1 );
- recordStream.add( d2 );
- recordStream.add( r2 );
- recordStream.add( n2 );
- recordStream.add(createWindow2Record());
- recordStream.add(EOFRecord.instance);
-
- confirmAggregatedRecords(recordStream);
- }
-
- private void confirmAggregatedRecords(List recordStream){
- InternalSheet sheet = InternalSheet.createSheet();
- sheet.getRecords().clear();
- sheet.getRecords().addAll(recordStream);
-
- List sheetRecords = sheet.getRecords();
-
- DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord() );
- sheet.aggregateDrawingRecords(drawingManager, false);
-
- assertEquals(4, sheetRecords.size());
- assertEquals(BOFRecord.sid, ((org.apache.poi.hssf.record.Record)sheetRecords.get(0)).getSid());
- assertEquals(EscherAggregate.sid, ((org.apache.poi.hssf.record.Record)sheetRecords.get(1)).getSid());
- assertEquals(WindowTwoRecord.sid, ((org.apache.poi.hssf.record.Record)sheetRecords.get(2)).getSid());
- assertEquals(EOFRecord.sid, ((org.apache.poi.hssf.record.Record)sheetRecords.get(3)).getSid());
- }
-
- @Test
- void testSheetDimensions() {
- InternalSheet sheet = InternalSheet.createSheet();
- DimensionsRecord dimensions = (DimensionsRecord)sheet.findFirstRecordBySid(DimensionsRecord.sid);
- assertNotNull(dimensions);
- assertEquals(0, dimensions.getFirstCol());
- assertEquals(0, dimensions.getFirstRow());
- assertEquals(1, dimensions.getLastCol()); // plus pne
- assertEquals(1, dimensions.getLastRow()); // plus pne
-
- RowRecord rr = new RowRecord(0);
- sheet.addRow(rr);
-
- assertEquals(0, dimensions.getFirstCol());
- assertEquals(0, dimensions.getFirstRow());
- assertEquals(1, dimensions.getLastCol());
- assertEquals(1, dimensions.getLastRow());
-
- CellValueRecordInterface cvr;
-
- cvr = new BlankRecord();
- cvr.setColumn((short)0);
- cvr.setRow(0);
- sheet.addValueRecord(0, cvr);
-
- assertEquals(0, dimensions.getFirstCol());
- assertEquals(0, dimensions.getFirstRow());
- assertEquals(1, dimensions.getLastCol());
- assertEquals(1, dimensions.getLastRow());
-
- cvr = new BlankRecord();
- cvr.setColumn((short)1);
- cvr.setRow(0);
- sheet.addValueRecord(0, cvr);
-
- assertEquals(0, dimensions.getFirstCol());
- assertEquals(0, dimensions.getFirstRow());
- assertEquals(2, dimensions.getLastCol()); //YK: failed until Bugzilla 53414 was fixed
- assertEquals(1, dimensions.getLastRow());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java b/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java
deleted file mode 100644
index c58dd39849..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.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.hssf.model;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-import org.apache.poi.hssf.record.ColumnInfoRecord;
-import org.junit.jupiter.api.Test;
-
-final class TestSheetAdditional {
- @Test
- void testGetCellWidth() {
- InternalSheet sheet = InternalSheet.createSheet();
- ColumnInfoRecord nci = new ColumnInfoRecord();
-
- // Prepare test model
- nci.setFirstColumn(5);
- nci.setLastColumn(10);
- nci.setColumnWidth(100);
-
-
- sheet._columnInfos.insertColumn(nci);
-
- assertEquals(100,sheet.getColumnWidth(5));
- assertEquals(100,sheet.getColumnWidth(6));
- assertEquals(100,sheet.getColumnWidth(7));
- assertEquals(100,sheet.getColumnWidth(8));
- assertEquals(100,sheet.getColumnWidth(9));
- assertEquals(100,sheet.getColumnWidth(10));
-
- sheet.setColumnWidth(6,200);
-
- assertEquals(100,sheet.getColumnWidth(5));
- assertEquals(200,sheet.getColumnWidth(6));
- assertEquals(100,sheet.getColumnWidth(7));
- assertEquals(100,sheet.getColumnWidth(8));
- assertEquals(100,sheet.getColumnWidth(9));
- assertEquals(100,sheet.getColumnWidth(10));
- }
-
- @Test
- void testMaxColumnWidth() {
- InternalSheet sheet = InternalSheet.createSheet();
- // the limit
- sheet.setColumnWidth(0, 255*256);
-
- // over the limit
- IllegalArgumentException ex = assertThrows(
- IllegalArgumentException.class,
- () -> sheet.setColumnWidth(0, 256*256)
- );
- assertEquals("The maximum column width for an individual cell is 255 characters.", ex.getMessage());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java b/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java
deleted file mode 100644
index ba63dc70b7..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.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.hssf.record.CountryRecord;
-import org.apache.poi.hssf.record.FontRecord;
-import org.apache.poi.hssf.record.RecalcIdRecord;
-import org.apache.poi.hssf.record.WriteAccessRecord;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.hssf.usermodel.TestHSSFWorkbook;
-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.junit.jupiter.api.Test;
-
-/**
- * Unit test for the Workbook class.
- */
-final class TestWorkbook {
- @Test
- void testFontStuff() throws IOException {
- HSSFWorkbook hwb = new HSSFWorkbook();
- InternalWorkbook wb = TestHSSFWorkbook.getInternalWorkbook(hwb);
-
- assertEquals(4, wb.getNumberOfFontRecords());
- assertEquals(68, wb.getRecords().size());
-
- FontRecord f1 = wb.getFontRecordAt(0);
- FontRecord f4 = wb.getFontRecordAt(3);
-
- assertEquals(0, wb.getFontIndex(f1));
- assertEquals(3, wb.getFontIndex(f4));
-
- assertEquals(f1, wb.getFontRecordAt(0));
- assertEquals(f4, wb.getFontRecordAt(3));
-
- // There is no 4! new ones go in at 5
-
- FontRecord n = wb.createNewFont();
- assertEquals(69, wb.getRecords().size());
- assertEquals(5, wb.getNumberOfFontRecords());
- assertEquals(5, wb.getFontIndex(n));
- assertEquals(n, wb.getFontRecordAt(5));
-
- // And another
- FontRecord n6 = wb.createNewFont();
- assertEquals(70, wb.getRecords().size());
- assertEquals(6, wb.getNumberOfFontRecords());
- assertEquals(6, wb.getFontIndex(n6));
- assertEquals(n6, wb.getFontRecordAt(6));
-
-
- // Now remove the one formerly at 5
- assertEquals(70, wb.getRecords().size());
- wb.removeFontRecord(n);
-
- // Check that 6 has gone to 5
- assertEquals(69, wb.getRecords().size());
- assertEquals(5, wb.getNumberOfFontRecords());
- assertEquals(5, wb.getFontIndex(n6));
- assertEquals(n6, wb.getFontRecordAt(5));
-
- // Check that the earlier ones are unchanged
- assertEquals(0, wb.getFontIndex(f1));
- assertEquals(3, wb.getFontIndex(f4));
- assertEquals(f1, wb.getFontRecordAt(0));
- assertEquals(f4, wb.getFontRecordAt(3));
-
- // Finally, add another one
- FontRecord n7 = wb.createNewFont();
- assertEquals(70, wb.getRecords().size());
- assertEquals(6, wb.getNumberOfFontRecords());
- assertEquals(6, wb.getFontIndex(n7));
- assertEquals(n7, wb.getFontRecordAt(6));
-
- hwb.close();
- }
-
- @Test
- void testAddNameX() throws IOException {
- HSSFWorkbook hwb = new HSSFWorkbook();
- InternalWorkbook wb = TestHSSFWorkbook.getInternalWorkbook(hwb);
- assertNotNull(wb.getNameXPtg("ISODD", AggregatingUDFFinder.DEFAULT));
-
- FreeRefFunction NotImplemented = (args, ec) -> {
- throw new RuntimeException("not implemented");
- };
-
- /*
- * register the two test UDFs in a UDF finder, to be passed to the evaluator
- */
- UDFFinder udff1 = new DefaultUDFFinder(new String[] { "myFunc", },
- new FreeRefFunction[] { NotImplemented });
- UDFFinder udff2 = new DefaultUDFFinder(new String[] { "myFunc2", },
- new FreeRefFunction[] { NotImplemented });
- UDFFinder udff = new AggregatingUDFFinder(udff1, udff2);
- assertNotNull(wb.getNameXPtg("myFunc", udff));
- assertNotNull(wb.getNameXPtg("myFunc2", udff));
-
- assertNull(wb.getNameXPtg("myFunc3", udff)); // myFunc3 is unknown
-
- hwb.close();
- }
-
- @Test
- void testRecalcId() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- assertFalse(wb.getForceFormulaRecalculation());
-
- InternalWorkbook iwb = TestHSSFWorkbook.getInternalWorkbook(wb);
- int countryPos = iwb.findFirstRecordLocBySid(CountryRecord.sid);
- assertTrue(countryPos != -1);
- // RecalcIdRecord is not present in new workbooks
- assertNull(iwb.findFirstRecordBySid(RecalcIdRecord.sid));
- RecalcIdRecord record = iwb.getRecalcId();
- assertNotNull(record);
- assertSame(record, iwb.getRecalcId());
-
- assertSame(record, iwb.findFirstRecordBySid(RecalcIdRecord.sid));
- assertEquals(countryPos + 1, iwb.findFirstRecordLocBySid(RecalcIdRecord.sid));
-
- record.setEngineId(100);
- assertEquals(100, record.getEngineId());
- assertTrue(wb.getForceFormulaRecalculation());
-
- wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero
- assertEquals(0, record.getEngineId());
- assertFalse(wb.getForceFormulaRecalculation());
-
- wb.close();
- }
-
- @Test
- void testWriteAccess() {
- HSSFWorkbook wb = new HSSFWorkbook();
- InternalWorkbook iwb = TestHSSFWorkbook.getInternalWorkbook(wb);
-
- int oldRecordsCount = iwb.getNumRecords();
- assertEquals(68, oldRecordsCount, "records count");
-
- WriteAccessRecord writeAccess = iwb.getWriteAccess();
- assertNotNull(writeAccess);
- assertEquals(WriteAccessRecord.sid, writeAccess.getSid());
-
- int newRecordsCount = iwb.getNumRecords();
- assertEquals(oldRecordsCount, newRecordsCount, "records count after getWriteAccess");
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/model/TestWorkbookRecordList.java b/src/testcases/org/apache/poi/hssf/model/TestWorkbookRecordList.java
deleted file mode 100644
index bc610c42e8..0000000000
--- a/src/testcases/org/apache/poi/hssf/model/TestWorkbookRecordList.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.hssf.model;
-
-import org.apache.poi.hssf.record.chart.ChartRecord;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.junit.jupiter.api.Test;
-
-import java.io.IOException;
-
-import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-public class TestWorkbookRecordList {
-
- @Test
- public void tabposIsOnlyUpdatedIfWorkbookHasTabIdRecord() throws IOException {
- try (HSSFWorkbook wb = openSampleWorkbook("55982.xls")) {
- WorkbookRecordList records = wb.getInternalWorkbook().getWorkbookRecordList();
- assertEquals(-1, records.getTabpos());
-
- // Add an arbitrary record to the front of the list
- records.add(0, new ChartRecord());
-
- assertEquals(-1, records.getTabpos());
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java b/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java
deleted file mode 100644
index 8433fb4cb1..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.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.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.hssf.util.CellRangeAddress8Bit;
-import org.apache.poi.ss.formula.Formula;
-import org.apache.poi.ss.formula.FormulaParser;
-import org.apache.poi.ss.formula.FormulaRenderer;
-import org.apache.poi.ss.formula.FormulaType;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-final class TestArrayRecord {
-
- @Test
- void testRead() {
- String hex =
- "21 02 25 00 01 00 01 00 01 01 00 00 00 00 00 00 " +
- "17 00 65 00 00 01 00 02 C0 02 C0 65 00 00 01 00 " +
- "03 C0 03 C0 04 62 01 07 00";
- byte[] data = HexRead.readFromString(hex);
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- ArrayRecord r1 = new ArrayRecord(in);
- CellRangeAddress8Bit range = r1.getRange();
- assertEquals(1, range.getFirstColumn());
- assertEquals(1, range.getLastColumn());
- assertEquals(1, range.getFirstRow());
- assertEquals(1, range.getLastRow());
-
- Ptg[] ptg = r1.getFormulaTokens();
- assertEquals("MAX(C1:C2-D1:D2)", FormulaRenderer.toFormulaString(null, ptg));
-
- //construct a new ArrayRecord with the same contents as r1
- Ptg[] fmlaPtg = FormulaParser.parse("MAX(C1:C2-D1:D2)", null, FormulaType.ARRAY, 0);
- ArrayRecord r2 = new ArrayRecord(Formula.create(fmlaPtg), new CellRangeAddress8Bit(1, 1, 1, 1));
- byte[] ser = r2.serialize();
- //serialize and check that the data is the same as in r1
- assertEquals(HexDump.toHex(data), HexDump.toHex(ser));
- }
-
- @Test
- void testBug57231() {
- HSSFWorkbook wb = HSSFTestDataSamples
- .openSampleWorkbook("57231_MixedGasReport.xls");
- HSSFSheet sheet = wb.getSheet("master");
-
- HSSFSheet newSheet = wb.cloneSheet(wb.getSheetIndex(sheet));
- int idx = wb.getSheetIndex(newSheet);
- wb.setSheetName(idx, "newName");
-
- // Write the output to a file
- HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
- assertNotNull(wbBack);
-
- assertNotNull(wbBack.getSheet("master"));
- assertNotNull(wbBack.getSheet("newName"));
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java b/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java
deleted file mode 100644
index 9c855f8b3e..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.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.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the AutoFilterInfoRecord class.
- */
-final class TestAutoFilterInfoRecord {
- private final byte[] data = new byte[] {
- 0x05, 0x00
- };
-
- @Test
- void testRead() {
-
- AutoFilterInfoRecord record = new AutoFilterInfoRecord(TestcaseRecordInputStream.create(AutoFilterInfoRecord.sid, data));
-
- assertEquals(AutoFilterInfoRecord.sid, record.getSid());
- assertEquals(data.length, record.getDataSize());
- assertEquals(5, record.getNumEntries());
- record.setNumEntries((short)3);
- assertEquals(3, record.getNumEntries());
- }
-
- @Test
- void testWrite() {
- AutoFilterInfoRecord record = new AutoFilterInfoRecord();
- record.setNumEntries((short)3);
-
- byte [] ser = record.serialize();
- assertEquals(ser.length - 4, data.length);
- record = new AutoFilterInfoRecord(TestcaseRecordInputStream.create(ser));
- assertEquals(3, record.getNumEntries());
- }
-
- @Test
- void testClone()
- {
- AutoFilterInfoRecord record = new AutoFilterInfoRecord();
- record.setNumEntries((short)3);
- byte[] src = record.serialize();
-
- AutoFilterInfoRecord cloned = record.copy();
- assertEquals(3, record.getNumEntries());
- byte[] cln = cloned.serialize();
-
- assertEquals(record.getDataSize(), cloned.getDataSize());
- assertArrayEquals(src, cln);
- }
-}
\ No newline at end of file
diff --git a/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java
deleted file mode 100644
index bbf5bf3549..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.IOException;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.junit.jupiter.api.Test;
-
-final class TestBOFRecord {
- @Test
- void testBOFRecord() throws IOException {
- // This used to throw an error before - #42794
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("bug_42794.xls")) {
- Sheet sh = wb.getSheetAt(0);
- for (int i=1; i<=10; i++) {
- double act = sh.getRow(i).getCell(0).getNumericCellValue();
- assertEquals(i, act, 0);
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java
deleted file mode 100644
index 700f415f07..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-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.assertTrue;
-
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link BoolErrRecord}
- */
-final class TestBoolErrRecord {
-
- @Test
- void testError() {
- byte[] data = HexRead.readFromString(
- "00 00 00 00 0F 00 " + // row, col, xfIndex
- "07 01 " // #DIV/0!, isError
- );
-
- RecordInputStream in = TestcaseRecordInputStream.create(BoolErrRecord.sid, data);
- BoolErrRecord ber = new BoolErrRecord(in);
- assertTrue(ber.isError());
- assertEquals(7, ber.getErrorValue());
-
- TestcaseRecordInputStream.confirmRecordEncoding(BoolErrRecord.sid, data, ber.serialize());
- }
-
- /**
- * Bugzilla 47479 was due to an apparent error in OOO which (as of version 3.0.1)
- * writes the value field of BOOLERR records as 2 bytes instead of 1.
- * Coincidentally, the extra byte written is zero, which is exactly the value
- * required by the isError field. This probably why Excel seems to have
- * no problem. OOO does not have the same bug for error values (which wouldn't
- * work by the same coincidence).
- */
- @Test
- void testOooBadFormat_bug47479() {
- byte[] data = HexRead.readFromString(
- "05 02 09 00 " + // sid, size
- "00 00 00 00 0F 00 " + // row, col, xfIndex
- "01 00 00 " // extra 00 byte here
- );
-
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- BoolErrRecord ber = new BoolErrRecord(in);
- boolean hasMore = in.hasNextRecord();
- assertFalse(hasMore);
- assertTrue(ber.isBoolean());
- assertTrue(ber.getBooleanValue());
-
- // Check that the record re-serializes correctly
- byte[] outData = ber.serialize();
- byte[] expData = HexRead.readFromString(
- "05 02 08 00 " +
- "00 00 00 00 0F 00 " +
- "01 00 " // normal number of data bytes
- );
- assertArrayEquals(expData, outData);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java
deleted file mode 100644
index 3ee14a90ba..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-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.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests BoundSheetRecord.
- */
-final class TestBoundSheetRecord {
-
- @Test
- void testRecordLength() {
- BoundSheetRecord record = new BoundSheetRecord("Sheet1");
- assertEquals(18, record.getRecordSize());
- }
-
- @Test
- void testWideRecordLength() {
- BoundSheetRecord record = new BoundSheetRecord("Sheet\u20ac");
- assertEquals(24, record.getRecordSize());
- }
-
- @Test
- void testName() {
- BoundSheetRecord record = new BoundSheetRecord("1234567890223456789032345678904");
- assertThrows(IllegalArgumentException.class, () -> record.setSheetname("s//*s"));
- }
-
- @Test
- void testDeserializeUnicode() {
-
- byte[] data = HexRead.readFromString(""
- + "85 00 1A 00" // sid, length
- + "3C 09 00 00" // bof
- + "00 00"// flags
- + "09 01" // str-len. unicode flag
- // string data
- + "21 04 42 04 40 04"
- + "30 04 3D 04 38 04"
- + "47 04 3A 04 30 04"
- );
-
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- BoundSheetRecord bsr = new BoundSheetRecord(in);
- // sheet name is unicode Russian for 'minor page'
- assertEquals("\u0421\u0442\u0440\u0430\u043D\u0438\u0447\u043A\u0430", bsr.getSheetname());
-
- byte[] data2 = bsr.serialize();
- assertArrayEquals(data, data2);
- }
-
- @Test
- void testOrdering() {
- BoundSheetRecord bs1 = new BoundSheetRecord("SheetB");
- BoundSheetRecord bs2 = new BoundSheetRecord("SheetC");
- BoundSheetRecord bs3 = new BoundSheetRecord("SheetA");
- bs1.setPositionOfBof(11);
- bs2.setPositionOfBof(33);
- bs3.setPositionOfBof(22);
-
- List l = new ArrayList<>();
- l.add(bs1);
- l.add(bs2);
- l.add(bs3);
-
- BoundSheetRecord[] r = BoundSheetRecord.orderByBofPosition(l);
- assertEquals(3, r.length);
- assertEquals(bs1, r[0]);
- assertEquals(bs3, r[1]);
- assertEquals(bs2, r[2]);
- }
-
- @Test
- void testValidNames() {
- assertTrue(isValid("Sheet1"));
- assertTrue(isValid("O'Brien's sales"));
- assertTrue(isValid(" data # "));
- assertTrue(isValid("data $1.00"));
-
- assertFalse(isValid("data?"));
- assertFalse(isValid("abc/def"));
- assertFalse(isValid("data[0]"));
- assertFalse(isValid("data*"));
- assertFalse(isValid("abc\\def"));
- assertFalse(isValid("'data"));
- assertFalse(isValid("data'"));
- }
-
- private static boolean isValid(String sheetName) {
- try {
- new BoundSheetRecord(sheetName);
- return true;
- } catch (IllegalArgumentException e) {
- return false;
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java
deleted file mode 100644
index 0a43dbfdb6..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.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.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.util.CellRangeAddress;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the {@link CFHeaderRecord}
- * and {@link CFHeader12Record} classes works correctly.
- */
-final class TestCFHeaderRecord {
- @Test
- void testCreateCFHeaderRecord () {
- CFHeaderRecord record = new CFHeaderRecord();
- CellRangeAddress[] ranges = {
- new CellRangeAddress(0,0xFFFF,5,5),
- new CellRangeAddress(0,0xFFFF,6,6),
- new CellRangeAddress(0,1,0,1),
- new CellRangeAddress(0,1,2,3),
- new CellRangeAddress(2,3,0,1),
- new CellRangeAddress(2,3,2,3),
- };
- record.setCellRanges(ranges);
- ranges = record.getCellRanges();
- assertEquals(6,ranges.length);
- CellRangeAddress enclosingCellRange = record.getEnclosingCellRange();
- assertEquals(0, enclosingCellRange.getFirstRow());
- assertEquals(65535, enclosingCellRange.getLastRow());
- assertEquals(0, enclosingCellRange.getFirstColumn());
- assertEquals(6, enclosingCellRange.getLastColumn());
-
- assertFalse(record.getNeedRecalculation());
- assertEquals(0, record.getID());
-
- record.setNeedRecalculation(true);
- assertTrue(record.getNeedRecalculation());
- assertEquals(0, record.getID());
-
- record.setID(7);
- record.setNeedRecalculation(false);
- assertFalse(record.getNeedRecalculation());
- assertEquals(7, record.getID());
- }
-
- @Test
- void testCreateCFHeader12Record () {
- CFHeader12Record record = new CFHeader12Record();
- CellRangeAddress[] ranges = {
- new CellRangeAddress(0,0xFFFF,5,5),
- new CellRangeAddress(0,0xFFFF,6,6),
- new CellRangeAddress(0,1,0,1),
- new CellRangeAddress(0,1,2,3),
- new CellRangeAddress(2,3,0,1),
- new CellRangeAddress(2,3,2,3),
- };
- record.setCellRanges(ranges);
- ranges = record.getCellRanges();
- assertEquals(6,ranges.length);
- CellRangeAddress enclosingCellRange = record.getEnclosingCellRange();
- assertEquals(0, enclosingCellRange.getFirstRow());
- assertEquals(65535, enclosingCellRange.getLastRow());
- assertEquals(0, enclosingCellRange.getFirstColumn());
- assertEquals(6, enclosingCellRange.getLastColumn());
-
- assertFalse(record.getNeedRecalculation());
- assertEquals(0, record.getID());
-
- record.setNeedRecalculation(true);
- assertTrue(record.getNeedRecalculation());
- assertEquals(0, record.getID());
-
- record.setID(7);
- record.setNeedRecalculation(false);
- assertFalse(record.getNeedRecalculation());
- assertEquals(7, record.getID());
- }
-
- @Test
- void testSerialization() {
- byte[] recordData =
- {
- (byte)0x03, (byte)0x00,
- (byte)0x01, (byte)0x00,
-
- (byte)0x00, (byte)0x00,
- (byte)0x03, (byte)0x00,
- (byte)0x00, (byte)0x00,
- (byte)0x03, (byte)0x00,
-
- (byte)0x04, (byte)0x00, // nRegions
-
- (byte)0x00, (byte)0x00,
- (byte)0x01, (byte)0x00,
- (byte)0x00, (byte)0x00,
- (byte)0x01, (byte)0x00,
-
- (byte)0x00, (byte)0x00,
- (byte)0x01, (byte)0x00,
- (byte)0x02, (byte)0x00,
- (byte)0x03, (byte)0x00,
-
- (byte)0x02, (byte)0x00,
- (byte)0x03, (byte)0x00,
- (byte)0x00, (byte)0x00,
- (byte)0x01, (byte)0x00,
-
- (byte)0x02, (byte)0x00,
- (byte)0x03, (byte)0x00,
- (byte)0x02, (byte)0x00,
- (byte)0x03, (byte)0x00,
- };
-
- CFHeaderRecord record = new CFHeaderRecord(TestcaseRecordInputStream.create(CFHeaderRecord.sid, recordData));
-
- assertEquals(3, record.getNumberOfConditionalFormats(), "#CFRULES");
- assertTrue(record.getNeedRecalculation());
- confirm(record.getEnclosingCellRange(), 0, 3, 0, 3);
- CellRangeAddress[] ranges = record.getCellRanges();
- assertEquals(4, ranges.length);
- confirm(ranges[0], 0, 1, 0, 1);
- confirm(ranges[1], 0, 1, 2, 3);
- confirm(ranges[2], 2, 3, 0, 1);
- confirm(ranges[3], 2, 3, 2, 3);
- assertEquals(recordData.length+4, record.getRecordSize());
-
- byte[] output = record.serialize();
- confirmRecordEncoding(CFHeaderRecord.sid, recordData, output);
- }
-
- @Test
- void testExtremeRows() {
- byte[] recordData = {
- (byte)0x13, (byte)0x00, // nFormats
- (byte)0x00, (byte)0x00,
-
- (byte)0x00, (byte)0x00,
- (byte)0xFF, (byte)0xFF,
- (byte)0x00, (byte)0x00,
- (byte)0xFF, (byte)0x00,
-
- (byte)0x03, (byte)0x00, // nRegions
-
- (byte)0x40, (byte)0x9C,
- (byte)0x50, (byte)0xC3,
- (byte)0x02, (byte)0x00,
- (byte)0x02, (byte)0x00,
-
- (byte)0x00, (byte)0x00,
- (byte)0xFF, (byte)0xFF,
- (byte)0x05, (byte)0x00,
- (byte)0x05, (byte)0x00,
-
- (byte)0x07, (byte)0x00,
- (byte)0x07, (byte)0x00,
- (byte)0x00, (byte)0x00,
- (byte)0xFF, (byte)0x00,
- };
-
- // bug 44739b - invalid cell range (-25536, 2, -15536, 2)
- CFHeaderRecord record = new CFHeaderRecord(TestcaseRecordInputStream.create(CFHeaderRecord.sid, recordData));
-
- assertEquals(19, record.getNumberOfConditionalFormats(), "#CFRULES");
- assertFalse(record.getNeedRecalculation());
- confirm(record.getEnclosingCellRange(), 0, 65535, 0, 255);
- CellRangeAddress[] ranges = record.getCellRanges();
- assertEquals(3, ranges.length);
- confirm(ranges[0], 40000, 50000, 2, 2);
- confirm(ranges[1], 0, 65535, 5, 5);
- confirm(ranges[2], 7, 7, 0, 255);
-
- byte[] output = record.serialize();
- confirmRecordEncoding(CFHeaderRecord.sid, recordData, output);
- }
-
- private static void confirm(CellRangeAddress cr, int expFirstRow, int expLastRow, int expFirstCol, int expLastColumn) {
- assertEquals(expFirstRow, cr.getFirstRow(), "first row");
- assertEquals(expLastRow, cr.getLastRow(), "last row");
- assertEquals(expFirstCol, cr.getFirstColumn(), "first column");
- assertEquals(expLastColumn, cr.getLastColumn(), "last column");
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java
deleted file mode 100644
index 81689f140c..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java
+++ /dev/null
@@ -1,453 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.assertSame;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator;
-import org.apache.poi.hssf.record.cf.BorderFormatting;
-import org.apache.poi.hssf.record.cf.FontFormatting;
-import org.apache.poi.hssf.record.cf.PatternFormatting;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.formula.ptg.RefNPtg;
-import org.apache.poi.ss.formula.ptg.RefPtg;
-import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold.RangeType;
-import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet;
-import org.apache.poi.util.LittleEndian;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the TestCFRuleRecord
- * class works correctly.
- */
-final class TestCFRuleRecord {
- @Test
- void testConstructors () throws IOException {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- HSSFSheet sheet = workbook.createSheet();
-
- CFRuleRecord rule1 = CFRuleRecord.create(sheet, "7");
- assertEquals(CFRuleBase.CONDITION_TYPE_FORMULA, rule1.getConditionType());
- assertEquals(ComparisonOperator.NO_COMPARISON, rule1.getComparisonOperation());
- assertNotNull(rule1.getParsedExpression1());
- assertSame(Ptg.EMPTY_PTG_ARRAY, rule1.getParsedExpression2());
-
- CFRuleRecord rule2 = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5");
- assertEquals(CFRuleBase.CONDITION_TYPE_CELL_VALUE_IS, rule2.getConditionType());
- assertEquals(ComparisonOperator.BETWEEN, rule2.getComparisonOperation());
- assertNotNull(rule2.getParsedExpression1());
- assertNotNull(rule2.getParsedExpression2());
-
- CFRuleRecord rule3 = CFRuleRecord.create(sheet, ComparisonOperator.EQUAL, null, null);
- assertEquals(CFRuleBase.CONDITION_TYPE_CELL_VALUE_IS, rule3.getConditionType());
- assertEquals(ComparisonOperator.EQUAL, rule3.getComparisonOperation());
- assertSame(Ptg.EMPTY_PTG_ARRAY, rule3.getParsedExpression2());
- assertSame(Ptg.EMPTY_PTG_ARRAY, rule3.getParsedExpression2());
- }
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testCreateCFRuleRecord() throws IOException {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- HSSFSheet sheet = workbook.createSheet();
- CFRuleRecord record = CFRuleRecord.create(sheet, "7");
- testCFRuleRecord(record);
-
- // Serialize
- byte[] serializedRecord = record.serialize();
-
- // Strip header
- byte[] recordData = Arrays.copyOfRange(serializedRecord, 4, serializedRecord.length);
-
- // Deserialize
- record = new CFRuleRecord(TestcaseRecordInputStream.create(CFRuleRecord.sid, recordData));
-
- // Serialize again
- byte[] output = record.serialize();
- confirmRecordEncoding(CFRuleRecord.sid, recordData, output);
- }
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testCreateCFRule12Record() throws IOException {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- HSSFSheet sheet = workbook.createSheet();
- CFRule12Record record = CFRule12Record.create(sheet, "7");
- testCFRule12Record(record);
-
- // Serialize
- byte[] serializedRecord = record.serialize();
-
- // Strip header
- byte[] recordData = Arrays.copyOfRange(serializedRecord, 4, serializedRecord.length);
-
- // Deserialize
- record = new CFRule12Record(TestcaseRecordInputStream.create(CFRule12Record.sid, recordData));
-
- // Serialize again
- byte[] output = record.serialize();
- confirmRecordEncoding(CFRule12Record.sid, recordData, output);
- }
- }
-
- @Test
- void testCreateIconCFRule12Record() throws IOException {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- HSSFSheet sheet = workbook.createSheet();
- CFRule12Record record = CFRule12Record.create(sheet, IconSet.GREY_5_ARROWS);
- record.getMultiStateFormatting().getThresholds()[1].setType(RangeType.PERCENT.id);
- record.getMultiStateFormatting().getThresholds()[1].setValue(10d);
- record.getMultiStateFormatting().getThresholds()[2].setType(RangeType.NUMBER.id);
- record.getMultiStateFormatting().getThresholds()[2].setValue(-4d);
-
- // Check it
- testCFRule12Record(record);
- assertEquals(IconSet.GREY_5_ARROWS, record.getMultiStateFormatting().getIconSet());
- assertEquals(5, record.getMultiStateFormatting().getThresholds().length);
-
- // Serialize
- byte[] serializedRecord = record.serialize();
-
- // Strip header
- byte[] recordData = Arrays.copyOfRange(serializedRecord, 4, serializedRecord.length);
-
- // Deserialize
- record = new CFRule12Record(TestcaseRecordInputStream.create(CFRule12Record.sid, recordData));
-
- // Check it has the icon, and the right number of thresholds
- assertEquals(IconSet.GREY_5_ARROWS, record.getMultiStateFormatting().getIconSet());
- assertEquals(5, record.getMultiStateFormatting().getThresholds().length);
-
- // Serialize again
- byte[] output = record.serialize();
- confirmRecordEncoding(CFRule12Record.sid, recordData, output);
- }
- }
-
- private void testCFRuleRecord(CFRuleRecord record) {
- testCFRuleBase(record);
-
- assertFalse(record.isLeftBorderModified());
- record.setLeftBorderModified(true);
- assertTrue(record.isLeftBorderModified());
-
- assertFalse(record.isRightBorderModified());
- record.setRightBorderModified(true);
- assertTrue(record.isRightBorderModified());
-
- assertFalse(record.isTopBorderModified());
- record.setTopBorderModified(true);
- assertTrue(record.isTopBorderModified());
-
- assertFalse(record.isBottomBorderModified());
- record.setBottomBorderModified(true);
- assertTrue(record.isBottomBorderModified());
-
- assertFalse(record.isTopLeftBottomRightBorderModified());
- record.setTopLeftBottomRightBorderModified(true);
- assertTrue(record.isTopLeftBottomRightBorderModified());
-
- assertFalse(record.isBottomLeftTopRightBorderModified());
- record.setBottomLeftTopRightBorderModified(true);
- assertTrue(record.isBottomLeftTopRightBorderModified());
-
-
- assertFalse(record.isPatternBackgroundColorModified());
- record.setPatternBackgroundColorModified(true);
- assertTrue(record.isPatternBackgroundColorModified());
-
- assertFalse(record.isPatternColorModified());
- record.setPatternColorModified(true);
- assertTrue(record.isPatternColorModified());
-
- assertFalse(record.isPatternStyleModified());
- record.setPatternStyleModified(true);
- assertTrue(record.isPatternStyleModified());
- }
- private void testCFRule12Record(CFRule12Record record) {
- assertEquals(CFRule12Record.sid, record.getFutureRecordType());
- assertEquals("A1", record.getAssociatedRange().formatAsString());
- testCFRuleBase(record);
- }
- private void testCFRuleBase(CFRuleBase record) {
- FontFormatting fontFormatting = new FontFormatting();
- testFontFormattingAccessors(fontFormatting);
- assertFalse(record.containsFontFormattingBlock());
- record.setFontFormatting(fontFormatting);
- assertTrue(record.containsFontFormattingBlock());
-
- BorderFormatting borderFormatting = new BorderFormatting();
- testBorderFormattingAccessors(borderFormatting);
- assertFalse(record.containsBorderFormattingBlock());
- record.setBorderFormatting(borderFormatting);
- assertTrue(record.containsBorderFormattingBlock());
-
- PatternFormatting patternFormatting = new PatternFormatting();
- testPatternFormattingAccessors(patternFormatting);
- assertFalse(record.containsPatternFormattingBlock());
- record.setPatternFormatting(patternFormatting);
- assertTrue(record.containsPatternFormattingBlock());
- }
-
- private void testPatternFormattingAccessors(PatternFormatting patternFormatting) {
- patternFormatting.setFillBackgroundColor(HSSFColorPredefined.GREEN.getIndex());
- assertEquals(HSSFColorPredefined.GREEN.getIndex(),patternFormatting.getFillBackgroundColor());
-
- patternFormatting.setFillForegroundColor(HSSFColorPredefined.INDIGO.getIndex());
- assertEquals(HSSFColorPredefined.INDIGO.getIndex(),patternFormatting.getFillForegroundColor());
-
- patternFormatting.setFillPattern(PatternFormatting.DIAMONDS);
- assertEquals(PatternFormatting.DIAMONDS,patternFormatting.getFillPattern());
- }
-
- private void testBorderFormattingAccessors(BorderFormatting borderFormatting) {
- borderFormatting.setBackwardDiagonalOn(false);
- assertFalse(borderFormatting.isBackwardDiagonalOn());
- borderFormatting.setBackwardDiagonalOn(true);
- assertTrue(borderFormatting.isBackwardDiagonalOn());
-
- borderFormatting.setBorderBottom(BorderFormatting.BORDER_DOTTED);
- assertEquals(BorderFormatting.BORDER_DOTTED, borderFormatting.getBorderBottom());
-
- borderFormatting.setBorderDiagonal(BorderFormatting.BORDER_MEDIUM);
- assertEquals(BorderFormatting.BORDER_MEDIUM, borderFormatting.getBorderDiagonal());
-
- borderFormatting.setBorderLeft(BorderFormatting.BORDER_MEDIUM_DASH_DOT_DOT);
- assertEquals(BorderFormatting.BORDER_MEDIUM_DASH_DOT_DOT, borderFormatting.getBorderLeft());
-
- borderFormatting.setBorderRight(BorderFormatting.BORDER_MEDIUM_DASHED);
- assertEquals(BorderFormatting.BORDER_MEDIUM_DASHED, borderFormatting.getBorderRight());
-
- borderFormatting.setBorderTop(BorderFormatting.BORDER_HAIR);
- assertEquals(BorderFormatting.BORDER_HAIR, borderFormatting.getBorderTop());
-
- borderFormatting.setBottomBorderColor(HSSFColorPredefined.AQUA.getIndex());
- assertEquals(HSSFColorPredefined.AQUA.getIndex(), borderFormatting.getBottomBorderColor());
-
- borderFormatting.setDiagonalBorderColor(HSSFColorPredefined.RED.getIndex());
- assertEquals(HSSFColorPredefined.RED.getIndex(), borderFormatting.getDiagonalBorderColor());
-
- assertFalse(borderFormatting.isForwardDiagonalOn());
- borderFormatting.setForwardDiagonalOn(true);
- assertTrue(borderFormatting.isForwardDiagonalOn());
-
- borderFormatting.setLeftBorderColor(HSSFColorPredefined.BLACK.getIndex());
- assertEquals(HSSFColorPredefined.BLACK.getIndex(), borderFormatting.getLeftBorderColor());
-
- borderFormatting.setRightBorderColor(HSSFColorPredefined.BLUE.getIndex());
- assertEquals(HSSFColorPredefined.BLUE.getIndex(), borderFormatting.getRightBorderColor());
-
- borderFormatting.setTopBorderColor(HSSFColorPredefined.GOLD.getIndex());
- assertEquals(HSSFColorPredefined.GOLD.getIndex(), borderFormatting.getTopBorderColor());
- }
-
-
- private void testFontFormattingAccessors(FontFormatting fontFormatting) {
- // Check for defaults
- assertFalse(fontFormatting.isEscapementTypeModified());
- assertFalse(fontFormatting.isFontCancellationModified());
- assertFalse(fontFormatting.isFontOutlineModified());
- assertFalse(fontFormatting.isFontShadowModified());
- assertFalse(fontFormatting.isFontStyleModified());
- assertFalse(fontFormatting.isUnderlineTypeModified());
- assertFalse(fontFormatting.isFontWeightModified());
-
- assertFalse(fontFormatting.isBold());
- assertFalse(fontFormatting.isItalic());
- assertFalse(fontFormatting.isOutlineOn());
- assertFalse(fontFormatting.isShadowOn());
- assertFalse(fontFormatting.isStruckout());
-
- assertEquals(0, fontFormatting.getEscapementType());
- assertEquals(-1, fontFormatting.getFontColorIndex());
- assertEquals(-1, fontFormatting.getFontHeight());
- assertEquals(0, fontFormatting.getFontWeight());
- assertEquals(0, fontFormatting.getUnderlineType());
-
- fontFormatting.setBold(true);
- assertTrue(fontFormatting.isBold());
- fontFormatting.setBold(false);
- assertFalse(fontFormatting.isBold());
-
- fontFormatting.setEscapementType(org.apache.poi.ss.usermodel.Font.SS_SUB);
- assertEquals(org.apache.poi.ss.usermodel.Font.SS_SUB, fontFormatting.getEscapementType());
- fontFormatting.setEscapementType(org.apache.poi.ss.usermodel.Font.SS_SUPER);
- assertEquals(org.apache.poi.ss.usermodel.Font.SS_SUPER, fontFormatting.getEscapementType());
- fontFormatting.setEscapementType(org.apache.poi.ss.usermodel.Font.SS_NONE);
- assertEquals(org.apache.poi.ss.usermodel.Font.SS_NONE, fontFormatting.getEscapementType());
-
- fontFormatting.setEscapementTypeModified(false);
- assertFalse(fontFormatting.isEscapementTypeModified());
- fontFormatting.setEscapementTypeModified(true);
- assertTrue(fontFormatting.isEscapementTypeModified());
-
- fontFormatting.setFontWieghtModified(false);
- assertFalse(fontFormatting.isFontWeightModified());
- fontFormatting.setFontWieghtModified(true);
- assertTrue(fontFormatting.isFontWeightModified());
-
- fontFormatting.setFontCancellationModified(false);
- assertFalse(fontFormatting.isFontCancellationModified());
- fontFormatting.setFontCancellationModified(true);
- assertTrue(fontFormatting.isFontCancellationModified());
-
- fontFormatting.setFontColorIndex((short)10);
- assertEquals(10,fontFormatting.getFontColorIndex());
-
- fontFormatting.setFontHeight(100);
- assertEquals(100,fontFormatting.getFontHeight());
-
- fontFormatting.setFontOutlineModified(false);
- assertFalse(fontFormatting.isFontOutlineModified());
- fontFormatting.setFontOutlineModified(true);
- assertTrue(fontFormatting.isFontOutlineModified());
-
- fontFormatting.setFontShadowModified(false);
- assertFalse(fontFormatting.isFontShadowModified());
- fontFormatting.setFontShadowModified(true);
- assertTrue(fontFormatting.isFontShadowModified());
-
- fontFormatting.setFontStyleModified(false);
- assertFalse(fontFormatting.isFontStyleModified());
- fontFormatting.setFontStyleModified(true);
- assertTrue(fontFormatting.isFontStyleModified());
-
- fontFormatting.setItalic(false);
- assertFalse(fontFormatting.isItalic());
- fontFormatting.setItalic(true);
- assertTrue(fontFormatting.isItalic());
-
- fontFormatting.setOutline(false);
- assertFalse(fontFormatting.isOutlineOn());
- fontFormatting.setOutline(true);
- assertTrue(fontFormatting.isOutlineOn());
-
- fontFormatting.setShadow(false);
- assertFalse(fontFormatting.isShadowOn());
- fontFormatting.setShadow(true);
- assertTrue(fontFormatting.isShadowOn());
-
- fontFormatting.setStrikeout(false);
- assertFalse(fontFormatting.isStruckout());
- fontFormatting.setStrikeout(true);
- assertTrue(fontFormatting.isStruckout());
-
- fontFormatting.setUnderlineType(org.apache.poi.ss.usermodel.Font.U_DOUBLE_ACCOUNTING);
- assertEquals(org.apache.poi.ss.usermodel.Font.U_DOUBLE_ACCOUNTING, fontFormatting.getUnderlineType());
-
- fontFormatting.setUnderlineTypeModified(false);
- assertFalse(fontFormatting.isUnderlineTypeModified());
- fontFormatting.setUnderlineTypeModified(true);
- assertTrue(fontFormatting.isUnderlineTypeModified());
- }
-
- @Test
- void testWrite() throws IOException {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- HSSFSheet sheet = workbook.createSheet();
- CFRuleRecord rr = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "5", "10");
-
- PatternFormatting patternFormatting = new PatternFormatting();
- patternFormatting.setFillPattern(PatternFormatting.BRICKS);
- rr.setPatternFormatting(patternFormatting);
-
- byte[] data = rr.serialize();
- assertEquals(26, data.length);
- assertEquals(3, LittleEndian.getShort(data, 6));
- assertEquals(3, LittleEndian.getShort(data, 8));
-
- int flags = LittleEndian.getInt(data, 10);
- assertEquals(0x00380000, flags & 0x00380000, "unused flags should be 111");
- // Otherwise Excel gets unhappy
- assertEquals(0, flags & 0x03C00000, "undocumented flags should be 0000");
- // check all remaining flag bits (some are not well understood yet)
- assertEquals(0x203FFFFF, flags);
- }
- }
-
- private static final byte[] DATA_REFN = {
- // formula extracted from bugzilla 45234 att 22141
- 1, 3,
- 9, // formula 1 length
- 0, 0, 0, -1, -1, 63, 32, 2, -128, 0, 0, 0, 5,
- // formula 1: "=B3=1" (formula is relative to B4)
- 76, -1, -1, 0, -64, // tRefN(B1)
- 30, 1, 0,
- 11,
- };
-
- /**
- * tRefN and tAreaN tokens must be preserved when re-serializing conditional format formulas
- */
- @Test
- void testReserializeRefNTokens() {
-
- RecordInputStream is = TestcaseRecordInputStream.create(CFRuleRecord.sid, DATA_REFN);
- CFRuleRecord rr = new CFRuleRecord(is);
- Ptg[] ptgs = rr.getParsedExpression1();
- assertEquals(3, ptgs.length);
- assertFalse(ptgs[0] instanceof RefPtg, "Identified bug 45234");
- assertEquals(RefNPtg.class, ptgs[0].getClass());
- RefNPtg refNPtg = (RefNPtg) ptgs[0];
- assertTrue(refNPtg.isColRelative());
- assertTrue(refNPtg.isRowRelative());
-
- byte[] data = rr.serialize();
- confirmRecordEncoding(CFRuleRecord.sid, DATA_REFN, data);
- }
-
- @Test
- void testBug53691() throws IOException {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- HSSFSheet sheet = workbook.createSheet();
-
- CFRuleRecord record = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5");
-
- CFRuleRecord clone = record.copy();
-
- byte[] serializedRecord = record.serialize();
- byte[] serializedClone = clone.serialize();
- assertArrayEquals(serializedRecord, serializedClone);
- }
- }
-
- @Test
- void testBug57231_rewrite() throws IOException {
- try (HSSFWorkbook wb1 = HSSFITestDataProvider.instance.openSampleWorkbook("57231_MixedGasReport.xls")) {
- assertEquals(7, wb1.getNumberOfSheets());
- try (HSSFWorkbook wb2 = HSSFITestDataProvider.instance.writeOutAndReadBack(wb1)) {
- assertEquals(7, wb2.getNumberOfSheets());
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java b/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java
deleted file mode 100644
index 6d472b9c2b..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.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.hssf.record;
-
-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 org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link ColumnInfoRecord}
- */
-final class TestColumnInfoRecord {
-
- @Test
- void testBasic() {
- byte[] data = HexRead.readFromString("7D 00 0C 00 14 00 9B 00 C7 19 0F 00 01 13 00 00");
-
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- ColumnInfoRecord cir = new ColumnInfoRecord(in);
- assertEquals(0, in.remaining());
-
- assertEquals(20, cir.getFirstColumn());
- assertEquals(155, cir.getLastColumn());
- assertEquals(6599, cir.getColumnWidth());
- assertEquals(15, cir.getXFIndex());
- assertTrue(cir.getHidden());
- assertEquals(3, cir.getOutlineLevel());
- assertTrue(cir.getCollapsed());
- assertArrayEquals(data, cir.serialize());
- }
-
- /**
- * Some applications skip the last reserved field when writing {@link ColumnInfoRecord}s
- * The attached file was apparently created by "SoftArtisans OfficeWriter for Excel".
- * Excel reads that file OK and assumes zero for the value of the reserved field.
- */
- @Test
- void testZeroResevedBytes_bug48332() {
- // Taken from bugzilla attachment 24661 (offset 0x1E73)
- byte[] inpData = HexRead.readFromString("7D 00 0A 00 00 00 00 00 D5 19 0F 00 02 00");
- byte[] outData = HexRead.readFromString("7D 00 0C 00 00 00 00 00 D5 19 0F 00 02 00 00 00");
-
- RecordInputStream in = TestcaseRecordInputStream.create(inpData);
- // bug 48332 - Unusual record size remaining=(0)
- ColumnInfoRecord cir = new ColumnInfoRecord(in);
- assertEquals(0, in.remaining());
- assertArrayEquals(outData, cir.serialize());
- }
-
- /**
- * Some sample files have just one reserved byte (field 6):
- * OddStyleRecord.xls, NoGutsRecords.xls, WORKBOOK_in_capitals.xls
- * but this seems to cause no problem to Excel
- */
- @Test
- void testOneReservedByte() {
- byte[] inpData = HexRead.readFromString("7D 00 0B 00 00 00 00 00 24 02 0F 00 00 00 01");
- byte[] outData = HexRead.readFromString("7D 00 0C 00 00 00 00 00 24 02 0F 00 00 00 01 00");
- RecordInputStream in = TestcaseRecordInputStream.create(inpData);
- ColumnInfoRecord cir = new ColumnInfoRecord(in);
- assertEquals(0, in.remaining());
- assertArrayEquals(outData, cir.serialize());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java
deleted file mode 100644
index 5fccfd0975..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.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.hssf.record;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the {@link CommonObjectDataSubRecord}
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestCommonObjectDataSubRecord {
- byte[] data = new byte[] {
- (byte)0x12,(byte)0x00,(byte)0x01,(byte)0x00,
- (byte)0x01,(byte)0x00,(byte)0x11,(byte)0x60,
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
- (byte)0x00,(byte)0x0D,(byte)0x26,(byte)0x01,
- (byte)0x00,(byte)0x00,
- };
-
- @Test
- void testLoad() {
- CommonObjectDataSubRecord record = new CommonObjectDataSubRecord(TestcaseRecordInputStream.createLittleEndian(data), data.length);
-
- assertEquals( CommonObjectDataSubRecord.OBJECT_TYPE_LIST_BOX, record.getObjectType());
- assertEquals((short) 1, record.getObjectId());
- assertEquals((short) 1, record.getOption());
- assertTrue(record.isLocked());
- assertFalse(record.isPrintable());
- assertFalse(record.isAutofill());
- assertFalse(record.isAutoline());
- assertEquals(24593, record.getReserved1());
- assertEquals(218103808, record.getReserved2());
- assertEquals(294, record.getReserved3());
- assertEquals(18, record.getDataSize());
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- CommonObjectDataSubRecord record = new CommonObjectDataSubRecord();
-
- record.setObjectType(CommonObjectDataSubRecord.OBJECT_TYPE_LIST_BOX);
- record.setObjectId( 1);
- record.setOption((short) 1);
- record.setLocked(true);
- record.setPrintable(false);
- record.setAutofill(false);
- record.setAutoline(false);
- record.setReserved1(24593);
- record.setReserved2(218103808);
- record.setReserved3(294);
-
- byte[] recordBytes = record.serialize();
- confirmRecordEncoding(CommonObjectDataSubRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java
deleted file mode 100644
index c6ea64d6b6..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ====================================================================
- */
-
-package org.apache.poi.hssf.record;
-
-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.assertTrue;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.poi.util.LittleEndianOutputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Unit tests for DConRefRecord class.
- */
-class TestDConRefRecord {
- /**
- * record of a proper single-byte external 'volume'-style path with multiple parts and a sheet
- * name.
- */
- final byte[] volumeString = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 17, 0,//cchFile (2 bytes)
- 0, //char type
- 1, 1, 'c', '[', 'f', 'o', 'o', 0x3,
- 'b', 'a', 'r', ']', 's', 'h', 'e', 'e',
- 't'
- };
- /**
- * record of a proper single-byte external 'unc-volume'-style path with multiple parts and a
- * sheet name.
- */
- final byte[] uncVolumeString = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 34, 0,//cchFile (2 bytes)
- 0, //char type
- 1, 1, '@', '[', 'c', 'o', 'm', 'p',
- 0x3, 's', 'h', 'a', 'r', 'e', 'd', 0x3,
- 'r', 'e', 'l', 'a', 't', 'i', 'v', 'e',
- 0x3, 'f', 'o', 'o', ']', 's', 'h', 'e',
- 'e', 't'
- };
- /**
- * record of a proper single-byte external 'simple-file-path-dcon' style path with a sheet name.
- */
- final byte[] simpleFilePathDconString = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 16, 0,//cchFile (2 bytes)
- 0, //char type
- 1, 'c', '[', 'f', 'o', 'o', 0x3, 'b',
- 'a', 'r', ']', 's', 'h', 'e', 'e', 't'
- };
- /**
- * record of a proper 'transfer-protocol'-style path. This one has a sheet name at the end, and
- * another one inside the file path. The spec doesn't seem to care about what they are.
- */
- final byte[] transferProtocolString = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 33, 0,//cchFile (2 bytes)
- 0, //char type
- 0x1, 0x5, 30, //count = 30
- '[', 'h', 't', 't', 'p', ':', '/', '/',
- '[', 'f', 'o', 'o', 0x3, 'b', 'a', 'r',
- ']', 's', 'h', 'e', 'e', 't', '1', ']',
- 's', 'h', 'e', 'e', 't', 'x'
- };
- /**
- * startup-type path.
- */
- final byte[] relVolumeString = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 16, 0,//cchFile (2 bytes)
- 0, //char type
- 0x1, 0x2, '[', 'f', 'o', 'o', 0x3, 'b',
- 'a', 'r', ']', 's', 'h', 'e', 'e', 't'
- };
- /**
- * startup-type path.
- */
- final byte[] startupString = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 16, 0,//cchFile (2 bytes)
- 0, //char type
- 0x1, 0x6, '[', 'f', 'o', 'o', 0x3, 'b',
- 'a', 'r', ']', 's', 'h', 'e', 'e', 't'
- };
- /**
- * alt-startup-type path.
- */
- final byte[] altStartupString = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 16, 0,//cchFile (2 bytes)
- 0, //char type
- 0x1, 0x7, '[', 'f', 'o', 'o', 0x3, 'b',
- 'a', 'r', ']', 's', 'h', 'e', 'e', 't'
- };
- /**
- * library-style path.
- */
- final byte[] libraryString = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 16, 0,//cchFile (2 bytes)
- 0, //char type
- 0x1, 0x8, '[', 'f', 'o', 'o', 0x3, 'b',
- 'a', 'r', ']', 's', 'h', 'e', 'e', 't'
- };
- /**
- * record of single-byte string, external, volume path.
- */
- final byte[] data1 = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 10, 0,//cchFile (2 bytes)
- 0, //char type
- 1, 1, (byte) 'b', (byte) 'l', (byte) 'a', (byte) ' ', (byte) 't',
- (byte) 'e', (byte) 's', (byte) 't'
- //unused doesn't exist as stFile[1] != 2
- };
- /**
- * record of double-byte string, self-reference.
- */
- final byte[] data2 = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 9, 0,//cchFile (2 bytes)
- 1, //char type = unicode
- 2, 0, (byte) 'b', 0, (byte) 'l', 0, (byte) 'a', 0, (byte) ' ', 0, (byte) 't', 0,
- (byte) 'e', 0, (byte) 's', (byte) 't', 0,//stFile
- 0, 0 //unused (2 bytes as we're using double-byte chars)
- };
- /**
- * record of single-byte string, self-reference.
- */
- final byte[] data3 = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 9, 0,//cchFile (2 bytes)
- 0, //char type = ansi
- 2, (byte) 'b', (byte) 'l', (byte) 'a', (byte) ' ', (byte) 't', (byte) 'e', (byte) 's',
- (byte) 't',//stFile
- 0 //unused (1 byte as we're using single byes)
- };
- /**
- * double-byte string, external reference, unc-volume.
- */
- final byte[] data4 = {
- 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used...
- 16, 0,//cchFile (2 bytes)
- //stFile starts here:
- 1, //char type = unicode
- 1, 0, 1, 0, 0x40, 0, (byte) 'c', 0, (byte) 'o', 0, (byte) 'm', 0, (byte) 'p', 0, 0x03, 0,
- (byte) 'b', 0, (byte) 'l', 0, (byte) 'a', 0, 0x03, 0, (byte) 't', 0, (byte) 'e', 0,
- (byte) 's', 0, (byte) 't', 0,
- //unused doesn't exist as stFile[1] != 2
- };
-
- /**
- * test read-constructor-then-serialize for a single-byte external reference strings of
- * various flavours. This uses the RecordInputStream constructor.
- */
- @Test
- void testReadWriteSBExtRef() throws IOException {
- testReadWrite(data1, "read-write single-byte external reference, volume type path");
- testReadWrite(volumeString,
- "read-write properly formed single-byte external reference, volume type path");
- testReadWrite(uncVolumeString,
- "read-write properly formed single-byte external reference, UNC volume type path");
- testReadWrite(relVolumeString,
- "read-write properly formed single-byte external reference, rel-volume type path");
- testReadWrite(simpleFilePathDconString,
- "read-write properly formed single-byte external reference, simple-file-path-dcon type path");
- testReadWrite(transferProtocolString,
- "read-write properly formed single-byte external reference, transfer-protocol type path");
- testReadWrite(startupString,
- "read-write properly formed single-byte external reference, startup type path");
- testReadWrite(altStartupString,
- "read-write properly formed single-byte external reference, alt-startup type path");
- testReadWrite(libraryString,
- "read-write properly formed single-byte external reference, library type path");
- }
-
- /**
- * test read-constructor-then-serialize for a double-byte external reference 'UNC-Volume' style
- * string
- */
- @Test
- void testReadWriteDBExtRefUncVol() throws IOException {
- testReadWrite(data4, "read-write double-byte external reference, UNC volume type path");
- }
-
- private void testReadWrite(byte[] data, String message) throws IOException {
- RecordInputStream is = TestcaseRecordInputStream.create(81, data);
- DConRefRecord d = new DConRefRecord(is);
- ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
- LittleEndianOutputStream o = new LittleEndianOutputStream(bos);
- d.serialize(o);
- o.flush();
-
- assertArrayEquals(data, bos.toByteArray(), message);
- }
-
- /**
- * test read-constructor-then-serialize for a double-byte self-reference style string
- */
- @Test
- void testReadWriteDBSelfRef() throws IOException {
- testReadWrite(data2, "read-write double-byte self reference");
- }
-
- /**
- * test read-constructor-then-serialize for a single-byte self-reference style string
- */
- @Test
- void testReadWriteSBSelfRef() throws IOException {
- testReadWrite(data3, "read-write single byte self reference");
- }
-
- /**
- * Test of getDataSize method, of class DConRefRecord.
- */
- @Test
- void testGetDataSize() {
- DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1));
- int expResult = data1.length;
- int result = instance.getDataSize();
- assertEquals(expResult, result, "single byte external reference, volume type path data size");
- instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data2));
- assertEquals(data2.length, instance.getDataSize(), "double byte self reference data size");
- instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data3));
- assertEquals(data3.length, instance.getDataSize(), "single byte self reference data size");
- instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data4));
- assertEquals(data4.length, instance.getDataSize(),
- "double byte external reference, UNC volume type path data size");
- }
-
- /**
- * Test of getSid method, of class DConRefRecord.
- */
- @Test
- void testGetSid() {
- DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1));
- short expResult = 81;
- short result = instance.getSid();
- assertEquals(expResult, result, "SID");
- }
-
- /**
- * Test of getPath method, of class DConRefRecord.
- */
- @Test
- void testGetPath() {
- // TODO: different types of paths.
- DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1));
- byte[] expResult = Arrays.copyOfRange(data1, 9, data1.length);
- byte[] result = instance.getPath();
- assertArrayEquals(expResult, result, "get path");
- }
-
- /**
- * Test of isExternalRef method, of class DConRefRecord.
- */
- @Test
- void testIsExternalRef() {
- DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1));
- assertTrue(instance.isExternalRef(), "external reference");
- instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data2));
- assertFalse(instance.isExternalRef(), "internal reference");
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java
deleted file mode 100644
index 00b25ac225..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-
-import java.io.ByteArrayInputStream;
-
-import org.apache.poi.util.LittleEndian;
-import org.junit.jupiter.api.Test;
-
-final class TestDVALRecord {
- @Test
- void testRead() {
- byte[] data = new byte[22];
- LittleEndian.putShort(data, 0, DVALRecord.sid);
- LittleEndian.putShort(data, 2, (short)18);
- LittleEndian.putShort(data, 4, (short)55);
- LittleEndian.putInt(data, 6, 56);
- LittleEndian.putInt(data, 10, 57);
- LittleEndian.putInt(data, 14, 58);
- LittleEndian.putInt(data, 18, 59);
-
- RecordInputStream in = new RecordInputStream(new ByteArrayInputStream(data));
- in.nextRecord();
- DVALRecord dv = new DVALRecord(in);
-
- assertEquals(55, dv.getOptions());
- assertEquals(56, dv.getHorizontalPos());
- assertEquals(57, dv.getVerticalPos());
- assertEquals(58, dv.getObjectID());
- assertNotEquals(0, dv.getDVRecNo(), "Identified bug 44510");
- assertEquals(59, dv.getDVRecNo());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.java
deleted file mode 100644
index e7c97e86ec..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.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.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.cut;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.ddf.EscherContainerRecord;
-import org.apache.poi.ddf.EscherSpRecord;
-import org.apache.poi.util.HexDump;
-import org.junit.jupiter.api.Test;
-
-final class TestDrawingGroupRecord {
- private static final int MAX_RECORD_SIZE = 8228;
- private static final int MAX_DATA_SIZE = MAX_RECORD_SIZE - 4;
-
- @Test
- void testGetRecordSize() {
- DrawingGroupRecord r = new DrawingGroupRecord();
- assertEquals(4, r.getRecordSize());
-
- EscherSpRecord sp = new EscherSpRecord();
- sp.setRecordId(EscherSpRecord.RECORD_ID);
- sp.setOptions((short) 0x1111);
- sp.setFlags(-1);
- sp.setShapeId(-1);
- EscherContainerRecord dggContainer = new EscherContainerRecord();
- dggContainer.setOptions((short) 0x000F);
- dggContainer.setRecordId((short) 0xF000);
- dggContainer.addChildRecord(sp);
-
- r.addEscherRecord(dggContainer);
- assertEquals(28, r.getRecordSize());
-
- byte[] data = new byte[28];
- int size = r.serialize(0, data);
- assertEquals("[EB, 00, 18, 00, 0F, 00, 00, F0, 10, 00, 00, 00, 11, 11, 0A, F0, 08, 00, 00, 00, FF, FF, FF, FF, FF, FF, FF, FF]", HexDump.toHex(data));
- assertEquals(28, size);
-
- assertEquals(24, dggContainer.getRecordSize());
-
-
- r = new DrawingGroupRecord( );
- r.setRawData( new byte[MAX_DATA_SIZE] );
- assertEquals( MAX_RECORD_SIZE, r.getRecordSize() );
- r.setRawData( new byte[MAX_DATA_SIZE+1] );
- assertEquals( MAX_RECORD_SIZE + 5, r.getRecordSize() );
- r.setRawData( new byte[MAX_DATA_SIZE*2] );
- assertEquals( MAX_RECORD_SIZE * 2, r.getRecordSize() );
- r.setRawData( new byte[MAX_DATA_SIZE*2 + 1] );
- assertEquals( MAX_RECORD_SIZE * 2 + 5, r.getRecordSize() );
- }
-
- @Test
- void testSerialize() {
- // Check under max record size
- DrawingGroupRecord r = new DrawingGroupRecord();
- byte[] rawData = new byte[100];
- rawData[0] = 100;
- rawData[99] = (byte) 200;
- r.setRawData( rawData );
- byte[] buffer = new byte[r.getRecordSize()];
- int size = r.serialize( 0, buffer );
- assertEquals( 104, size );
- assertEquals("[EB, 00, 64, 00, 64, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, C8]", HexDump.toHex(buffer));
-
- // check at max record size
- rawData = new byte[MAX_DATA_SIZE];
- r.setRawData( rawData );
- buffer = new byte[r.getRecordSize()];
- size = r.serialize( 0, buffer );
- assertEquals( MAX_RECORD_SIZE, size );
-
- // check over max record size
- rawData = new byte[MAX_DATA_SIZE+1];
- rawData[rawData.length-1] = (byte) 255;
- r.setRawData( rawData );
- buffer = new byte[r.getRecordSize()];
- size = r.serialize( 0, buffer );
- assertEquals( MAX_RECORD_SIZE + 5, size );
- assertEquals( "[EB, 00, 20, 20]", HexDump.toHex(cut(buffer, 0, 4) ));
- assertEquals( "[00, EB, 00, 01, 00, FF]", HexDump.toHex(cut(buffer, MAX_RECORD_SIZE - 1, MAX_RECORD_SIZE + 5) ));
-
- // check continue record
- rawData = new byte[MAX_DATA_SIZE * 2 + 1];
- rawData[rawData.length-1] = (byte) 255;
- r.setRawData( rawData );
- buffer = new byte[r.getRecordSize()];
- size = r.serialize( 0, buffer );
- assertEquals( MAX_RECORD_SIZE * 2 + 5, size );
- assertEquals( MAX_RECORD_SIZE * 2 + 5, r.getRecordSize() );
- assertEquals( "[EB, 00, 20, 20]", HexDump.toHex(cut(buffer, 0, 4) ));
- assertEquals( "[EB, 00, 20, 20]", HexDump.toHex(cut(buffer, MAX_RECORD_SIZE, MAX_RECORD_SIZE + 4) ));
- assertEquals( "[3C, 00, 01, 00, FF]", HexDump.toHex(cut(buffer, MAX_RECORD_SIZE * 2, MAX_RECORD_SIZE * 2 + 5) ));
-
- // check continue record
- rawData = new byte[664532];
- r.setRawData( rawData );
- buffer = new byte[r.getRecordSize()];
- size = r.serialize( 0, buffer );
- assertEquals( 664856, size );
- assertEquals( 664856, r.getRecordSize() );
- }
-
- @Test
- void testGrossSizeFromDataSize() {
- assertEquals( 4, DrawingGroupRecord.grossSizeFromDataSize( 0 ) );
- assertEquals( 5, DrawingGroupRecord.grossSizeFromDataSize( 1 ) );
- assertEquals( MAX_RECORD_SIZE, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE ) );
- assertEquals( MAX_RECORD_SIZE + 5, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE + 1 ) );
- assertEquals( MAX_RECORD_SIZE * 2, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE * 2 ) );
- assertEquals( MAX_RECORD_SIZE * 2 + 5, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE * 2 + 1 ) );
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java
deleted file mode 100644
index bac766e08a..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.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.hssf.record;
-
-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 java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.jupiter.api.Test;
-
-final class TestDrawingRecord {
-
- /**
- * Check that RecordFactoryInputStream properly handles continued DrawingRecords
- * See Bugzilla #47548
- */
- @Test
- void testReadContinued() throws IOException {
-
- //simulate a continues drawing record
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- //main part
- DrawingRecord dg = new DrawingRecord();
- byte[] data1 = new byte[8224];
- Arrays.fill(data1, (byte)1);
- dg.setData(data1);
- out.write(dg.serialize());
-
- //continued part
- byte[] data2 = new byte[4048];
- Arrays.fill(data2, (byte)2);
- ContinueRecord cn = new ContinueRecord(data2);
- out.write(cn.serialize());
-
- List rec = RecordFactory.createRecords(new ByteArrayInputStream(out.toByteArray()));
- assertEquals(2, rec.size());
- assertTrue(rec.get(0) instanceof DrawingRecord);
- assertTrue(rec.get(1) instanceof ContinueRecord);
-
- assertArrayEquals(data1, ((DrawingRecord)rec.get(0)).getRecordData());
- assertArrayEquals(data2, ((ContinueRecord)rec.get(1)).getData());
-
- }
-
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java
deleted file mode 100644
index 0f936fd405..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the TestEmbeddedObjectRefSubRecord
- * class works correctly. Test data taken directly from a real Excel file.
- */
-final class TestEmbeddedObjectRefSubRecord {
-
- private static final short EORSR_SID = EmbeddedObjectRefSubRecord.sid;
-
- @Test
- void testStore() {
- String data1
- = "20 00 05 00 FC 10 76 01 02 24 14 DF 00 03 10 00 "
- + "00 46 6F 72 6D 73 2E 43 68 65 63 6B 42 6F 78 2E "
- + "31 00 00 00 00 00 70 00 00 00 00 00 00 00 00 00 "
- + "00 00";
-
- byte[] src = hr(data1);
-
- RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, src);
-
- EmbeddedObjectRefSubRecord record1 = new EmbeddedObjectRefSubRecord(in, src.length);
-
- byte[] ser = record1.serialize();
-
- RecordInputStream in2 = TestcaseRecordInputStream.create(ser);
- EmbeddedObjectRefSubRecord record2 = new EmbeddedObjectRefSubRecord(in2, ser.length-4);
- confirmRecordEncoding(EmbeddedObjectRefSubRecord.sid, src, ser);
- assertEquals(record1.getOLEClassName(), record2.getOLEClassName());
-
- byte[] ser2 = record1.serialize();
- assertArrayEquals(ser, ser2);
- }
-
- @Test
- void testCreate() {
- EmbeddedObjectRefSubRecord record1 = new EmbeddedObjectRefSubRecord();
-
- byte[] ser = record1.serialize();
- RecordInputStream in2 = TestcaseRecordInputStream.create(ser);
- EmbeddedObjectRefSubRecord record2 = new EmbeddedObjectRefSubRecord(in2, ser.length-4);
-
- assertEquals(record1.getOLEClassName(), record2.getOLEClassName());
- assertEquals(record1.getStreamId(), record2.getStreamId());
-
- byte[] ser2 = record1.serialize();
- assertArrayEquals(ser, ser2);
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testCameraTool_bug45912() {
- /*
- * taken from ftPictFmla sub-record in attachment 22645 (offset 0x40AB).
- */
- byte[] data45912 = hr(
- "12 00 0B 00 F8 02 88 04 3B 00 " +
- "00 00 00 01 00 00 00 01 " +
- "00 00");
- RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data45912);
-
- EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data45912.length);
- byte[] ser2 = rec.serialize();
- confirmRecordEncoding(EmbeddedObjectRefSubRecord.sid, data45912, ser2);
- }
-
- private static byte[] hr(String string) {
- return HexRead.readFromString(string);
- }
-
- /**
- * tests various examples of OLE controls
- */
- @SuppressWarnings("squid:S2699")
- @Test
- void testVarious() {
- String[] rawData = {
- "12 00 0B 00 70 95 0B 05 3B 01 00 36 00 40 00 18 00 19 00 18",
- "12 00 0B 00 B0 4D 3E 03 3B 00 00 00 00 01 00 00 80 01 C0 00",
- "0C 00 05 00 60 AF 3B 03 24 FD FF FE C0 FE",
- "24 00 05 00 40 42 3E 03 02 80 CD B4 04 03 15 00 00 46 6F 72 6D 73 2E 43 6F 6D 6D 61 6E 64 42 75 74 74 6F 6E 2E 31 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00",
- "22 00 05 00 10 4E 3E 03 02 00 4C CC 04 03 12 00 00 46 6F 72 6D 73 2E 53 70 69 6E 42 75 74 74 6F 6E 2E 31 00 54 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00",
- "20 00 05 00 E0 41 3E 03 02 00 FC 0B 05 03 10 00 00 46 6F 72 6D 73 2E 43 6F 6D 62 6F 42 6F 78 2E 31 00 74 00 00 00 4C 00 00 00 00 00 00 00 00 00 00 00",
- "24 00 05 00 00 4C AF 03 02 80 E1 93 05 03 14 00 00 46 6F 72 6D 73 2E 4F 70 74 69 6F 6E 42 75 74 74 6F 6E 2E 31 00 C0 00 00 00 70 00 00 00 00 00 00 00 00 00 00 00",
- "20 00 05 00 E0 A4 28 04 02 80 EA 93 05 03 10 00 00 46 6F 72 6D 73 2E 43 68 65 63 6B 42 6F 78 2E 31 00 30 01 00 00 6C 00 00 00 00 00 00 00 00 00 00 00",
- "1C 00 05 00 30 40 3E 03 02 00 CC B4 04 03 0D 00 00 46 6F 72 6D 73 2E 4C 61 62 65 6C 2E 31 9C 01 00 00 54 00 00 00 00 00 00 00 00 00 00 00",
- "1E 00 05 00 B0 A4 28 04 02 00 D0 0A 05 03 0F 00 00 46 6F 72 6D 73 2E 4C 69 73 74 42 6F 78 2E 31 F0 01 00 00 48 00 00 00 00 00 00 00 00 00 00 00",
- "24 00 05 00 C0 AF 3B 03 02 80 D1 0A 05 03 14 00 00 46 6F 72 6D 73 2E 54 6F 67 67 6C 65 42 75 74 74 6F 6E 2E 31 00 38 02 00 00 6C 00 00 00 00 00 00 00 00 00 00 00",
- "1E 00 05 00 90 AF 3B 03 02 80 D4 0A 05 03 0F 00 00 46 6F 72 6D 73 2E 54 65 78 74 42 6F 78 2E 31 A4 02 00 00 48 00 00 00 00 00 00 00 00 00 00 00",
- "24 00 05 00 60 40 3E 03 02 00 D6 0A 05 03 14 00 00 46 6F 72 6D 73 2E 54 6F 67 67 6C 65 42 75 74 74 6F 6E 2E 31 00 EC 02 00 00 6C 00 00 00 00 00 00 00 00 00 00 00",
- "20 00 05 00 20 4D 3E 03 02 00 D9 0A 05 03 11 00 00 46 6F 72 6D 73 2E 53 63 72 6F 6C 6C 42 61 72 2E 31 58 03 00 00 20 00 00 00 00 00 00 00 00 00 00 00",
- "20 00 05 00 00 AF 28 04 02 80 31 AC 04 03 10 00 00 53 68 65 6C 6C 2E 45 78 70 6C 6F 72 65 72 2E 32 00 78 03 00 00 AC 00 00 00 00 00 00 00 00 00 00 00",
- };
-
- for (int i = 0; i < rawData.length; i++) {
- confirmRead(hr(rawData[i]), i);
- }
- }
-
- private static void confirmRead(byte[] data, int i) {
- RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data);
-
- EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data.length);
- byte[] ser2 = rec.serialize();
- confirmRecordEncoding("Test record " + i, EORSR_SID, data, ser2);
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testVisioDrawing_bug46199() {
- /*
- * taken from ftPictFmla sub-record in attachment 22860 (stream offset 0x768F).
- * Note that the since the string length is zero, there is no unicode flag byte
- */
- byte[] data46199 = hr(
- "0E 00 "
- + "05 00 "
- + "28 25 A3 01 "
- + "02 6C D1 34 02 "
- + "03 00 00 "
- + "0F CB E8 00");
- RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data46199);
-
- // bug 22860 - Not enough data (3) to read requested (4) bytes
- EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data46199.length);
- byte[] ser2 = rec.serialize();
- confirmRecordEncoding(EORSR_SID, data46199, ser2);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java
deleted file mode 100644
index 0a69b6554f..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.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.hssf.record;
-
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the EndSubRecord
- * class works correctly. Test data taken directly from a real Excel file.
- */
-final class TestEndSubRecord {
- private static final byte[] data = { };
-
- @Test
- void testLoad() {
- EndSubRecord record = new EndSubRecord(TestcaseRecordInputStream.create(0x00, data), 0);
- assertEquals(0, record.getDataSize());
- }
-
- @Test
- void testStore() {
- EndSubRecord record = new EndSubRecord();
- byte [] recordBytes = record.serialize();
- assertEquals(0, recordBytes.length - 4);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java b/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java
deleted file mode 100644
index 3578a8d99b..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.poi.ddf.EscherClientDataRecord;
-import org.apache.poi.ddf.EscherContainerRecord;
-import org.apache.poi.ddf.EscherSpRecord;
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the EscherAggregate class.
- */
-final class TestEscherAggregate {
- /**
- * Tests that the create aggregate method correctly rejoins escher records together.
- */
- @Test
- void testCreateAggregate() {
- String msoDrawingRecord1 =
- "0F 00 02 F0 20 01 00 00 10 00 08 F0 08 00 00 00 \n" +
- "03 00 00 00 02 04 00 00 0F 00 03 F0 08 01 00 00 \n" +
- "0F 00 04 F0 28 00 00 00 01 00 09 F0 10 00 00 00 \n" +
- "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \n" +
- "02 00 0A F0 08 00 00 00 00 04 00 00 05 00 00 00 \n" +
- "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 \n" +
- "01 04 00 00 00 0A 00 00 73 00 0B F0 2A 00 00 00 \n" +
- "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 \n" +
- "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 \n" +
- "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 \n" +
- "00 00 00 00 01 00 54 00 05 00 45 00 01 00 88 03 \n" +
- "05 00 94 00 00 00 11 F0 00 00 00 00";
-
- String msoDrawingRecord2 =
- "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 " +
- "02 04 00 00 80 0A 00 00 73 00 0B F0 2A 00 00 00 " +
- "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 " +
- "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 " +
- "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 " +
- "00 00 00 00 01 00 8D 03 05 00 E4 00 03 00 4D 03 " +
- "0B 00 0C 00 00 00 11 F0 00 00 00 00";
-
- DrawingRecord d1 = new DrawingRecord();
- d1.setData( HexRead.readFromString( msoDrawingRecord1 ) );
-
- ObjRecord r1 = new ObjRecord();
-
- DrawingRecord d2 = new DrawingRecord();
- d2.setData( HexRead.readFromString( msoDrawingRecord2 ) );
-
- ObjRecord r2 = new ObjRecord();
-
- List records = new ArrayList<>();
- records.add( d1 );
- records.add( r1 );
- records.add( d2 );
- records.add( r2 );
-
- EscherAggregate aggregate = EscherAggregate.createAggregate(records, 0);
-
- assertEquals( 1, aggregate.getEscherRecords().size() );
- assertEquals( (short) 0xF002, aggregate.getEscherRecord( 0 ).getRecordId() );
- assertEquals( 2, aggregate.getEscherRecord( 0 ).getChildRecords().size() );
- }
-
- @Test
- void testSerialize() {
-
- EscherContainerRecord container1 = new EscherContainerRecord();
- EscherContainerRecord spContainer1 = new EscherContainerRecord();
- EscherContainerRecord spContainer2 = new EscherContainerRecord();
- EscherContainerRecord spContainer3 = new EscherContainerRecord();
- EscherSpRecord sp1 = new EscherSpRecord();
- EscherSpRecord sp2 = new EscherSpRecord();
- EscherSpRecord sp3 = new EscherSpRecord();
- EscherClientDataRecord d2 = new EscherClientDataRecord();
- EscherClientDataRecord d3 = new EscherClientDataRecord();
-
- container1.setOptions( (short) 0x000F );
- spContainer1.setOptions( (short) 0x000F );
- spContainer1.setRecordId( EscherContainerRecord.SP_CONTAINER );
- spContainer2.setOptions( (short) 0x000F );
- spContainer2.setRecordId( EscherContainerRecord.SP_CONTAINER );
- spContainer3.setOptions( (short) 0x000F );
- spContainer3.setRecordId( EscherContainerRecord.SP_CONTAINER );
- d2.setRecordId( EscherClientDataRecord.RECORD_ID );
- d2.setRemainingData( new byte[0] );
- d3.setRecordId( EscherClientDataRecord.RECORD_ID );
- d3.setRemainingData( new byte[0] );
- container1.addChildRecord( spContainer1 );
- container1.addChildRecord( spContainer2 );
- container1.addChildRecord( spContainer3 );
- spContainer1.addChildRecord( sp1 );
- spContainer2.addChildRecord( sp2 );
- spContainer3.addChildRecord( sp3 );
- spContainer2.addChildRecord( d2 );
- spContainer3.addChildRecord( d3 );
-
- EscherAggregate aggregate = new EscherAggregate(false);
- aggregate.addEscherRecord( container1 );
- aggregate.associateShapeToObjRecord( d2, new ObjRecord() );
- aggregate.associateShapeToObjRecord( d3, new ObjRecord() );
-
- byte[] data = new byte[112];
- int bytesWritten = aggregate.serialize( 0, data );
- assertEquals( 112, bytesWritten );
- assertEquals( "[EC, 00, 40, 00, 0F, 00, 00, 00, 58, 00, 00, 00, 0F, 00, 04, F0, 10, 00, 00, 00, 00, 00, 0A, F0, 08, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 0F, 00, 04, F0, 18, 00, 00, 00, 00, 00, 0A, F0, 08, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 11, F0, 00, 00, 00, 00, 5D, 00, 00, 00, EC, 00, 20, 00, 0F, 00, 04, F0, 18, 00, 00, 00, 00, 00, 0A, F0, 08, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 11, F0, 00, 00, 00, 00, 5D, 00, 00, 00]",
- HexDump.toHex( data ) );
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java
deleted file mode 100644
index 6b0933cc31..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.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.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.IOException;
-
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.junit.jupiter.api.Test;
-
-final class TestExtSSTRecord {
-
- /**
- * ExtSSTRecord can be continued. Ensure we properly read the continue remainder.
- */
- @Test
- void test50967() throws IOException {
- // hex dump from ISBN_UPD_PL_20100104_1525.xls attached to Bugzilla 50867
- byte[] bytes = RawDataUtil.decompress("H4sIAAAAAAAAACWaBbAVxxZF9/jgrkFDcAvu7hrc3d3dLbhrgBDcXR8OwV2CEz" +
- "RIIFhw+4G/Zqiiqrn3zkyvvc/p7tM976sSp/CVOJIUVVJH2sa022lX0e6OLK0zpE9RpKemdCQav9lSlhhSCldqEEuq7EsbYkuLuGdJHG" +
- "km90yNJ43ggZETSP/jnuwJpR+4Z0QiqVdMaU5iaTz3NkoiVeGeH5JK8eNKtZJJZbk3SXIpenzpOu0p2l4ppTY8I0sq+uXeBT/Qx3dwpY" +
- "aLZ+xMK63h3tjpJfBUOYNUFO4FGbkO7mOZuMaSmmWRajhSnaxSefjn/AiHJ5nZpTfoyJ1DSgf/jzml79H8P9rntF9ySf+iJ00eKWF0fM" +
- "iLD+j5lI/+0TOxgDQEDzIVkpKho2BhWNExpIjUDf4eRaVWeDG2mDQAHS2KoxUvZpaQRqNnWEmuQU+vUuhEz5DS3Icno8tI/dA1pCyf8a" +
- "JVOQkk9SovlUTfuQrSb+h7VVHaj77rlaQVGLDlJ56JvthVpTvoy1BN+oC+gtWJCfo61eD/6NpdEyZ0xa0t/UWcCtbhd3TlrouP6CpfD7" +
- "3EqXx9WvStaQAP8TrQUJqMzkwkyyd09mgiFUdfrWbEEl2xW9Avuh61lLah50Qr6Rf0xG1DP+ip1fZbnJ62IwbouNEeDnQ87yD9io5Wnb" +
- "iWOC3rTLzQMbUL8UTHw67SdHSU7S69I9/W9JDqoWNRT/IIHYd64RM6KvchdsQpbj9Y0RG1P/EPcnUA36Oj3kDJh//QIK6Hf+cQfIc/yT" +
- "BYiU+j4dwD/84RfE9cHv5Mv+goPYo8Qcf00eglHj+MlWLCP2Sc1AH+iePxB/5hE/AYgTUmwo2OJpOkiuhoM5nv0DF1ijQIHcemEit0ZJ" +
- "qOv+iYOIP70bFqJrmBjk+z6BsdhWcTQ3TUmMPz0HFxLvFGx4FfGZ/EI9lvxA0db2jv0N6Z/23c+Av5Dl3RF/EsdI1dTO6gq89SchA9lZ" +
- "dJ+dFTfDn5Slz8lVyPrr0M/gnoyrlGsoJxs1bKhp4266Q86Km2XkqJnlsbpLXoWbFR6o2ebZukn9FzfbO0kjx7ukXaha5/tko7gvkgQr" +
- "qGrsjbadGVZof0lnzrtlMqhq6ru6Tl6Mq/R4pEfDrslQqgZ/Q+qTZ6ru7nd/Q0OSBlJc9GHJSqo2fFIfonTmcOS/PQZR6VzqOrzjEpLX" +
- "pqHf+Wb+dO4Du6Lp4kRsQr72n8Rd/9s8QEPb3OE1N0xLyAB+iocpGxj47pl/AoGCdX8Bz+qVeJA9xPr5G/xCXFDfqGe9BNYgl3g9tohH" +
- "f7nW/j/te7jCH8L3mPsQr3svvEEt4PD/g/vBf/hgf/szxmLMB77B+pJ5wFn0qP4Wz3TEqAgN3Ppbb4n/Bf6TC8515KA+Ft9VqKA+f4N1" +
- "K+YK5+K82GN8N76Qq8Iz4QP3gXfJQqwet+ljbj90PaaXD7/0lbyaNWX3gOfl//Ko2Cv5ph6Cv8PUxDKYP5yjJUAr9324bawt/NNZQcny" +
- "96hoYG4zqSEfr8v8iGVsHfKKqhqPi7LZqhFvzwJrqhRfD3YNB8T94otqF18JePY+gDfheNa+g5OlrFMxQX/u3xDbWCv3BCQ0/JlzqJDL" +
- "nwd0tsKEUwLyXhPvgnJjVUEN8fJTM0E/4VKQzVgnt0KkO54VVq+oF3XRpDDYJ5NR3f4/PM9IZYQvQwgxH6vSiToWzwFs1i6Cy827MaKo" +
- "PPLbIZeg3v/uyGfoIzSU5Dq+FckstQjsDnPIZ2wDknr6H0+Dw9v6FU8I0sYCgefCULGbqAv50KG/oPzvEsTt/BV7I435MX0ZnM58Hplj" +
- "I0A86dpQ2Vg/OHcoY2w7movBFYpUwVDf1KPlysZKgkfI2qGDoD37Cqhl7B92s1/IbvtxqGopMHHWoZugFf8dqGNsHXpY6hO/jYqZ6hW/" +
- "g4soGhd/C9amioGVwLGhuKSdw7NOU++Dq0oIXr31aGmsBTua2hvfC0aWeIFFWnDob+hWd7R0P54anW2dBF4nuki6Gy8AzpZsiE50Z3Q4" +
- "3w6xUm94CnQ2/iDE/pvoaO4depfoYq49eQAVyPTz6DdCw8QwbzGZ7SQ7kOnjTDDa0gD5eMMJQGn8yRhkYwft6MMtSL/Gsz5lv+VR4HH3" +
- "7ZTGILiOeXiYbmwLVosqHCcC2bYqg4eddrGr7C1W0GfsGVe5ahP+CqMpt8g+uvuYYG4U+7eeQdPOnmGzpEfv270NB44rZ9saEa+BN3ma" +
- "ENcAxYbighHH+t4D58Gs8gILU0fg0tHMsopkrC0WsD+Q3Hgk3w4E/sLdwPR5+thuLDsWQbfHA0iDD0idbfbmgZcTu3w1An4vbHLkNd4O" +
- "qwx1BkuPrs4z58WrffUEV82vm7oTrwmQfRj187aevA+e6Qoen41uUoeuF8dMzQSDjXnDA0Gs7RpxincE4+Y6gDnA3OGcoLZ6s/4IHz3Q" +
- "X8gbPyJfTAuegKOuHaexV/8WvddeJGHAfdMFSPOL65aegcfL/cJu7wrbpLf0EteI/O4Blxn7yCp85DQznJr+uPDG2DZxnBIxVV8injJc" +
- "ivZ4a6EtiELwydhyv/y2/jsfBrQ+/h+vWNoZrke4/3hjLDk/ujoRfwrPpsqDk+NfnPUCI4mnylhWOTYao9HCMsU4XgKO6a+kz8bvmmZt" +
- "F/8SimYtHvgmimOtNvupim3jPOvvDlafKmRRxTOfChYlxT39Hv1XimluPHkfimZhCvDwlMHYXjUCJT04iX+Z2p8/iyJImp7vjSL6mpcv" +
- "BsSmZqKPnUKoWpXMRtU0o+w1UtlamUcG35wdRw/Hma2tQu+HKnNeUQt0bpTGWGc0V6U5RcKp/RlA3viUwmmliPspi6DveRrKaGwJ0mmx" +
- "nWgfmzm2Gd2ymHGda5b3KaWgf/9VympsN/P7ep34J8y2vqAPzV8pmKCv/M/KaqwF+woBnOF38UMjUe/h+LmPoH/n5FTeUM1oliprLA/6" +
- "Y4zyXvWpQ0lQz+LaVMdYL/U2lTW4hz+bLwwl+xnBmO1zrlzbCO+qUC/aDjTkVTv6CjbGU+EO8sP5l6SLuXH3uhI2E1U+eCda86z0fHzh" +
- "qmuqHjVU1Tq9BRsDY60dGujqnvyYOLdeEN1un6pq6io2ID+iUO/6PdEsSjkans6NjS2FQH8uNTE1Ob0DOomanc6CjYnOfRnmlhaiR63r" +
- "VEH3oStoYDPcPamMqPngVtTbEV0Jl2ppgqdaq9KS7RZYrDruiJ3snUSgT/0NnUPvSU72LqAfHp19VUPPTU62bqLe2C7jwHXdt6mKoaxK" +
- "enqZ5BfHqZGoyuFH3IB+Kjvqbmou9D3295Fr+/qY3ocweYWkicPtHOQF+GQaYOB3XJYPIYnaWHmLqLzhpDTb1AZxeKoSjoazPclEXeFR" +
- "1h6k/a+D/zPPSmG2nqYDA+aPui1x9tajF5eIa2LbpfjTFFqa0jFPGV0X11nCks1Jbxpgqie9EEUxnQ/Xwi8UO3O9nUxGB/MsXUHOL5gX" +
- "YIulNMM7WC8Rx5hqmpwb6LdmQwrmby3KDummUqcTC+fzG1l9acbWos+tPNMbUB/fXmmvoL/T1YJIM6v8M84ob+4mySTqB/8nxTCdGdc6" +
- "Gp3ehOtsjUMvK1+GJ+R3+zJeQzunss5X50b1hmKi96660ww33LyJXf8vXH1Wa4L76+xlQd9B1aa6o4P4xfZyoy+g6t5zP6Rm7kenTV2G" +
- "TqD9qxm035xLXGFjOcR6ttJX/QWWebqcvobBNBngf1znb40JdpB/mMvj47GXfoW7WLcYuuy7tN1UDXqT2myqPrw158Ja7F95vaj74Gvz" +
- "P+0Vf8AJ/Rl/sgeY6+Pod4DvomHzYVPdg3H/mmL/Exxhv6mh1nngj23idM9UbnDyfNcB+Q9xT5RDyXnTYVA50jzph6RlvlrKkd6M10jj" +
- "xDb/7z5AXx/P6CqXHEMe5FUwPRWfgS8yM621xmHkRnsyumTqKz4lVTW9HZ7pqpC+icep15GJ2n/mQ+ROf/bphqic5lt+gXfZtuM9+i77" +
- "c7pjz0LbvL9+hb9ZepOOgbeY98pj1231Q24vfvA1N10Xnkoams6Nz5t6lU6Hz6yFRNdJr/MN7R2eKJKZY8vXlqqlFQLzwz1SYI9AtT7d" +
- "D3jrYJ+j5R7LRA35mX+EY8s7zGN3TmfmNqATpLvyUP0Vnlnamd6GzynrxC54APZriPO/WR+QR9tz6ZKhsrWJ9MxUVnFha5X9BZ4wt5TT" +
- "w7fWWeCvY9svQKvZcNS0XRWZ7NWBDHIbYV5ulkx9IndM50gUbfEs8K1/XYkSwNQF+KyJbYmmpiFEssidpGMZ6SSy9Hs1QMfZej0zrB+m" +
- "ZpGvpyx7K0EH0jYlt6gb5XcSw1RFfJeJbWo+tdfEtN0ZMmoaUp6NmeyFIq9ET+zlLP8DzH0nH0LElqKQY6TiSzlAsd+VNYWoqOA3SeGR" +
- "0rvrfCeF1PZakUOvKn5nd0ZEpjaRbxmpnWkoGOReksRUPHhvRWOO76ZLR0KqgLMlliClCPzJaOoUdZrfBcJ+GPljqgowNF/H50PMpuqS" +
- "DxeZjDUn50NMplaRM6zDyWaqGjVl5Lq9AxLJ+ly+TfsfyWkqDDZ9JqgI5uhSwdCc47CluKj450RfE1qLOKWTLRkbeEpfHo6FfS0hl0HC" +
- "plKSH8ycpY4fnNorKW3qEjWXlLVcHsV8HSWvg/VLSEFA2ojK8I61DF0ny4t1e19ATuH6tbag53hhrf/G9Q09IkuC/WsuTBfau2pVhwP2" +
- "Ly+Q7uDXUt3aN9U89SWvjbNLA0F/53DS2lJw5vSOq08Ldogr/B+Glq6Tzj50QzS/+hoyBFX2f4Z7YkfsThf62scLwUbWOpO/zr2lq6Sx" +
- "wKt+cz/K068Hz8r9bR0igrWM8s1cX/VV0s3XaDcxq4yJ9h3S1FoEM9yQP4f+tl6ULUYP2yVBP+6H0tlYA7Zj/yIKiT+lvKE9QZAyx1Df" +
- "Z1Ay0dDOrIQeiAf+YQSyfhLznMUl+4e1HsrIZ76khLR/E982hLzeBNNNZi7EixxlkaAu+u8VZYf5+cYIX7lJMTaeE9O8lSYXgPT7aUE9" +
- "+XTyHOcB+faikv3Ien8T3+n55uhedlh2fyGf93UZxkgHvlbOIN98E5lrLDXf1XSwfgrjqP/IN7/W+WksH9bD75BHf1hfyO7wkWWxpJ3t" +
- "RcYukQ/O2XWrqO742XkUfoaLycFv/nr2A843vVVZZ+Q0/yNVZ4zpRgnRXupyM2MC7gdjZbqgbvrC2W7sNrbbPC87DBEYwXeKPssFQH3m" +
- "K7LE2EM9UeS13gS7rPUjv4yuy3NB2+z79bKouvpQ5amgrf4EPcD1+iI5ZawVXzqKVFcM1j0P2Dz5+P81y4xpy0RAmvjKfxHZ8nnOF3+D" +
- "6eZZzhb8fzlk7A+eKCpYrwJb1kqR9+Hr9sKQ18B69aSgFf0ut8j5/eDfThY9OblvbCee8W8x+c6e/gG5z1/7K0Hc6I+5bi4tvyh/gA14" +
- "NHVngut/4fS2y5tfappQLw/P7c0k/E++i/5B0cUV5bmo1fj99Y6g3Hs3eW+sNR/SN5Dkf9z5Ye41Pj/yw9o/8XXy0NpN/1hq1C9LvDtF" +
- "UGf9batgrQf1XX1m386ezZ+g+Otr6t9/hzN5KtavgzNIqtV/BUjWqLJVn5otkipGoY3dYZfNrFopoJn6bEtGXClzS2rYnkYeY4tn6Ds3" +
- "9cW08D3+LzPXEdl8AOz9W3JrSVBt6Oie1wPz/uO76He3USW0ng/juprTqM/zzJba3Av7YpbF1Hx/CUdnguOOF7W1/Q83cqO9wfRqS2lQ" +
- "4d6dPZmgP/rPR2OO/+SfFWFv4XGW1RMqt+Zjucd7tmoV8u2Jf1G/+8bLYiw30zu63ycH/OYasN3LFy2xoEd6U8tnbCbeSz1Qnu1gzGi3" +
- "BHK2irH/FeWMhWdHhfF7bVBN5RReEMeCmu/oXzfQlbLeB8X8oOzy8/l+H5cBYqh5/EPV8FW1PhHFfRFiWAZlXmPvgaVrG1Db5E1Wx1g6" +
- "9EdVu/wvdfDVu1iP9/NWnhq1Db1hL4htexdYP56XFdW8XhK1Pf1gJ83dHAVmx8bdiI58H5Z2NbOeF72dQOz/dyMSgnwjeqla078O2giI" +
- "gN19p2tj7h45MOtlhyFIVNZR3ysRyb2pnEO1Z3W43gWdqTPIFnTG+bNZrx0ddWfPo/3I/n0H+8Abaa4dPggbZOwTF8sK1z+LR6qM2ek3" +
- "wZjo/kZf8RxAeO0z/bSgzH7VHEB59ajrG1CZ5942yxxVXqiXa4r347yVYx/Ok7xdZheBJNs9USnobT7fAct8JMW7PwJ2KWLQtf8sy2NZ" +
- "z4PZljh/P1vbm2ssK1Z54dntv+Pt9WNHxZvZBxANeTRVwH1+3FtjLCdXKJrQSMm2lLGTe0nZfZ4f627nJbSxk/9VfYWg5vGTZL0+CtsM" +
- "rWOvwrt9rWGuJbfQ3+w99/LfmHn63X2TqBju4sppfxdfMGfAvm843f8rH/Jq6jPbrZVgb0bN7C7/j8ZKutyuiKFGGrA37H2m6rR6Bvhx" +
- "2eZxTbST7g//JdPAd9o3bb+od23h46Q+ftveQH/h/ex7hB78r9tqKid+HvjBvyYe6Bb+Pr5kFbRdG9/hBxRO/5w+QNet8eIQ+Ceeso4w" +
- "u9WY+Tv+iNhZjm6H1Amwe9B0/aiofeladsUTJq42niAMJCJo/XtOPO2rqJ7obnbK0njjnO2/oZ/fn+sDUO3Wkv2OpLPFNetNUd/S9oi6" +
- "H/4CWei/6Bl22dpS1yxdYUfGh81dZGfCh0zdYkfIh23VZjfHhPW454Z7tB/PEh4ua3eD9jEiiCDy9u81x8uHTHVlp8WH/XloH+o3/ZSk" +
- "T8I+5xPT6svI+OYL55wGd8+P2hrTj4sPJvvqdd/Yh5FD+mPbb1AD96spicxY8iT2zNxo/mT22x9VFrNiEsWRr+HP34MOmFrcf40JdBfw" +
- "EffnpJ/uJDkVfchw/FMGsuPsR6Y6s9PqR9azM348s7W/3Rn+q9rYGB/g+2dqA/80dbo9Cf9ZOtMejP+Blf0V/pf3b4niLjf3xmHGb9wu" +
- "/4UOkr3+NDXTnajA8DDUdX8GGt6cgL9FuOYqG7jONoIXkw0OV39MfwHbVFb8NIjiLQO5dN5C30Lozi6D56p0R1xFZKkaI7YmrT8hiO/k" +
- "HnfzGd8L3YtNiOLqMvV1xHfdDVPJ6jZeialcDRdfRsTOToDToyJnHUCe62SR2tgXtCMic8nzuf3FFceL+mcML3eNO+53nE7WUqRznhrZ" +
- "na0S/wDk/j6Ai8+9I6MuGNk95RLXgHZnC0Fd7XGR1lhLNvZkcbicuVLI5AVawfHZUL5t/sjqrCmTGHE9a3OXI6YRzW53L0N7yTcjs6Sh" +
- "yMvI7y4X+5fI6Gwr2WYu0B/qcv6Kgp/DEKOyoD9+wijs7jd182MRvh/ruEo+Twni/tKBJ5lL4c18N3toKj5/j4sZIjlkw9qOKEdVPV6o" +
- "66wPF7TUd36L8xk3JwnjmPYnY3/U6q52gd/c5rwGf6PdkQ3/FtUmO+p9+NTfAvqJuaOkqMX+mbOypLnPe0cMJz89atHI3Er5RtiBN+DW" +
- "/raBE8H9lURjGC9cAJzze3dkI3XIm64B8+xermKBU+Ve/uhPPw7B5O+L4hVS9HufAnTh9HqeGc0tfRYjjv9XP0Fs6I/o6Ok58RA5xwHx" +
- "YxkBbeoYMdTYP37yGOPsLbepgT1s/thzsaCO+4EU74/qHrSEfDg3lpFPkKb0GVjVlmrKPKxLbUOHIP5rrjnfBsZ8oEJzyj6z0Jz4jxjs" +
- "mO9sN+YQo5h7c9pzkaAHvWGY5y4+3LmY4+wP7nL47+CuaWOY5KwlzsVzwL1v55jlbA+v43R1+IbdcF5DKssRYRM1hjLHYUH9a2S4gZrG" +
- "OWOZoMa8sVjjrAem+VE84R69c44d5kyjq0hTUyHsH18yZHXfH02mZHh+H6aaujAnDt2eZoJVzrt3MfXM13OvoJrly7HaWEq/4ecg2u6n" +
- "sdFYFr/j5H4/AywQFHFlwnDzJm4fp8iBwOuI446glX66OOqpODV445OghflBOO3hP7aCcdPYHzPe0l/LROO7oLb5wzjl7iZ46zzBH4Wf" +
- "Wco6xwlzvvKC1+lvgDHvibX3RUjFyYdgk9YQ3thGfPX684uslY736NMUZOpP3TkUMujLvB3IKOgywQC9FR5LajpPA/uANXMObvch9jJ/" +
- "29b3NUkfv8jo54Dxy9pv1Ie4Wxf/ghPqLr+N/0h660TLQOehYyEXVHT/unjgqhY/EzJ9juaetzR5QdevzC0S709H7JHICOHa+ccE06/M" +
- "bRLHREe+fodrAWvXfCs/MHH/ET/q2fuR/+9l94Lr7flKv18EaxXN3E9/mOq65w9fddVcLf5ZHd8Cy8bjRXcem/UAxXTOOaG9MN9yAJYr" +
- "v6g/47x3GVgfjXjct19J88vqvr9F8ugSub/s8ndDWePPg9sasBwZyfxNVDOOYndcN3Gr2Tu+FZ8ekUrkbDE5HSVTf8m/e9G75zaZrKVR" +
- "J8zPGDq+e0rVO7+h7On9K4iox/RdK6+kSbIB08+Jg6vas7wZ41g6uL+HmbdiY6zjIRjCQ/5lFY18DX05nd8Gx/fhb0oGswyZE7qCF/RB" +
- "z/UmZzdTXQmd3VmWBPmMPVbnz+SrsNvTdzupqO3o25XLVB7+zcbrhH7J4HP9A9I6+riuiekM9VyWBvm99VE/S/LuBqFfoTFXJ1jjzKzI" +
- "b5Pj6UK0Jn+PC1KM/Hh3nF4UR/pZL4SN7MLe2qWrBWlHXDd3OJKri6FuwlKrmai47qP7mKA/+TKq5W86jU1Vw9gHtudVf14bVqujoI78" +
- "8ErxScj+u4Wgnfi7rkAXxN67tKCVfGhq6ewFW7sasE8Jxv4moKPPGau7oEz6yWrmrj/4XWrqbhd7a2rl4GtWU7V14Kxm17V7PwuURHV7" +
- "eDmrKTG75rz9eF++Hb09VVXbjad+d6uGb0cJUNrrq9XL3Fx6O9XTXHv3194Q7Wqv5uWCPNHegqDz59HsTzyd/MQ10dD/auw9ywJr40nP" +
- "wlPzb+TP7C132UqxjBmjXG1WH41o91w7/1OT7ODc/U801wtTeo/SYSd/iMyeQHfB2nuHqFf0enEj/inXK6q2VwVp3h6jKcTWeSv8H8O4" +
- "s4wPn2F1f9ghp3jhuucX3nuvpCnCPNczURH2/SNoM7+XxXS+BOv8AN17oCC93wbHn9Irjw9R6Tahv4Cy11dYB4T1nmKn6Q3ytcHULHd6" +
- "tcLSCfvyO4Y9HRfA35jo6ea91wbzZlnRv+UcbfFKy10FFso6sN4Tzt6g1+D9+MLvSc3uKqIDoitrpKE+zV2cg1IB+uRbgqi57NO9zwHU" +
- "/zXTwfHfd2k3exg/karmCPtI/noGM9i1My+CcdQC/+xzjkalCwJzmMv/jf+yg+wX/tmBvW4odPuMoF97WTxBPu9KddzYb79RniDXeU86" +
- "4ItUr94WorvHUvEl98H3WZ+MJ58wpxhS/zdVfz4Mt8gzZYm2+6SgtXpNuu+sL1+Y6r9nA9/os8w9cy991wPUn5kDyGy3rkqjt+nn/sqh" +
- "h+lnrqakZQAz93tZlxdPylq0T0v+eNq2j4VPu9G64Hcz8xLug3z3+uRuFHza+ultJfbcPTcvq7YHlKRT/7HE8x6Cep56kj+uP5nlrSX/" +
- "JInjonC/6exNNEfLgU1VMG9KeM7qkX/daN6YklViVie/qF/hfG8fSOeM1l4/VvML8k9MJ3/CUS8zscF5J44buLCsk8LUD/4+SeCpNXcV" +
- "J6agNPy+897SQu+1J5igtX79ReePYUi8UvOHv6Lp2nLnCNyeDpFj54mTw1xYdKWdADT7FsnkhlvczhqQJxGJfb0wM44uVDB/meoICnrs" +
- "F8XtgLa/amFM676D9pcU+9g/WvhKfh+B+tlKfW9Ju5tKdR+HK7jKd89Hu0vBeehayu5OkRPtSs4mkq+o9X8+Sie0pNT2fwf35tL/ybi3" +
- "FMGsfod3g9T/vRbzXwwr/dKtLQ0wB86N/I0/bgbKmxp0xw/NzU0wF8yNrcUwc4drX09AGOa628cFylbOOpERyV2noaG9Q77b7xnG2P38" +
- "H629HTeLhedvIUmx86diFu8HXu6ompQvO7eeGZeM0exA9/yvXy1A5/LvTxwneljft5GhLM+/09ncCnSQO98O86tw72dJm8+TjUU2J8qj" +
- "3cUx/4lo7wdIQ4HWSjeR/OzyM9JYHTGOPpe/gyjvVUkTj1Hoff8K0dj9/E66eJnhoSr9mTiRt8H6d68vBv9XRPO4I9wUwv3JueneXpJj" +
- "4mmuMpLVzZ5noqAte+Xz2dxseFv3laj3/7FvAZ/xYv8sI9wIwlnhbDNWMZLfGLWOHpcHCWusrTWnjervHCs7hJ6/ALjj83eLoKx4RN+B" +
- "qcxWzxFD2Y5xnUU4nnhQhP5+BouMNTvaA+3OWF62LKvZ6S0f+TfeQD/iw+QF7Tf+pD6Kf/97TBO+P0R7zwb1X2HCW/8afpceKIPwVOMt" +
- "7w5egpL3w3U4lFezA8087BC091ipVgD7/vgqeXfrBn95QSnveXPaWHZ9JVT78Ttz+veYqGPyn/9FQdrro3PI3Dn9S3PNWGb/VtfISv/l" +
- "1PE8ivKfc8HSR+FottLuKW/qGn+vAV+9tTd/hGPSIO+PXyMfMDfuV4Ai+ceZ55ahbUqS8Yt+RXvH+98G8b47z0wjP0fK+88N1YsdfkL7" +
- "ypmcSr4GPPt174bmz4e+aLoM7+6Ok6Pt797CkqnAW+ML7hHPfVC8/UUhq+KsI5xvK1Bc6Bth/+zU8MBll+OOeTLCfgfO37ShbUFZF9lY" +
- "SzUFRfdfGxaTRfA+GMFcNXZjhLxfTF9kzzY/liiVDLOL6Gwjc8nq/5cOVL4KsmXNES++HfbnVN4msCXDOS+tpI/l9L5ustfLlS+KpKns" +
- "2mCN8KX6QffKUO6uXUvurjY+00vrrDVy6tr5bwtU3n62d8PJje120452X0w/onUmZfpeBLn4XriHfWbL7aB2en2fkd/zbm8PUMvmi5fZ" +
- "VjHOzK4+t9MA7ywxms1wXpH767hXwlhatzEV+r8a1xUV9z4ZtQzA/rjK/FfRXAP6+krxJwpi3tqzl81cv4mgRfmbK+hsNXvRyf4Wta3t" +
- "c8fLxSAV/xsXYlP/zb4pOV/XA+GVjFF1scrWQD/y+8xar7Gg3nsxp++I4kQW1fjeCcUsfXVfIyoq6vL8Q5Rn1ftcjLHA189YN7eUNfz/" +
- "E1dWNfHeC+1NRXkuCMsLmv7HAubenrKX7ebe0rXTBu2/p6CN/Ndn4433UmuWbCF9HR1y34Onb2NZ0fnnXxRUmv+t18DcPHSD18/Uj+le" +
- "jpqx18vXuhBz8H9va1BM57fXxFhm9Ufz/c498e4MuF6/ZA2mCfNNhXq2AfOsTXL/g6iaQJ6twXw3zFx9fVI3z9Ae+EkeQpvu4Y5Ydnvm" +
- "XG+OoE7/ux33g/s9nx4Z07gTyG9/ZE9AXzziRfj4Kz/8m+2CLq9RTMDPZ503xhtbpO9zUI/voz/bBeXzmL/uGOMRu/4D48h/7Jh1i/Ei" +
- "98PU97K1ZQv/nhGWX3+b6GwO8sJH5wJ13kK0Pg82JfH+DPsdQPzyTfLvNlwt1+ha8++N17pa8R8C9d7esM/LPX+uE7i2fr0Q3nyY2+KD" +
- "W0Y7Ovv/xgH+2HZ06tt/maHNQ9EfhH/Fvv4DOcR3eSL3D+HwCCjIRqMAAA");
-
- RecordInputStream in = TestcaseRecordInputStream.create(bytes);
- assertEquals(ExtSSTRecord.sid, in.getSid());
- ExtSSTRecord src = new ExtSSTRecord(in);
- assertEquals(12386, src.getDataSize());
- ExtSSTRecord.InfoSubRecord[] sub1 = src.getInfoSubRecords();
-
- byte[] serialized = src.serialize();
-
- in = TestcaseRecordInputStream.create(serialized);
- assertEquals(ExtSSTRecord.sid, in.getSid());
- ExtSSTRecord dst = new ExtSSTRecord(in);
- assertEquals(12386, dst.getDataSize());
- ExtSSTRecord.InfoSubRecord[] sub2 = src.getInfoSubRecords();
- assertEquals(sub1.length, sub2.length);
-
- for(int i = 0; i < sub1.length; i++){
- ExtSSTRecord.InfoSubRecord s1 = sub1[i];
- ExtSSTRecord.InfoSubRecord s2 = sub2[i];
-
- assertEquals(s1.getBucketSSTOffset(), s2.getBucketSSTOffset());
- assertEquals(s1.getStreamPos(), s2.getStreamPos());
-
- }
- }
-
-
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java
deleted file mode 100644
index f4d191d69f..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-final class TestExtendedFormatRecord {
-
- private static final byte[] data = {
- 0, 0, // Font 0
- 0, 0, // Format 0
- 0xF5 - 256, 0xFF - 256, // Cell opts ...
- 0x20, 0, // Alignment 20
- 0, 0, // Ident 0
- 0, 0, // Border 0
- 0, 0, // Palette 0
- 0, 0, 0, 0, // ADTL Palette 0
- 0xC0 - 256, 0x20 // Fill Palette 20c0
- };
-
- private static ExtendedFormatRecord createEFR() {
- return new ExtendedFormatRecord(TestcaseRecordInputStream.create(0x00E0, data));
- }
-
- @Test
- void testLoad() {
- ExtendedFormatRecord record = createEFR();
- assertEquals(0, record.getFontIndex());
- assertEquals(0, record.getFormatIndex());
- assertEquals(0xF5 - 256, record.getCellOptions());
- assertEquals(0x20, record.getAlignmentOptions());
- assertEquals(0, record.getIndentionOptions());
- assertEquals(0, record.getBorderOptions());
- assertEquals(0, record.getPaletteOptions());
- assertEquals(0, record.getAdtlPaletteOptions());
- assertEquals(0x20c0, record.getFillPaletteOptions());
-
- assertEquals(20 + 4, record.getRecordSize());
- }
-
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
-// .fontindex = 0
-// .formatindex = 0
-// .celloptions = fffffff5
-// .islocked = true
-// .ishidden = false
-// .recordtype= 1
-// .parentidx = fff
-// .alignmentoptions= 20
-// .alignment = 0
-// .wraptext = false
-// .valignment= 2
-// .justlast = 0
-// .rotation = 0
-// .indentionoptions= 0
-// .indent = 0
-// .shrinktoft= false
-// .mergecells= false
-// .readngordr= 0
-// .formatflag= false
-// .fontflag = false
-// .prntalgnmt= false
-// .borderflag= false
-// .paternflag= false
-// .celloption= false
-// .borderoptns = 0
-// .lftln = 0
-// .rgtln = 0
-// .topln = 0
-// .btmln = 0
-// .paleteoptns = 0
-// .leftborder= 0
-// .rghtborder= 0
-// .diag = 0
-// .paleteoptn2 = 0
-// .topborder = 0
-// .botmborder= 0
-// .adtldiag = 0
-// .diaglnstyl= 0
-// .fillpattrn= 0
-// .fillpaloptn = 20c0
-// .foreground= 40
-// .background= 41
-
- ExtendedFormatRecord record = new ExtendedFormatRecord();
- record.setFontIndex((short) 0);
- record.setFormatIndex((short) 0);
-
- record.setLocked(true);
- record.setHidden(false);
- record.setXFType((short) 1);
- record.setParentIndex((short) 0xfff);
-
- record.setVerticalAlignment((short) 2);
-
- record.setFillForeground((short) 0x40);
- record.setFillBackground((short) 0x41);
-
- byte[] recordBytes = record.serialize();
- confirmRecordEncoding(ExtendedFormatRecord.sid, data, recordBytes);
- }
-
-
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testCloneOnto() {
- ExtendedFormatRecord base = createEFR();
-
- ExtendedFormatRecord other = new ExtendedFormatRecord();
- other.cloneStyleFrom(base);
-
- byte[] recordBytes = other.serialize();
- confirmRecordEncoding(ExtendedFormatRecord.sid, data, recordBytes);
- }
-
- @Test
- void testRotation() {
- ExtendedFormatRecord record = createEFR();
- assertEquals(0, record.getRotation());
-
- record.setRotation((short)1);
- assertEquals(1, record.getRotation());
-
- record.setRotation((short)89);
- assertEquals(89, record.getRotation());
-
- record.setRotation((short)90);
- assertEquals(90, record.getRotation());
-
- // internally values below zero are stored differently
- record.setRotation((short)-1);
- assertEquals(255, record.getRotation());
-
- record.setRotation((short)-89);
- assertEquals(-77, 90-record.getRotation());
-
- record.setRotation((short)-90);
- assertEquals(-76, 90-record.getRotation());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java
deleted file mode 100644
index 41372882c6..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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 org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-final class TestExternalNameRecord {
-
- private static final byte[] dataFDS = {
- 0, 0, 0, 0, 0, 0, 3, 0, 70, 68, 83, 0, 0,
- };
-
- // data taken from bugzilla 44774 att 21790
- private static final byte[] dataAutoDocName = {
- -22, 127, 0, 0, 0, 0, 29, 0, 39, 49, 57, 49, 50, 49, 57, 65, 87, 52, 32, 67, 111, 114,
- 112, 44, 91, 87, 79, 82, 75, 79, 85, 84, 95, 80, 88, 93, 39,
- };
-
- // data taken from bugzilla 44774 att 21790
- private static final byte[] dataPlainName = {
- 0, 0, 0, 0, 0, 0, 9, 0, 82, 97, 116, 101, 95, 68, 97, 116, 101, 9, 0, 58, 0, 0, 0, 0, 4, 0, 8, 0
- // TODO - the last 2 bytes of formula data (8,0) seem weird. They encode to ConcatPtg, UnknownPtg
- // UnknownPtg is otherwise not created by any other test cases
- };
-
- private static ExternalNameRecord createSimpleENR(byte[] data) {
- return new ExternalNameRecord(TestcaseRecordInputStream.create(0x0023, data));
- }
-
- @Test
- void testBasicDeserializeReserialize() {
-
- ExternalNameRecord enr = createSimpleENR(dataFDS);
- assertEquals("FDS", enr.getText());
-
- // bug 44695
- confirmRecordEncoding(0x0023, dataFDS, enr.serialize());
- }
-
- @Test
- void testBasicSize() {
- ExternalNameRecord enr = createSimpleENR(dataFDS);
- assertNotEquals(13, enr.getRecordSize(), "Identified bug 44695");
- assertEquals(17, enr.getRecordSize());
-
- assertNotNull(enr.serialize());
- }
-
- @Test
- void testAutoStdDocName() {
-
- ExternalNameRecord enr = createSimpleENR(dataAutoDocName);
- assertEquals("'191219AW4 Corp,[WORKOUT_PX]'", enr.getText());
- assertTrue(enr.isAutomaticLink());
- assertFalse(enr.isBuiltInName());
- assertFalse(enr.isIconifiedPictureLink());
- assertFalse(enr.isOLELink());
- assertFalse(enr.isPicureLink());
- assertTrue(enr.isStdDocumentNameIdentifier());
-
- confirmRecordEncoding(0x0023, dataAutoDocName, enr.serialize());
- }
-
- @Test
- void testPlainName() {
-
- ExternalNameRecord enr = createSimpleENR(dataPlainName);
- assertEquals("Rate_Date", enr.getText());
- assertFalse(enr.isAutomaticLink());
- assertFalse(enr.isBuiltInName());
- assertFalse(enr.isIconifiedPictureLink());
- assertFalse(enr.isOLELink());
- assertFalse(enr.isPicureLink());
- assertFalse(enr.isStdDocumentNameIdentifier());
-
- confirmRecordEncoding(0x0023, dataPlainName, enr.serialize());
- }
-
- @Test
- void testDDELink_bug47229() {
- /*
- * Hex dump read directly from text of bugzilla 47229
- */
- final byte[] dataDDE = HexRead.readFromString(
- "E2 7F 00 00 00 00 " +
- "37 00 " + // text len
- // 010672AT0 MUNI,[RTG_MOODY_UNDERLYING,RTG_SP_UNDERLYING]
- "30 31 30 36 37 32 41 54 30 20 4D 55 4E 49 2C " +
- "5B 52 54 47 5F 4D 4F 4F 44 59 5F 55 4E 44 45 52 4C 59 49 4E 47 2C " +
- "52 54 47 5F 53 50 5F 55 4E 44 45 52 4C 59 49 4E 47 5D " +
- // constant array { { "#N/A N.A.", "#N/A N.A.", }, }
- " 01 00 00 " +
- "02 09 00 00 23 4E 2F 41 20 4E 2E 41 2E " +
- "02 09 00 00 23 4E 2F 41 20 4E 2E 41 2E");
-
- // actual msg reported in bugzilla 47229 is different
- // because that seems to be using a version from before svn r646666
- ExternalNameRecord enr = createSimpleENR(dataDDE);
- assertEquals("010672AT0 MUNI,[RTG_MOODY_UNDERLYING,RTG_SP_UNDERLYING]", enr.getText());
-
- confirmRecordEncoding(0x0023, dataDDE, enr.serialize());
- }
-
- @Test
- void testUnicodeName_bug47384() {
- // data taken from bugzilla 47384 att 23830 at offset 0x13A0
- byte[] dataUN = HexRead.readFromString(
- "23 00 22 00" +
- "00 00 00 00 00 00 " +
- "0C 01 " +
- "59 01 61 00 7A 00 65 00 6E 00 ED 00 5F 00 42 00 69 00 6C 00 6C 00 61 00" +
- "00 00");
-
- RecordInputStream in = TestcaseRecordInputStream.create(dataUN);
- ExternalNameRecord enr = new ExternalNameRecord(in);
- assertEquals("\u0159azen\u00ED_Billa", enr.getText());
- byte[] ser = enr.serialize();
- assertEquals(HexDump.toHex(dataUN), HexDump.toHex(ser));
- }
-
- @Test
- void test48339() {
- // data taken from bugzilla 48339
- byte[] data = HexRead.readFromString(
- "23 00 09 00" +
- "F4, FF, 14, 2D, 61, 01, 01, 00, 27");
-
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- ExternalNameRecord enr = new ExternalNameRecord(in);
- byte[] ser = enr.serialize();
- assertEquals(HexDump.toHex(data), HexDump.toHex(ser));
- }
-
- @Test
- void testNPEWithFileFrom49219() {
- // the file at test-data/spreadsheet/49219.xls has ExternalNameRecords without actual data,
- // we did handle this during reading, but failed during serializing this out, ensure it works now
- byte[] data = new byte[] {
- 2, 127, 0, 0, 0, 0,
- 9, 0, 82, 97, 116, 101, 95, 68, 97, 116, 101};
-
- ExternalNameRecord enr = createSimpleENR(data);
-
- byte[] ser = enr.serialize();
- assertEquals("[23, 00, 11, 00, 02, 7F, 00, 00, 00, 00, 09, 00, 52, 61, 74, 65, 5F, 44, 61, 74, 65]",
- HexDump.toHex(ser));
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java
deleted file mode 100644
index c6a9cd9581..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-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 java.io.IOException;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.InternalSheet;
-import org.apache.poi.hssf.model.InternalWorkbook;
-import org.apache.poi.hssf.record.common.FeatFormulaErr2;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFTestHelper;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for FeatRecord
- */
-final class TestFeatRecord {
- @Test
- void testWithoutFeatRecord() throws Exception {
- HSSFWorkbook hssf =
- HSSFTestDataSamples.openSampleWorkbook("46136-WithWarnings.xls");
- InternalWorkbook wb = HSSFTestHelper.getWorkbookForTest(hssf);
-
- assertEquals(1, hssf.getNumberOfSheets());
-
- int countFR = 0;
- int countFRH = 0;
-
- // Check on the workbook, but shouldn't be there!
- for(org.apache.poi.hssf.record.Record r : wb.getRecords()) {
- if(r instanceof FeatRecord) {
- countFR++;
- } else if (r.getSid() == FeatRecord.sid) {
- countFR++;
- }
- if(r instanceof FeatHdrRecord) {
- countFRH++;
- } else if (r.getSid() == FeatHdrRecord.sid) {
- countFRH++;
- }
- }
-
- assertEquals(0, countFR);
- assertEquals(0, countFRH);
-
- // Now check on the sheet
- HSSFSheet s = hssf.getSheetAt(0);
- InternalSheet sheet = HSSFTestHelper.getSheetForTest(s);
-
- for(RecordBase rb : sheet.getRecords()) {
- if(rb instanceof Record) {
- Record r = (org.apache.poi.hssf.record.Record)rb;
- if(r instanceof FeatRecord) {
- countFR++;
- } else if (r.getSid() == FeatRecord.sid) {
- countFR++;
- }
- if(r instanceof FeatHdrRecord) {
- countFRH++;
- } else if (r.getSid() == FeatHdrRecord.sid) {
- countFRH++;
- }
- }
- }
-
- assertEquals(0, countFR);
- assertEquals(0, countFRH);
- }
-
- @Test
- void testReadFeatRecord() {
- HSSFWorkbook hssf =
- HSSFTestDataSamples.openSampleWorkbook("46136-NoWarnings.xls");
- InternalWorkbook wb = HSSFTestHelper.getWorkbookForTest(hssf);
-
- FeatRecord fr = null;
- FeatHdrRecord fhr = null;
-
- assertEquals(1, hssf.getNumberOfSheets());
-
- // First check it isn't on the Workbook
- int countFR = 0;
- int countFRH = 0;
- for(org.apache.poi.hssf.record.Record r : wb.getRecords()) {
- if(r instanceof FeatRecord) {
- fr = (FeatRecord)r;
- countFR++;
- } else if (r.getSid() == FeatRecord.sid) {
- fail("FeatRecord SID found but not created correctly!");
- }
- if(r instanceof FeatHdrRecord) {
- countFRH++;
- } else if (r.getSid() == FeatHdrRecord.sid) {
- fail("FeatHdrRecord SID found but not created correctly!");
- }
- }
-
- assertEquals(0, countFR);
- assertEquals(0, countFRH);
-
- // Now find it on our sheet
- HSSFSheet s = hssf.getSheetAt(0);
- InternalSheet sheet = HSSFTestHelper.getSheetForTest(s);
-
- for(RecordBase rb : sheet.getRecords()) {
- if(rb instanceof Record) {
- Record r = (org.apache.poi.hssf.record.Record)rb;
- if(r instanceof FeatRecord) {
- fr = (FeatRecord)r;
- countFR++;
- } else if (r.getSid() == FeatRecord.sid) {
- countFR++;
- }
- if(r instanceof FeatHdrRecord) {
- fhr = (FeatHdrRecord)r;
- countFRH++;
- } else if (r.getSid() == FeatHdrRecord.sid) {
- countFRH++;
- }
- }
- }
-
- assertEquals(1, countFR);
- assertEquals(1, countFRH);
- assertNotNull(fr);
- assertNotNull(fhr);
-
- // Now check the contents are as expected
- assertEquals(
- FeatHdrRecord.SHAREDFEATURES_ISFFEC2,
- fr.getIsf_sharedFeatureType()
- );
-
- // Applies to one cell only
- assertEquals(1, fr.getCellRefs().length);
- assertEquals(0, fr.getCellRefs()[0].getFirstRow());
- assertEquals(0, fr.getCellRefs()[0].getLastRow());
- assertEquals(0, fr.getCellRefs()[0].getFirstColumn());
- assertEquals(0, fr.getCellRefs()[0].getLastColumn());
-
- // More checking of shared features stuff
- assertEquals(4, fr.getCbFeatData());
- assertEquals(4, fr.getSharedFeature().getDataSize());
- assertEquals(FeatFormulaErr2.class, fr.getSharedFeature().getClass());
-
- FeatFormulaErr2 fferr2 = (FeatFormulaErr2)fr.getSharedFeature();
- assertEquals(0x04, fferr2._getRawErrorCheckValue());
-
- assertFalse(fferr2.getCheckCalculationErrors());
- assertFalse(fferr2.getCheckDateTimeFormats());
- assertFalse(fferr2.getCheckEmptyCellRef());
- assertFalse(fferr2.getCheckInconsistentFormulas());
- assertFalse(fferr2.getCheckInconsistentRanges());
- assertTrue(fferr2.getCheckNumbersAsText());
- assertFalse(fferr2.getCheckUnprotectedFormulas());
- assertFalse(fferr2.getPerformDataValidation());
- }
-
- /**
- * cloning sheets with feat records
- */
- @Test
- void testCloneSheetWithFeatRecord() throws IOException {
- try (HSSFWorkbook wb =
- HSSFTestDataSamples.openSampleWorkbook("46136-WithWarnings.xls")) {
- HSSFSheet src = wb.getSheetAt(0);
- HSSFSheet dst = wb.cloneSheet(0);
-
- InternalSheet isrc = HSSFTestHelper.getSheetForTest(src);
- InternalSheet idst = HSSFTestHelper.getSheetForTest(dst);
-
- assertEquals(isrc.getRecords().size(), idst.getRecords().size());
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java
deleted file mode 100644
index 2dbaeb4818..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestFontRecord.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.hssf.record;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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 org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the {@link FontRecord}
- * class works correctly. Test data taken directly from a real Excel file.
- */
-final class TestFontRecord {
-
- private static final int SID = 0x31;
- private static final byte[] data = {
- 0xC8-256, 0, // font height = xc8
- 0, 0, // attrs = 0
- 0xFF-256, 0x7F, // colour palette = x7fff
- 0x90-256, 0x01, // bold weight = x190
- 0, 0, // supersubscript
- 0, 0, // underline, family
- 0, 0, // charset, padding
- 5, 0, // name length, unicode flag
- 0x41, 0x72, 0x69, 0x61, 0x6C, // Arial, as unicode
-
- };
-
- @Test
- void testLoad() {
-
- FontRecord record = new FontRecord(TestcaseRecordInputStream.create(0x31, data));
- assertEquals(0xc8, record.getFontHeight());
- assertEquals(0x00, record.getAttributes());
- assertFalse(record.isItalic());
- assertFalse(record.isStruckout());
- assertFalse(record.isMacoutlined());
- assertFalse(record.isMacshadowed());
- assertEquals(0x7fff, record.getColorPaletteIndex());
- assertEquals(0x190, record.getBoldWeight());
- assertEquals(0x00, record.getSuperSubScript());
- assertEquals(0x00, record.getUnderline());
- assertEquals(0x00, record.getFamily());
- assertEquals(0x00, record.getCharset());
- assertEquals("Arial", record.getFontName());
-
- assertEquals(21 + 4, record.getRecordSize());
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
-// .fontheight = c8
-// .attributes = 0
-// .italic = false
-// .strikout = false
-// .macoutlined= false
-// .macshadowed= false
-// .colorpalette = 7fff
-// .boldweight = 190
-// .supersubscript = 0
-// .underline = 0
-// .family = 0
-// .charset = 0
-// .namelength = 5
-// .fontname = Arial
-
- FontRecord record = new FontRecord();
- record.setFontHeight((short)0xc8);
- record.setAttributes((short)0);
- record.setColorPaletteIndex((short)0x7fff);
- record.setBoldWeight((short)0x190);
- record.setSuperSubScript((short)0);
- record.setUnderline((byte)0);
- record.setFamily((byte)0);
- record.setCharset((byte)0);
- record.setFontName("Arial");
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(0x31, data, recordBytes);
- }
-
- @Test
- void testCloneOnto() {
- FontRecord base = new FontRecord(TestcaseRecordInputStream.create(0x31, data));
-
- FontRecord other = new FontRecord();
- other.cloneStyleFrom(base);
-
- byte [] recordBytes = other.serialize();
- assertEquals(recordBytes.length - 4, data.length);
- for (int i = 0; i < data.length; i++)
- assertEquals(data[i], recordBytes[i+4], "At offset " + i);
- }
-
- @Test
- void testSameProperties() {
- FontRecord f1 = new FontRecord(TestcaseRecordInputStream.create(0x31, data));
- FontRecord f2 = new FontRecord(TestcaseRecordInputStream.create(0x31, data));
-
- assertTrue(f1.sameProperties(f2));
-
- f2.setFontName("Arial2");
- assertFalse(f1.sameProperties(f2));
- f2.setFontName("Arial");
- assertTrue(f1.sameProperties(f2));
-
- f2.setFontHeight((short)11);
- assertFalse(f1.sameProperties(f2));
- f2.setFontHeight((short)0xc8);
- assertTrue(f1.sameProperties(f2));
- }
-
- /**
- * Bugzilla 47250 suggests that the unicode options byte should be present even when the name
- * length is zero. The OOO documentation seems to agree with this and POI had no test data
- * samples to say otherwise.
- */
- @Test
- void testEmptyName_bug47250() {
- byte[] emptyNameData = HexRead.readFromString(
- "C8 00 00 00 FF 7F 90 01 00 00 00 00 00 00 "
- + "00" // zero length
- + "00" // unicode options byte
- );
-
- RecordInputStream in = TestcaseRecordInputStream.create(SID, emptyNameData);
- FontRecord fr = new FontRecord(in);
- assertNotEquals(1, in.available());
- assertEquals(0, in.available());
-
- assertEquals(0, fr.getFontName().length());
- byte[] recordBytes = fr.serialize();
- confirmRecordEncoding(SID, emptyNameData, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java
deleted file mode 100644
index 623588ffee..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-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.formula.ptg.AttrPtg;
-import org.apache.poi.ss.formula.ptg.FuncVarPtg;
-import org.apache.poi.ss.formula.ptg.IntPtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.formula.ptg.RefPtg;
-import org.apache.poi.ss.usermodel.CellType;
-import org.apache.poi.ss.usermodel.FormulaError;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link FormulaRecord}
- */
-final class TestFormulaRecord {
-
- @Test
- void testCreateFormulaRecord () {
- FormulaRecord record = new FormulaRecord();
- record.setColumn((short)0);
- record.setRow(1);
- record.setXFIndex((short)4);
-
- assertEquals(record.getColumn(),0);
- assertEquals(record.getRow(), 1);
- assertEquals(record.getXFIndex(),4);
- }
-
- /**
- * Make sure a NAN value is preserved
- * This formula record is a representation of =1/0 at row 0, column 0
- */
- @Test
- void testCheckNanPreserve() {
- byte[] formulaByte = {
- 0, 0, 0, 0,
- 0x0F, 0x00,
-
- // 8 bytes cached number is a 'special value' in this case
- 0x02, // special cached value type 'error'
- 0x00,
- FormulaError.DIV0.getCode(),
- 0x00,
- 0x00,
- 0x00,
- (byte)0xFF,
- (byte)0xFF,
-
- 0x00,
- 0x00,
- 0x00,
- 0x00,
-
- (byte)0xE0, //18
- (byte)0xFC,
- // Ptgs
- 0x07, 0x00, // encoded length
- 0x1E, 0x01, 0x00, // IntPtg(1)
- 0x1E, 0x00, 0x00, // IntPtg(0)
- 0x06, // DividePtg
-
- };
-
- FormulaRecord record = new FormulaRecord(TestcaseRecordInputStream.create(FormulaRecord.sid, formulaByte));
- assertEquals(0, record.getRow(), "Row");
- assertEquals(0, record.getColumn(), "Column");
- //noinspection deprecation
- assertEquals(CellType.ERROR.getCode(), record.getCachedResultType());
- assertEquals(CellType.ERROR, record.getCachedResultTypeEnum());
-
- byte[] output = record.serialize();
- // includes sid+recordlength
- assertEquals(33, output.length, "Output size");
-
- for (int i = 5; i < 13;i++) {
- assertEquals(formulaByte[i], output[i+4], "FormulaByte NaN doesn't match");
- }
- }
-
- /**
- * Tests to see if the shared formula cells properly reserialize the expPtg
- */
- @Test
- void testExpFormula() {
- byte[] formulaByte = new byte[27];
-
- formulaByte[4] =(byte)0x0F;
- formulaByte[14]=(byte)0x08;
- formulaByte[18]=(byte)0xE0;
- formulaByte[19]=(byte)0xFD;
- formulaByte[20]=(byte)0x05;
- formulaByte[22]=(byte)0x01;
- FormulaRecord record = new FormulaRecord(TestcaseRecordInputStream.create(FormulaRecord.sid, formulaByte));
- assertEquals(0, record.getRow(), "Row");
- assertEquals(0, record.getColumn(), "Column");
- byte[] output = record.serialize();
- // includes sid+recordlength
- assertEquals(31, output.length, "Output size");
- assertEquals(1, output[26], "Offset 22");
- }
-
- @Test
- void testWithConcat() {
- // =CHOOSE(2,A2,A3,A4)
- byte[] data = {
- 1, 0, 1, 0, 15, 0, 0, 0, 0, 0, 0, 0, 57,
- 64, 0, 0, 12, 0, 12, -4, 46, 0,
- 30, 2, 0, // Int - 2
- 25, 4, 3, 0, // Attr
- 8, 0, 17, 0, 26, 0, // jumpTable
- 35, 0, // chooseOffset
- 36, 1, 0, 0, -64, // Ref - A2
- 25, 8, 21, 0, // Attr
- 36, 2, 0, 0, -64, // Ref - A3
- 25, 8, 12, 0, // Attr
- 36, 3, 0, 0, -64, // Ref - A4
- 25, 8, 3, 0, // Attr
- 66, 4, 100, 0 // CHOOSE
- };
- RecordInputStream inp = TestcaseRecordInputStream.create(FormatRecord.sid, data);
-
- FormulaRecord fr = new FormulaRecord(inp);
-
- Ptg[] ptgs = fr.getParsedExpression();
- assertEquals(9, ptgs.length);
- assertEquals(IntPtg.class, ptgs[0].getClass());
- assertEquals(AttrPtg.class, ptgs[1].getClass());
- assertEquals(RefPtg.class, ptgs[2].getClass());
- assertEquals(AttrPtg.class, ptgs[3].getClass());
- assertEquals(RefPtg.class, ptgs[4].getClass());
- assertEquals(AttrPtg.class, ptgs[5].getClass());
- assertEquals(RefPtg.class, ptgs[6].getClass());
- assertEquals(AttrPtg.class, ptgs[7].getClass());
- assertEquals(FuncVarPtg.class, ptgs[8].getClass());
-
- FuncVarPtg choose = (FuncVarPtg)ptgs[8];
- assertEquals("CHOOSE", choose.getName());
- }
-
- @Test
- void testReserialize() {
- FormulaRecord formulaRecord = new FormulaRecord();
- formulaRecord.setRow(1);
- formulaRecord.setColumn((short) 1);
- formulaRecord.setParsedExpression(new Ptg[] { new RefPtg("B$5"), });
- formulaRecord.setValue(3.3);
- byte[] ser = formulaRecord.serialize();
- assertEquals(31, ser.length);
-
- RecordInputStream in = TestcaseRecordInputStream.create(ser);
- FormulaRecord fr2 = new FormulaRecord(in);
- assertEquals(3.3, fr2.getValue(), 0.0);
- Ptg[] ptgs = fr2.getParsedExpression();
- assertEquals(1, ptgs.length);
- RefPtg rp = (RefPtg) ptgs[0];
- assertEquals("B$5", rp.toFormulaString());
- }
-
- /**
- * Bug noticed while fixing 46479. Operands of conditional operator ( ? : ) were swapped
- * inside {@link FormulaRecord}
- */
- @Test
- void testCachedValue_bug46479() {
- FormulaRecord fr0 = new FormulaRecord();
- FormulaRecord fr1 = new FormulaRecord();
- // test some other cached value types
- fr0.setValue(3.5);
- assertEquals(3.5, fr0.getValue(), 0.0);
- fr0.setCachedResultErrorCode(FormulaError.REF.getCode());
- assertEquals(FormulaError.REF.getCode(), fr0.getCachedErrorValue());
-
- fr0.setCachedResultBoolean(false);
- fr1.setCachedResultBoolean(true);
- assertFalse(fr0.getCachedBooleanValue() && !fr1.getCachedBooleanValue(), "Identified bug 46479c");
- assertFalse(fr0.getCachedBooleanValue());
- assertTrue(fr1.getCachedBooleanValue());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java
deleted file mode 100644
index 2804fe3d71..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the FtCblsSubRecord
- * class works correctly.
- */
-final class TestFtCblsSubRecord {
- private final byte[] data = new byte[] {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00,
- 0x01, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00
- };
-
- @Test
- void testRead() {
- FtCblsSubRecord record = new FtCblsSubRecord(TestcaseRecordInputStream.create(FtCblsSubRecord.sid, data), data.length);
-
- assertEquals(FtCblsSubRecord.sid, record.getSid());
- assertEquals(data.length, record.getDataSize());
- }
-
- @Test
- void testWrite() {
- FtCblsSubRecord record = new FtCblsSubRecord();
- assertEquals(FtCblsSubRecord.sid, record.getSid());
- assertEquals(data.length, record.getDataSize());
-
- byte [] ser = record.serialize();
- assertEquals(ser.length - 4, data.length);
- }
-
- @Test
- void testClone() {
- FtCblsSubRecord record = new FtCblsSubRecord();
- byte[] src = record.serialize();
-
- FtCblsSubRecord cloned = record.copy();
- byte[] cln = cloned.serialize();
-
- assertEquals(record.getDataSize(), cloned.getDataSize());
- assertArrayEquals(src, cln);
- }
-}
\ No newline at end of file
diff --git a/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java b/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java
deleted file mode 100644
index a372d11685..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java
+++ /dev/null
@@ -1,545 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-package org.apache.poi.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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 java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.poi.hpsf.ClassID;
-import org.apache.poi.hpsf.ClassIDPredefined;
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.apache.poi.util.LittleEndianByteArrayInputStream;
-import org.apache.poi.util.LittleEndianByteArrayOutputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test HyperlinkRecord
- */
-final class TestHyperlinkRecord {
-
- //link to http://www.lakings.com/
- private static final byte[] data1 = {
- 0x02, 0x00, //First row of the hyperlink
- 0x02, 0x00, //Last row of the hyperlink
- 0x00, 0x00, //First column of the hyperlink
- 0x00, 0x00, //Last column of the hyperlink
-
- //16-byte GUID. Seems to be always the same. Does not depend on the hyperlink type
- (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
- (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
-
- 0x02, 0x00, 0x00, 0x00, //integer, always 2
-
- // flags. Define the type of the hyperlink:
- // HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL
- 0x17, 0x00, 0x00, 0x00,
-
- 0x08, 0x00, 0x00, 0x00, //length of the label including the trailing '\0'
-
- //label:
- 0x4D, 0x00, 0x79, 0x00, 0x20, 0x00, 0x4C, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x6B, 0x00, 0x00, 0x00,
-
- //16-byte link moniker: HyperlinkRecord.URL_MONIKER
- (byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
- (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
-
- //count of bytes in the address including the tail
- 0x48, 0x00, 0x00, 0x00, //integer
-
- //the actual link, terminated by '\u0000'
- 0x68, 0x00, 0x74, 0x00, 0x74, 0x00, 0x70, 0x00, 0x3A, 0x00, 0x2F, 0x00,
- 0x2F, 0x00, 0x77, 0x00, 0x77, 0x00, 0x77, 0x00, 0x2E, 0x00, 0x6C, 0x00,
- 0x61, 0x00, 0x6B, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x73, 0x00,
- 0x2E, 0x00, 0x63, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x2F, 0x00, 0x00, 0x00,
-
- //standard 24-byte tail of a URL link. Seems to always be the same for all URL HLINKs
- 0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, 0x2C,
- (byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00,
- 0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00
- };
-
- //link to a file in the current directory: link1.xls
- private static final byte[] data2 = {
- 0x00, 0x00,
- 0x00, 0x00,
- 0x00, 0x00,
- 0x00, 0x00,
- //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type
- (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
- (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
-
- 0x02, 0x00, 0x00, 0x00, //integer, always 2
-
- 0x15, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL
-
- 0x05, 0x00, 0x00, 0x00, //length of the label
- //label
- 0x66, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x65, 0x00, 0x00, 0x00,
-
- //16-byte link moniker: HyperlinkRecord.FILE_MONIKER
- 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46,
-
- 0x00, 0x00, //level
- 0x0A, 0x00, 0x00, 0x00, //length of the path )
-
- //path to the file (plain ISO-8859 bytes, NOT UTF-16LE!)
- 0x6C, 0x69, 0x6E, 0x6B, 0x31, 0x2E, 0x78, 0x6C, 0x73, 0x00,
-
- //standard 24-byte tail of a file link
- (byte)0xFF, (byte)0xFF, (byte)0xAD, (byte)0xDE, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
-
- 0x00, 0x00, 0x00, 0x00, // length of address link field
- };
-
- // mailto:ebgans@mail.ru?subject=Hello,%20Ebgans!
- private static final byte[] data3 = {
- 0x01, 0x00,
- 0x01, 0x00,
- 0x00, 0x00,
- 0x00, 0x00,
-
- //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type
- (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
- (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
-
- 0x02, 0x00, 0x00, 0x00, //integer, always 2
-
- 0x17, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL
-
- 0x06, 0x00, 0x00, 0x00, //length of the label
- 0x65, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x00, 0x00, //label
-
- //16-byte link moniker: HyperlinkRecord.URL_MONIKER
- (byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
- (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
-
- //length of the address including the tail.
- 0x76, 0x00, 0x00, 0x00,
-
- //the address is terminated by '\u0000'
- 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x74, 0x00, 0x6F, 0x00,
- 0x3A, 0x00, 0x65, 0x00, 0x62, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6E, 0x00,
- 0x73, 0x00, 0x40, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00,
- 0x2E, 0x00, 0x72, 0x00, 0x75, 0x00, 0x3F, 0x00, 0x73, 0x00, 0x75, 0x00,
- 0x62, 0x00, 0x6A, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x3D, 0x00,
- 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x2C, 0x00,
- 0x25, 0x00, 0x32, 0x00, 0x30, 0x00, 0x45, 0x00, 0x62, 0x00, 0x67, 0x00,
- 0x61, 0x00, 0x6E, 0x00, 0x73, 0x00, 0x21, 0x00, 0x00, 0x00,
-
- //standard 24-byte tail of a URL link
- 0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, (byte)0x2C,
- (byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00,
- 0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00
- };
-
- //link to a place in worksheet: Sheet1!A1
- private static final byte[] data4 = {
- 0x03, 0x00,
- 0x03, 0x00,
- 0x00, 0x00,
- 0x00, 0x00,
-
- //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type
- (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11,
- (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B,
-
- 0x02, 0x00, 0x00, 0x00, //integer, always 2
-
- 0x1C, 0x00, 0x00, 0x00, //flags: HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE
-
- 0x06, 0x00, 0x00, 0x00, //length of the label
-
- 0x70, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x63, 0x00, 0x65, 0x00, 0x00, 0x00, //label
-
- 0x0A, 0x00, 0x00, 0x00, //length of the document link including trailing zero
-
- //link: Sheet1!A1
- 0x53, 0x00, 0x68, 0x00, 0x65, 0x00, 0x65, 0x00, 0x74, 0x00, 0x31, 0x00, 0x21,
- 0x00, 0x41, 0x00, 0x31, 0x00, 0x00, 0x00
- };
-
- private static final byte[] dataLinkToWorkbook = HexRead.readFromString(
- "01 00 01 00 01 00 01 00 " +
- "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
- "02 00 00 00 " +
- "1D 00 00 00 " + // options: LABEL | PLACE | FILE_OR_URL
- // label: "My Label"
- "09 00 00 00 " +
- "4D 00 79 00 20 00 4C 00 61 00 62 00 65 00 6C 00 00 00 " +
- "03 03 00 00 00 00 00 00 C0 00 00 00 00 00 00 46 " + // file GUID
- "00 00 " + // file options
- // shortFileName: "YEARFR~1.XLS"
- "0D 00 00 00 " +
- "59 45 41 52 46 52 7E 31 2E 58 4C 53 00 " +
- // FILE_TAIL - unknown byte sequence
- "FF FF AD DE 00 00 00 00 " +
- "00 00 00 00 00 00 00 00 " +
- "00 00 00 00 00 00 00 00 " +
- // field len, char data len
- "2E 00 00 00 " +
- "28 00 00 00 " +
- "03 00 " + // unknown ushort
- // _address: "yearfracExamples.xls"
- "79 00 65 00 61 00 72 00 66 00 72 00 61 00 63 00 " +
- "45 00 78 00 61 00 6D 00 70 00 6C 00 65 00 73 00 " +
- "2E 00 78 00 6C 00 73 00 " +
- // textMark: "Sheet1!B6"
- "0A 00 00 00 " +
- "53 00 68 00 65 00 65 00 74 00 31 00 21 00 42 00 " +
- "36 00 00 00"
- );
-
- private static final byte[] dataTargetFrame = HexRead.readFromString(
- "0E 00 0E 00 00 00 00 00 " +
- "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
- "02 00 00 00 " +
- "83 00 00 00 " + // options: TARGET_FRAME | ABS | FILE_OR_URL
- // targetFrame: "_blank"
- "07 00 00 00 " +
- "5F 00 62 00 6C 00 61 00 6E 00 6B 00 00 00 " +
- // url GUID
- "E0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
- // address: "http://www.regnow.com/softsell/nph-softsell.cgi?currency=USD&item=7924-37"
- "94 00 00 00 " +
- "68 00 74 00 74 00 70 00 3A 00 2F 00 2F 00 77 00 " +
- "77 00 77 00 2E 00 72 00 65 00 67 00 6E 00 6F 00 " +
- "77 00 2E 00 63 00 6F 00 6D 00 2F 00 73 00 6F 00 " +
- "66 00 74 00 73 00 65 00 6C 00 6C 00 2F 00 6E 00 " +
- "70 00 68 00 2D 00 73 00 6F 00 66 00 74 00 73 00 " +
- "65 00 6C 00 6C 00 2E 00 63 00 67 00 69 00 3F 00 " +
- "63 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 " +
- "3D 00 55 00 53 00 44 00 26 00 69 00 74 00 65 00 " +
- "6D 00 3D 00 37 00 39 00 32 00 34 00 2D 00 33 00 " +
- "37 00 00 00"
- );
-
-
- private static final byte[] dataUNC = HexRead.readFromString(
- "01 00 01 00 01 00 01 00 " +
- "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " +
- "02 00 00 00 " +
- "1F 01 00 00 " + // options: UNC_PATH | LABEL | TEXT_MARK | ABS | FILE_OR_URL
- "09 00 00 00 " + // label: "My Label"
- "4D 00 79 00 20 00 6C 00 61 00 62 00 65 00 6C 00 00 00 " +
- // note - no moniker GUID
- "27 00 00 00 " + // "\\\\MyServer\\my-share\\myDir\\PRODNAME.xls"
- "5C 00 5C 00 4D 00 79 00 53 00 65 00 72 00 76 00 " +
- "65 00 72 00 5C 00 6D 00 79 00 2D 00 73 00 68 00 " +
- "61 00 72 00 65 00 5C 00 6D 00 79 00 44 00 69 00 " +
- "72 00 5C 00 50 00 52 00 4F 00 44 00 4E 00 41 00 " +
- "4D 00 45 00 2E 00 78 00 6C 00 73 00 00 00 " +
-
- "0C 00 00 00 " + // textMark: PRODNAME!C2
- "50 00 52 00 4F 00 44 00 4E 00 41 00 4D 00 45 00 21 00 " +
- "43 00 32 00 00 00"
- );
-
-
- /**
- * From Bugzilla 47498
- */
- private static final byte[] data_47498 = {
- 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xD0, (byte)0xC9,
- (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C,
- (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x02, 0x00,
- 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x50, 0x00,
- 0x44, 0x00, 0x46, 0x00, 0x00, 0x00, (byte)0xE0, (byte)0xC9, (byte)0xEA,
- 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, (byte)0x11, (byte)0x8C, (byte)0x82,
- 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x28, 0x00, 0x00, 0x00,
- 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x66, 0x00, 0x6F, 0x00,
- 0x6C, 0x00, 0x64, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2F, 0x00, 0x74, 0x00,
- 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x2E, 0x00, 0x50, 0x00, 0x44, 0x00,
- 0x46, 0x00, 0x00, 0x00
- };
-
-
- private void confirmGUID(ClassID expectedGuid, ClassID actualGuid) {
- assertEquals(expectedGuid, actualGuid);
- }
-
- @Test
- void testReadURLLink(){
- RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data1);
- HyperlinkRecord link = new HyperlinkRecord(is);
- assertEquals(2, link.getFirstRow());
- assertEquals(2, link.getLastRow());
- assertEquals(0, link.getFirstColumn());
- assertEquals(0, link.getLastColumn());
- confirmGUID(ClassIDPredefined.STD_MONIKER.getClassID(), link.getGuid());
- confirmGUID(ClassIDPredefined.URL_MONIKER.getClassID(), link.getMoniker());
- assertEquals(2, link.getLabelOptions());
- int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL;
- assertEquals(0x17, opts);
- assertEquals(opts, link.getLinkOptions());
- assertEquals(0, link.getFileOptions());
-
- assertEquals("My Link", link.getLabel());
- assertEquals("http://www.lakings.com/", link.getAddress());
- }
-
- @Test
- void testReadFileLink(){
- RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data2);
- HyperlinkRecord link = new HyperlinkRecord(is);
- assertEquals(0, link.getFirstRow());
- assertEquals(0, link.getLastRow());
- assertEquals(0, link.getFirstColumn());
- assertEquals(0, link.getLastColumn());
- confirmGUID(ClassIDPredefined.STD_MONIKER.getClassID(), link.getGuid());
- confirmGUID(ClassIDPredefined.FILE_MONIKER.getClassID(), link.getMoniker());
- assertEquals(2, link.getLabelOptions());
- int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL;
- assertEquals(0x15, opts);
- assertEquals(opts, link.getLinkOptions());
-
- assertEquals("file", link.getLabel());
- assertEquals("link1.xls", link.getShortFilename());
- assertEquals("link1.xls", link.getAddress());
- }
-
- @Test
- void testReadEmailLink(){
- RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data3);
- HyperlinkRecord link = new HyperlinkRecord(is);
- assertEquals(1, link.getFirstRow());
- assertEquals(1, link.getLastRow());
- assertEquals(0, link.getFirstColumn());
- assertEquals(0, link.getLastColumn());
- confirmGUID(ClassIDPredefined.STD_MONIKER.getClassID(), link.getGuid());
- confirmGUID(ClassIDPredefined.URL_MONIKER.getClassID(), link.getMoniker());
- assertEquals(2, link.getLabelOptions());
- int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL;
- assertEquals(0x17, opts);
- assertEquals(opts, link.getLinkOptions());
-
- assertEquals("email", link.getLabel());
- assertEquals("mailto:ebgans@mail.ru?subject=Hello,%20Ebgans!", link.getAddress());
- }
-
- @Test
- void testReadDocumentLink(){
- RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data4);
- HyperlinkRecord link = new HyperlinkRecord(is);
- assertEquals(3, link.getFirstRow());
- assertEquals(3, link.getLastRow());
- assertEquals(0, link.getFirstColumn());
- assertEquals(0, link.getLastColumn());
- confirmGUID(ClassIDPredefined.STD_MONIKER.getClassID(), link.getGuid());
- assertEquals(2, link.getLabelOptions());
- int opts = HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE;
- assertEquals(0x1C, opts);
- assertEquals(opts, link.getLinkOptions());
-
- assertEquals("place", link.getLabel());
- assertEquals("Sheet1!A1", link.getTextMark());
- assertEquals("Sheet1!A1", link.getAddress());
- }
-
- private void serialize(byte[] data){
- RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data);
- HyperlinkRecord link = new HyperlinkRecord(is);
- byte[] bytes1 = link.serialize();
- is = TestcaseRecordInputStream.create(bytes1);
- link = new HyperlinkRecord(is);
- byte[] bytes2 = link.serialize();
- assertEquals(bytes1.length, bytes2.length);
- assertArrayEquals(bytes1, bytes2);
- }
-
- @Test
- void testSerialize(){
- serialize(data1);
- serialize(data2);
- serialize(data3);
- serialize(data4);
- }
-
- @Test
- void testCreateURLRecord() {
- HyperlinkRecord link = new HyperlinkRecord();
- link.newUrlLink();
- link.setFirstRow((short)2);
- link.setLastRow((short)2);
- link.setLabel("My Link");
- link.setAddress("http://www.lakings.com/");
-
- byte[] tmp = link.serialize();
- byte[] ser = Arrays.copyOfRange(tmp, 4, tmp.length);
- assertEquals(data1.length, ser.length);
- assertArrayEquals(data1, ser);
- }
-
- @Test
- void testCreateFileRecord() {
- HyperlinkRecord link = new HyperlinkRecord();
- link.newFileLink();
- link.setFirstRow((short)0);
- link.setLastRow((short)0);
- link.setLabel("file");
- link.setShortFilename("link1.xls");
-
- byte[] tmp = link.serialize();
- byte[] ser = Arrays.copyOfRange(tmp, 4, tmp.length);
- assertEquals(data2.length, ser.length);
- assertArrayEquals(data2, ser);
- }
-
- @Test
- void testCreateDocumentRecord() {
- HyperlinkRecord link = new HyperlinkRecord();
- link.newDocumentLink();
- link.setFirstRow((short)3);
- link.setLastRow((short)3);
- link.setLabel("place");
- link.setTextMark("Sheet1!A1");
-
- byte[] tmp = link.serialize();
- byte[] ser = Arrays.copyOfRange(tmp, 4, tmp.length);
- assertEquals(data4.length, ser.length);
- assertArrayEquals(data4, ser);
- }
-
- @Test
- void testCreateEmailtRecord() {
- HyperlinkRecord link = new HyperlinkRecord();
- link.newUrlLink();
- link.setFirstRow((short)1);
- link.setLastRow((short)1);
- link.setLabel("email");
- link.setAddress("mailto:ebgans@mail.ru?subject=Hello,%20Ebgans!");
-
- byte[] tmp = link.serialize();
- byte[] ser = Arrays.copyOfRange(tmp, 4, tmp.length);
- assertEquals(data3.length, ser.length);
- assertArrayEquals(data3, ser);
- }
-
- @Test
- void testClone() {
- byte[][] data = {data1, data2, data3, data4};
- for (final byte[] d : data) {
- RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, d);
- HyperlinkRecord link = new HyperlinkRecord(is);
- HyperlinkRecord clone = link.copy();
- assertArrayEquals(link.serialize(), clone.serialize());
- }
-
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testReserializeTargetFrame() {
- RecordInputStream in = TestcaseRecordInputStream.create(HyperlinkRecord.sid, dataTargetFrame);
- HyperlinkRecord hr = new HyperlinkRecord(in);
- byte[] ser = hr.serialize();
- confirmRecordEncoding(HyperlinkRecord.sid, dataTargetFrame, ser);
- }
-
- @Test
- void testReserializeLinkToWorkbook() {
-
- RecordInputStream in = TestcaseRecordInputStream.create(HyperlinkRecord.sid, dataLinkToWorkbook);
- HyperlinkRecord hr = new HyperlinkRecord(in);
- byte[] ser = hr.serialize();
- confirmRecordEncoding(HyperlinkRecord.sid, dataLinkToWorkbook, ser);
- assertNotEquals("Identified bug in reading workbook link", "YEARFR~1.XLS", hr.getAddress());
- assertEquals("yearfracExamples.xls", hr.getAddress());
- }
-
- @Test
- void testReserializeUNC() {
-
- RecordInputStream in = TestcaseRecordInputStream.create(HyperlinkRecord.sid, dataUNC);
- HyperlinkRecord hr = new HyperlinkRecord(in);
- byte[] ser = hr.serialize();
- confirmRecordEncoding(HyperlinkRecord.sid, dataUNC, ser);
- assertNotNull(hr.toString());
- }
-
- @Test
- void testGUID() throws IOException {
- ClassID g;
- g = new ClassID("3F2504E0-4F89-11D3-9A0C-0305E82C3301");
- confirmGUID(g, 0x3F2504E0, 0x4F89, 0x11D3, 0x9A0C0305E82C3301L);
- assertEquals("{3F2504E0-4F89-11D3-9A0C-0305E82C3301}", g.toString());
-
- g = new ClassID("13579BDF-0246-8ACE-0123-456789ABCDEF");
- confirmGUID(g, 0x13579BDF, 0x0246, 0x8ACE, 0x0123456789ABCDEFL);
- assertEquals("{13579BDF-0246-8ACE-0123-456789ABCDEF}", g.toString());
-
- byte[] buf = new byte[16];
- g.write(new LittleEndianByteArrayOutputStream(buf, 0));
- String expectedDump = "[DF, 9B, 57, 13, 46, 02, CE, 8A, 01, 23, 45, 67, 89, AB, CD, EF]";
- assertEquals(expectedDump, HexDump.toHex(buf));
-
- // STD Moniker
- g = createFromStreamDump("[D0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]");
- assertEquals("{79EAC9D0-BAF9-11CE-8C82-00AA004BA90B}", g.toString());
- // URL Moniker
- g = createFromStreamDump("[E0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]");
- assertEquals("{79EAC9E0-BAF9-11CE-8C82-00AA004BA90B}", g.toString());
- // File Moniker
- g = createFromStreamDump("[03, 03, 00, 00, 00, 00, 00, 00, C0, 00, 00, 00, 00, 00, 00, 46]");
- assertEquals("{00000303-0000-0000-C000-000000000046}", g.toString());
- }
-
- private static ClassID createFromStreamDump(String s) {
- return new ClassID(new LittleEndianByteArrayInputStream(HexRead.readFromString(s)));
- }
-
- private void confirmGUID(ClassID g, int d1, int d2, int d3, long d4) throws IOException {
- try (DataInputStream dis = new DataInputStream(new ByteArrayInputStream(g.getBytes()))) {
- assertEquals(d1, dis.readInt());
- assertEquals(d2, dis.readShort() & 0xFFFF);
- assertEquals(d3, dis.readShort() & 0xFFFF);
- assertEquals(d4, dis.readLong());
- }
- }
-
- @Test
- void test47498(){
- RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data_47498);
- HyperlinkRecord link = new HyperlinkRecord(is);
- assertEquals(2, link.getFirstRow());
- assertEquals(2, link.getLastRow());
- assertEquals(0, link.getFirstColumn());
- assertEquals(0, link.getLastColumn());
- confirmGUID(ClassIDPredefined.STD_MONIKER.getClassID(), link.getGuid());
- confirmGUID(ClassIDPredefined.URL_MONIKER.getClassID(), link.getMoniker());
- assertEquals(2, link.getLabelOptions());
- int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL;
- assertEquals(opts, link.getLinkOptions());
- assertEquals(0, link.getFileOptions());
-
- assertEquals("PDF", link.getLabel());
- assertEquals("testfolder/test.PDF", link.getAddress());
-
- byte[] ser = link.serialize();
- confirmRecordEncoding(HyperlinkRecord.sid, data_47498, ser);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java b/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java
deleted file mode 100644
index 169efaf2ad..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.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.hssf.record;
-
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.ByteArrayInputStream;
-import java.util.List;
-
-import org.apache.poi.util.HexDump;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the EndSubRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestInterfaceEndRecord {
-
- @Test
- void testCreate() {
- InterfaceEndRecord record = InterfaceEndRecord.instance;
- assertEquals(0, record.getDataSize());
- }
-
- /**
- * Silently swallow unexpected contents in InterfaceEndRecord.
- * Although it violates the spec, Excel silently converts this
- * data to an {@link InterfaceHdrRecord}.
- */
- @Test
- void testUnexpectedBytes_bug47251(){
- String hex = "" +
- "09 08 10 00 00 06 05 00 EC 15 CD 07 C1 C0 00 00 06 03 00 00 " + //BOF
- "E2 00 02 00 B0 04 " + //INTERFACEEND with extra two bytes
- "0A 00 00 00"; // EOF
- byte[] data = HexRead.readFromString(hex);
- List records = RecordFactory.createRecords(new ByteArrayInputStream(data));
- assertEquals(3, records.size());
- Record rec1 = records.get(1);
- assertEquals(InterfaceHdrRecord.class, rec1.getClass());
- InterfaceHdrRecord r = (InterfaceHdrRecord)rec1;
- assertEquals("[E1, 00, 02, 00, B0, 04]", HexDump.toHex(r.serialize()));
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java b/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java
deleted file mode 100644
index 84946bd6b2..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.IOException;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for LabelRecord
- */
-final class TestLabelRecord {
-
- @Test
- void testEmptyString() throws IOException {
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("ex42570-20305.xls");
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
- HSSFSheet s1 = wb1.getSheetAt(0);
- HSSFSheet s2 = wb2.getSheetAt(0);
- for (int c=0; c<2; c++) {
- for (int r=0; r<146; r++) {
- assertEquals(s1.getRow(r).getCell(c).getNumericCellValue(), s2.getRow(r).getCell(c).getNumericCellValue(), 0);
- }
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java
deleted file mode 100644
index afd988fb37..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.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.hssf.record;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-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.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
-import org.apache.poi.ss.formula.ptg.AreaPtg;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.apache.poi.util.HexRead;
-import org.apache.poi.util.LittleEndianInputStream;
-import org.apache.poi.util.LittleEndianOutputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the LbsDataSubRecord class works correctly.
- */
-final class TestLbsDataSubRecord {
-
- /**
- * test read-write round trip
- * test data was taken from 47701.xls
- */
- @Test
- void test_47701(){
- byte[] data = HexRead.readFromString(
- "15, 00, 12, 00, 12, 00, 02, 00, 11, 20, " +
- "00, 00, 00, 00, 80, 3D, 03, 05, 00, 00, " +
- "00, 00, 0C, 00, 14, 00, 00, 00, 00, 00, " +
- "00, 00, 00, 00, 00, 00, 01, 00, 0A, 00, " +
- "00, 00, 10, 00, 01, 00, 13, 00, EE, 1F, " +
- "10, 00, 09, 00, 40, 9F, 74, 01, 25, 09, " +
- "00, 0C, 00, 07, 00, 07, 00, 07, 04, 00, " +
- "00, 00, 08, 00, 00, 00");
- RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, data);
- // check read OK
- ObjRecord record = new ObjRecord(in);
- assertEquals(3, record.getSubRecords().size());
- SubRecord sr = record.getSubRecords().get(2);
- assertTrue(sr instanceof LbsDataSubRecord);
- LbsDataSubRecord lbs = (LbsDataSubRecord)sr;
- assertEquals(4, lbs.getNumberOfItems());
-
- assertTrue(lbs.getFormula() instanceof AreaPtg);
- AreaPtg ptg = (AreaPtg)lbs.getFormula();
- CellRangeAddress range = new CellRangeAddress(
- ptg.getFirstRow(), ptg.getLastRow(), ptg.getFirstColumn(), ptg.getLastColumn());
- assertEquals("H10:H13", range.formatAsString());
-
- // check that it re-serializes to the same data
- byte[] ser = record.serialize();
- confirmRecordEncoding(ObjRecord.sid, data, ser);
- }
-
- /**
- * test data was taken from the file attached to Bugzilla 45778
- */
- @Test
- void test_45778(){
- byte[] data = HexRead.readFromString(
- "15, 00, 12, 00, 14, 00, 01, 00, 01, 00, " +
- "01, 21, 00, 00, 3C, 13, F4, 03, 00, 00, " +
- "00, 00, 0C, 00, 14, 00, 00, 00, 00, 00, " +
- "00, 00, 00, 00, 00, 00, 01, 00, 08, 00, 00, " +
- "00, 10, 00, 00, 00, " +
- "13, 00, EE, 1F, " +
- "00, 00, " +
- "08, 00, " + //number of items
- "08, 00, " + //selected item
- "01, 03, " + //flags
- "00, 00, " + //objId
- //LbsDropData
- "0A, 00, " + //flags
- "14, 00, " + //the number of lines to be displayed in the dropdown
- "6C, 00, " + //the smallest width in pixels allowed for the dropdown window
- "00, 00, " + //num chars
- "00, 00");
- RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, data);
- // check read OK
- ObjRecord record = new ObjRecord(in);
-
- SubRecord sr = record.getSubRecords().get(2);
- assertTrue(sr instanceof LbsDataSubRecord);
- LbsDataSubRecord lbs = (LbsDataSubRecord)sr;
- assertEquals(8, lbs.getNumberOfItems());
- assertNull(lbs.getFormula());
-
- // check that it re-serializes to the same data
- byte[] ser = record.serialize();
- confirmRecordEncoding(ObjRecord.sid, data, ser);
-
- }
-
- /**
- * Test data produced by OpenOffice 3.1 by opening and saving 47701.xls
- * There are 5 padding bytes that are removed by POI
- */
- @Test
- void test_remove_padding(){
- byte[] data = HexRead.readFromString(
- "5D, 00, 4C, 00, " +
- "15, 00, 12, 00, 12, 00, 01, 00, 11, 00, " +
- "00, 00, 00, 00, 00, 00, 00, 00, 00, 00, " +
- "00, 00, 0C, 00, 14, 00, 00, 00, 00, 00, " +
- "00, 00, 00, 00, 00, 00, 01, 00, 09, 00, " +
- "00, 00, 0F, 00, 01, 00, " +
- "13, 00, 1B, 00, " +
- "10, 00, " + //next 16 bytes is a ptg aray
- "09, 00, 00, 00, 00, 00, 25, 09, 00, 0C, 00, 07, 00, 07, 00, 00, " +
- "01, 00, " + //num lines
- "00, 00, " + //selected
- "08, 00, " +
- "00, 00, " +
- "00, 00, 00, 00, 00"); //padding bytes
-
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- // check read OK
- ObjRecord record = new ObjRecord(in);
- // check that it re-serializes to the same data
- byte[] ser = record.serialize();
-
- assertEquals(data.length-5, ser.length);
- for(int i=0; i < ser.length; i++) assertEquals(data[i],ser[i]);
-
- //check we can read the trimmed record
- RecordInputStream in2 = TestcaseRecordInputStream.create(ser);
- ObjRecord record2 = new ObjRecord(in2);
- byte[] ser2 = record2.serialize();
- assertArrayEquals(ser, ser2);
- }
-
- @Test
- void test_LbsDropData() throws IOException{
- byte[] data = HexRead.readFromString(
- //LbsDropData
- "0A, 00, " + //flags
- "14, 00, " + //the number of lines to be displayed in the dropdown
- "6C, 00, " + //the smallest width in pixels allowed for the dropdown window
- "00, 00, " + //num chars
- "00, " + //compression flag
- "00"); //padding byte
-
- try (LittleEndianInputStream in = new LittleEndianInputStream(new ByteArrayInputStream(data))) {
- LbsDataSubRecord.LbsDropData lbs = new LbsDataSubRecord.LbsDropData(in);
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- try (LittleEndianOutputStream out = new LittleEndianOutputStream(baos)) {
- lbs.serialize(out);
-
- assertArrayEquals(data, baos.toByteArray());
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java b/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java
deleted file mode 100644
index 7e9e1da0d0..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.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.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotSame;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.Collections;
-
-import org.apache.poi.hssf.model.RecordStream;
-import org.apache.poi.hssf.record.aggregates.MergedCellsTable;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.junit.jupiter.api.Test;
-
-
-/**
- * Make sure the merge cells record behaves
- */
-final class TestMergeCellsRecord {
-
- /**
- * Make sure when a clone is called, we actually clone it.
- */
- @Test
- void testCloneReferences() {
- CellRangeAddress[] cras = { new CellRangeAddress(0, 1, 0, 2), };
- MergeCellsRecord merge = new MergeCellsRecord(cras, 0, cras.length);
- MergeCellsRecord clone = merge.copy();
-
- assertNotSame(merge, clone, "Merged and cloned objects are the same");
-
- CellRangeAddress mergeRegion = merge.getAreaAt(0);
- CellRangeAddress cloneRegion = clone.getAreaAt(0);
- assertNotSame(mergeRegion, cloneRegion, "Should not point to same objects when cloning");
- assertEquals(mergeRegion.getFirstRow(), cloneRegion.getFirstRow(), "New Clone Row From doesnt match");
- assertEquals(mergeRegion.getLastRow(), cloneRegion.getLastRow(), "New Clone Row To doesnt match");
- assertEquals(mergeRegion.getFirstColumn(), cloneRegion.getFirstColumn(), "New Clone Col From doesnt match");
- assertEquals(mergeRegion.getLastColumn(), cloneRegion.getLastColumn(), "New Clone Col To doesnt match");
-
- assertNotSame(merge.getAreaAt(0), clone.getAreaAt(0));
- }
-
- @Test
- void testMCTable_bug46009() {
- MergedCellsTable mct = new MergedCellsTable();
- CellRangeAddress[] cras = { new CellRangeAddress(0, 0, 0, 3) };
- MergeCellsRecord mcr1 = new MergeCellsRecord(cras, 0, 1);
- RecordStream rs = new RecordStream(Collections.singletonList(mcr1), 0);
- mct.read(rs);
- mct.visitContainedRecords(r -> {
- assertTrue(r instanceof MergeCellsRecord);
- MergeCellsRecord mcr2 = (MergeCellsRecord)r;
- assertEquals(mcr1.getNumAreas(), mcr2.getNumAreas());
- assertEquals(mcr1.getAreaAt(0), mcr2.getAreaAt(0));
- });
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java
deleted file mode 100644
index 9884379747..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.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.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the NameCommentRecord serializes/deserializes correctly
- */
-final class TestNameCommentRecord {
- @Test
- void testReserialize() {
- final byte[] data = HexRead
- .readFromString(""
- + "94 08 00 00 00 00 00 00 00 00 00 00 04 00 07 00 00 6E 61 6D 65 00 63 6F 6D 6D 65 6E 74]");
- final RecordInputStream in = TestcaseRecordInputStream.create(NameCommentRecord.sid, data);
- final NameCommentRecord ncr = new NameCommentRecord(in);
- assertEquals(0x0894, ncr.getRecordType());
- assertEquals("name", ncr.getNameText());
- assertEquals("comment", ncr.getCommentText());
- final byte[] data2 = ncr.serialize();
- confirmRecordEncoding(NameCommentRecord.sid, data, data2);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java
deleted file mode 100644
index 12da160752..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestNameRecord.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.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.assertTrue;
-
-import java.io.IOException;
-
-import org.apache.poi.hssf.usermodel.HSSFName;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.apache.poi.ss.formula.ptg.Area3DPtg;
-import org.apache.poi.ss.formula.ptg.ArrayPtg;
-import org.apache.poi.ss.formula.ptg.NamePtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.formula.ptg.Ref3DPtg;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the NameRecord serializes/deserializes correctly
- */
-final class TestNameRecord {
-
- /**
- * Makes sure that additional name information is parsed properly such as menu/description
- */
- @Test
- void testFillExtras() {
-
- byte[] examples = HexRead.readFromString(""
- + "88 03 67 06 07 00 00 00 00 00 00 23 00 00 00 4D "
- + "61 63 72 6F 31 3A 01 00 00 00 11 00 00 4D 61 63 "
- + "72 6F 20 72 65 63 6F 72 64 65 64 20 32 37 2D 53 "
- + "65 70 2D 39 33 20 62 79 20 41 4C 4C 57 4F 52");
-
- NameRecord name = new NameRecord(TestcaseRecordInputStream.create(NameRecord.sid, examples));
- String description = name.getDescriptionText();
- assertNotNull(description);
- assertTrue(description.endsWith("Macro recorded 27-Sep-93 by ALLWOR"));
- }
-
- @Test
- void testReserialize() {
- byte[] data = HexRead
- .readFromString(""
- + "20 00 00 01 0B 00 00 00 01 00 00 00 00 00 00 06 3B 00 00 00 00 02 00 00 00 09 00]");
- RecordInputStream in = TestcaseRecordInputStream.create(NameRecord.sid, data);
- NameRecord nr = new NameRecord(in);
- assertEquals(0x0020, nr.getOptionFlag());
- byte[] data2 = nr.serialize();
- confirmRecordEncoding(NameRecord.sid, data, data2);
- }
-
- @Test
- void testFormulaRelAbs_bug46174() throws IOException {
- // perhaps this testcase belongs on TestHSSFName
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFName name = wb.createName();
- wb.createSheet("Sheet1");
- name.setNameName("test");
- name.setRefersToFormula("Sheet1!$B$3");
- assertNotEquals("Sheet1!B3", name.getRefersToFormula());
- assertEquals("Sheet1!$B$3", name.getRefersToFormula());
- }
- }
-
- @Test
- void testFormulaGeneral() throws IOException {
- // perhaps this testcase belongs on TestHSSFName
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFName name = wb.createName();
- wb.createSheet("Sheet1");
- name.setNameName("test");
- name.setRefersToFormula("Sheet1!A1+Sheet1!A2");
- assertEquals("Sheet1!A1+Sheet1!A2", name.getRefersToFormula());
- name.setRefersToFormula("5*6");
- assertEquals("5*6", name.getRefersToFormula());
-
- wb.close();
- }
-
- /**
- * A NameRecord followed by a ContinueRecord. See Bugzilla 50244
- */
- @Test
- void test50244() throws IOException {
- byte[] data1 = RawDataUtil.decompress(
- "H4sIAAAAAAAAAI3Zu2qWQRAA0I8EQcHGzkrwBcLO7B0sBR9AwdYIKdKFoPhovp7xLyQWyX+m2OWw7TIX5u3x/t1xHG9ePhyXxyl+" +
- "fbz+cf3p/ufd3c3nm/vbm6tvx++L18fXy4fr4tVxxNWXLFelhCENlRCIZuiERAzDJFTEMmxCM/RiCMJApKESJqIZOmEhhmESNmIZ" +
- "tiCKIYohCIlIQyVURDN0QkMMwyR0xDJswjDMYoizGH9Lzib8+6NnEIREpKESKqIZOqEhhmESOmIZNmEUQje0bViEipiGQUhENzRC" +
- "IKohCQURZ3FKT0kYiDAUQjc87iCfwyJUxDQMQiK6oRECUQ1JKIgwFEHZhrUNizAR0zAIA9ENjdAR1ZCEhghDIVRDbsMiBGIaBqEg" +
- "uqEZpmEZNiEMWQxBqIg0VEJDNEMndMQwTMJALMMmTMMqhiBsRBqqIAqiGTohEMMwCYlYhk2ohlYMQeiINFTCQDRDP4vT/FMNzdAJ" +
- "gRiGSUjEMmxCNbRiCEJHpKEahqEbGqEhqiEJFRGGQkhDbMMiFMQ0jLM4padlmIZB6IhuaIT2Pz4c3188+VoNSaiIMBRCGh7PGc9h" +
- "EQpiGoagbEQ3NMJCVEMSJiIMhTAMjxdcz2ERGmIaBqEiuqERElENSQhEGMrT+APX2vm3iyMAAA=="
- );
-
- RecordInputStream in1 = TestcaseRecordInputStream.create(data1);
- NameRecord nr1 = new NameRecord(in1);
- assert_bug50244(nr1);
-
- byte[] data2 = nr1.serialize();
-
- assertEquals(data1.length, data2.length);
- RecordInputStream in2 = TestcaseRecordInputStream.create(data2);
- NameRecord nr2 = new NameRecord(in2);
- assert_bug50244(nr2);
- }
-
- private void assert_bug50244(NameRecord nr){
- assertEquals("wDataGruppeSerie.", nr.getNameText());
- Ptg[] ptg = nr.getNameDefinition();
- assertEquals(1, ptg.length);
- ArrayPtg arr = (ArrayPtg)ptg[0];
- assertEquals(696, arr.getRowCount());
- assertEquals(1, arr.getColumnCount());
- Object[][] vals = arr.getTokenArrayValues();
- assertEquals("1.T20.001", vals[0][0]);
- assertEquals("1.T20.010", vals[vals.length - 1][0]);
- }
-
- @Test
- void testBug57923() {
- NameRecord record = new NameRecord();
- assertEquals(0, record.getExternSheetNumber());
-
- record.setNameDefinition(Ptg.EMPTY_PTG_ARRAY);
- assertEquals(0, record.getExternSheetNumber());
-
- record.setNameDefinition(new Ptg[] {new NamePtg(1)});
- assertEquals(0, record.getExternSheetNumber());
-
- record.setNameDefinition(new Ptg[] {new Area3DPtg("area", 1)});
- assertEquals(1, record.getExternSheetNumber());
-
- record.setNameDefinition(new Ptg[] {new Ref3DPtg("A1", 1)});
- assertEquals(1, record.getExternSheetNumber());
- }
-
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java
deleted file mode 100644
index b59541da10..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.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.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.assertTrue;
-
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the NoteRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestNoteRecord {
- private final byte[] testData = HexRead.readFromString(
- "06 00 01 00 02 00 02 04 " +
- "1A 00 00 " +
- "41 70 61 63 68 65 20 53 6F 66 74 77 61 72 65 20 46 6F 75 6E 64 61 74 69 6F 6E " +
- "00" // padding byte
- );
-
- @Test
- void testRead() {
-
- NoteRecord record = new NoteRecord(TestcaseRecordInputStream.create(NoteRecord.sid, testData));
-
- assertEquals(NoteRecord.sid, record.getSid());
- assertEquals(6, record.getRow());
- assertEquals(1, record.getColumn());
- assertEquals(NoteRecord.NOTE_VISIBLE, record.getFlags());
- assertEquals(1026, record.getShapeId());
- assertEquals("Apache Software Foundation", record.getAuthor());
- }
-
- @Test
- void testWrite() {
- NoteRecord record = new NoteRecord();
- assertEquals(NoteRecord.sid, record.getSid());
-
- record.setRow((short)6);
- record.setColumn((short)1);
- record.setFlags(NoteRecord.NOTE_VISIBLE);
- record.setShapeId((short)1026);
- record.setAuthor("Apache Software Foundation");
-
- byte[] ser = record.serialize();
- confirmRecordEncoding(NoteRecord.sid, testData, ser);
- }
-
- @Test
- void testClone() {
- NoteRecord record = new NoteRecord();
-
- record.setRow((short)1);
- record.setColumn((short)2);
- record.setFlags(NoteRecord.NOTE_VISIBLE);
- record.setShapeId((short)1026);
- record.setAuthor("Apache Software Foundation");
-
- NoteRecord cloned = record.copy();
- assertEquals(record.getRow(), cloned.getRow());
- assertEquals(record.getColumn(), cloned.getColumn());
- assertEquals(record.getFlags(), cloned.getFlags());
- assertEquals(record.getShapeId(), cloned.getShapeId());
- assertEquals(record.getAuthor(), cloned.getAuthor());
-
- //finally check that the serialized data is the same
- byte[] src = record.serialize();
- byte[] cln = cloned.serialize();
- assertArrayEquals(src, cln);
- }
-
- @Test
- void testUnicodeAuthor() {
- // This sample data was created by setting the 'user name' field in the 'Personalize'
- // section of Excel's options to \u30A2\u30D1\u30C3\u30C1\u65CF, and then
- // creating a cell comment.
- byte[] data = HexRead.readFromString("01 00 01 00 00 00 03 00 " +
- "05 00 01 " + // len=5, 16bit
- "A2 30 D1 30 C3 30 C1 30 CF 65 " + // character data
- "00 " // padding byte
- );
- RecordInputStream in = TestcaseRecordInputStream.create(NoteRecord.sid, data);
- NoteRecord nr = new NoteRecord(in);
- assertNotEquals("Identified bug in reading note with unicode author","\u00A2\u0030\u00D1\u0030\u00C3", nr.getAuthor());
- assertEquals("\u30A2\u30D1\u30C3\u30C1\u65CF", nr.getAuthor());
- assertTrue(nr.authorIsMultibyte());
-
- byte[] ser = nr.serialize();
- confirmRecordEncoding(NoteRecord.sid, data, ser);
-
- // Re-check
- in = TestcaseRecordInputStream.create(ser);
- nr = new NoteRecord(in);
- assertEquals("\u30A2\u30D1\u30C3\u30C1\u65CF", nr.getAuthor());
- assertTrue(nr.authorIsMultibyte());
-
-
- // Change to a non unicode author, will stop being unicode
- nr.setAuthor("Simple");
- ser = nr.serialize();
- in = TestcaseRecordInputStream.create(ser);
- nr = new NoteRecord(in);
-
- assertEquals("Simple", nr.getAuthor());
- assertFalse(nr.authorIsMultibyte());
-
- // Now set it back again
- nr.setAuthor("Unicode\u1234");
- ser = nr.serialize();
- in = TestcaseRecordInputStream.create(ser);
- nr = new NoteRecord(in);
-
- assertEquals("Unicode\u1234", nr.getAuthor());
- assertTrue(nr.authorIsMultibyte());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java
deleted file mode 100644
index 9aa690b79f..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.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.hssf.record;
-
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the NoteRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestNoteStructureSubRecord {
- private final byte[] data = new byte[] {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0x80, 0x00, 0x00, 0x00,
- 0x00, 0x00, (byte)0xBF, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0x81, 0x01,
- (byte)0xCC, (byte)0xEC
- };
-
- @Test
- void testRead() {
- NoteStructureSubRecord record = new NoteStructureSubRecord(TestcaseRecordInputStream.create(NoteStructureSubRecord.sid, data), data.length);
-
- assertEquals(NoteStructureSubRecord.sid, record.getSid());
- assertEquals(data.length, record.getDataSize());
- }
-
- @Test
- void testWrite() {
- NoteStructureSubRecord record = new NoteStructureSubRecord();
- assertEquals(NoteStructureSubRecord.sid, record.getSid());
- assertEquals(data.length, record.getDataSize());
-
- byte [] ser = record.serialize();
- assertEquals(ser.length - 4, data.length);
- }
-
- @Test
- void testClone() {
- NoteStructureSubRecord record = new NoteStructureSubRecord();
- byte[] src = record.serialize();
-
- NoteStructureSubRecord cloned = record.copy();
- byte[] cln = cloned.serialize();
-
- assertEquals(record.getDataSize(), cloned.getDataSize());
- assertArrayEquals(src, cln);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java b/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java
deleted file mode 100644
index f797358de9..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestObjRecord.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.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.assertTrue;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the ObjRecord class works correctly.
- * Test data taken directly from a real Excel file.
- */
-final class TestObjRecord {
- /**
- * OBJ record data containing two sub-records.
- * The data taken directly from a real Excel file.
- *
- * [OBJ]
- * [ftCmo]
- * [ftEnd]
- */
- private static final byte[] recdata = HexRead.readFromString(""
- + "15 00 12 00 06 00 01 00 11 60 "
- + "F4 02 41 01 14 10 1F 02 00 00 "
- +"00 00 00 00 00 00"
- // TODO - this data seems to require two extra bytes padding. not sure where original file is.
- // it's not bug 38607 attachment 17639
- );
-
- /**
- * Hex dump from
- * offset 0x2072 in att 22076 of bug 45133
- */
- private static final byte[] recdataNeedingPadding = HexRead.readFromString(""
- + "5D 00 20 00"
- + "15 00 12 00 00 00 01 00 11 60 00 00 00 00 38 6F CC 03 00 00 00 00 06 00 02 00 00 00 00 00 00 00"
- );
-
- @Test
- void testLoad() {
- ObjRecord record = new ObjRecord(TestcaseRecordInputStream.create(ObjRecord.sid, recdata));
-
- assertEquals(26, record.getRecordSize() - 4);
-
- List subrecords = record.getSubRecords();
- assertEquals(2, subrecords.size() );
- assertTrue(subrecords.get(0) instanceof CommonObjectDataSubRecord);
- assertTrue(subrecords.get(1) instanceof EndSubRecord );
-
- }
-
- @Test
- void testStore() {
- ObjRecord record = new ObjRecord(TestcaseRecordInputStream.create(ObjRecord.sid, recdata));
-
- byte [] recordBytes = record.serialize();
- assertEquals(26, recordBytes.length - 4);
- byte[] subData = Arrays.copyOfRange(recordBytes, 4, 4+recdata.length);
- assertArrayEquals(recdata, subData);
- }
-
- @Test
- void testConstruct() {
- ObjRecord record = new ObjRecord();
- CommonObjectDataSubRecord ftCmo = new CommonObjectDataSubRecord();
- ftCmo.setObjectType( CommonObjectDataSubRecord.OBJECT_TYPE_COMMENT);
- ftCmo.setObjectId( 1024 );
- ftCmo.setLocked( true );
- ftCmo.setPrintable( true );
- ftCmo.setAutofill( true );
- ftCmo.setAutoline( true );
- record.addSubRecord(ftCmo);
- EndSubRecord ftEnd = new EndSubRecord();
- record.addSubRecord(ftEnd);
-
- //serialize and read again
- byte [] recordBytes = record.serialize();
- //cut off the record header
- byte [] bytes = Arrays.copyOfRange(recordBytes, 4, recordBytes.length);
-
- record = new ObjRecord(TestcaseRecordInputStream.create(ObjRecord.sid, bytes));
- List subrecords = record.getSubRecords();
- assertEquals( 2, subrecords.size() );
- assertTrue( subrecords.get(0) instanceof CommonObjectDataSubRecord);
- assertTrue( subrecords.get(1) instanceof EndSubRecord );
- }
-
- @Test
- void testReadWriteWithPadding_bug45133() {
- ObjRecord record = new ObjRecord(TestcaseRecordInputStream.create(recdataNeedingPadding));
- assertNotEquals(34, record.getRecordSize(), "Identified bug 45133");
- assertEquals(36, record.getRecordSize());
-
- List subrecords = record.getSubRecords();
- assertEquals(3, subrecords.size() );
- assertEquals(CommonObjectDataSubRecord.class, subrecords.get(0).getClass());
- assertEquals(GroupMarkerSubRecord.class, subrecords.get(1).getClass());
- assertEquals(EndSubRecord.class, subrecords.get(2).getClass());
- }
-
- /**
- * Check that ObjRecord tolerates and preserves padding to a 4-byte boundary
- * (normally padding is to a 2-byte boundary).
- */
- @SuppressWarnings("squid:S2699")
- @Test
- void test4BytePadding() {
- // actual data from file saved by Excel 2007
- byte[] data = HexRead.readFromString(""
- + "15 00 12 00 1E 00 01 00 11 60 B4 6D 3C 01 C4 06 "
- + "49 06 00 00 00 00 00 00 00 00 00 00");
- // this data seems to have 2 extra bytes of padding more than usual
- // the total may have been padded to the nearest quad-byte length
- RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, data);
- // check read OK
- ObjRecord record = new ObjRecord(in);
- // check that it re-serializes to the same data
- byte[] ser = record.serialize();
- confirmRecordEncoding(ObjRecord.sid, data, ser);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java b/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java
deleted file mode 100644
index 55fc393bde..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.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.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-
-import java.io.InputStream;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.usermodel.DVConstraint;
-import org.apache.poi.hssf.usermodel.HSSFDataValidation;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.ss.usermodel.DataValidationConstraint;
-import org.apache.poi.ss.util.CellRangeAddressList;
-import org.junit.jupiter.api.Test;
-
-/**
- * Verify that presence of PLV record doesn't break data
- * validation, bug #53972:
- * https://issues.apache.org/bugzilla/show_bug.cgi?id=53972
- */
-
-final class TestPLVRecord {
- private static final String DV_DEFINITION = "$A$1:$A$5";
- private static final String XLS_FILENAME = "53972.xls";
- private static final String SHEET_NAME = "S2";
-
- @Test
- void testPLVRecord() throws Exception {
- try (InputStream is = HSSFTestDataSamples.openSampleFileStream(XLS_FILENAME);
- HSSFWorkbook workbook = new HSSFWorkbook(is)) {
-
- CellRangeAddressList cellRange = new CellRangeAddressList(0, 0, 1, 1);
- DataValidationConstraint constraint = DVConstraint.createFormulaListConstraint(DV_DEFINITION);
- HSSFDataValidation dataValidation = new HSSFDataValidation(cellRange, constraint);
-
- // This used to throw an IllegalStateException before
- // Identified bug 53972, PLV record breaks addDataValidation()
- HSSFSheet sheet = workbook.getSheet(SHEET_NAME);
- assertDoesNotThrow(() -> sheet.addValidationData(dataValidation));
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java b/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java
deleted file mode 100644
index ac97d99d4e..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.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.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.poi.hssf.util.HSSFColor;
-import org.junit.jupiter.api.Test;
-
-/**
- * Verifies that custom palette editing works correctly
- */
-final class TestPaletteRecord {
-
- /**
- * Tests that the default palette matches the constants of HSSFColor
- */
- @Test
- void testDefaultPalette() {
- PaletteRecord palette = new PaletteRecord();
-
- //make sure all the HSSFColor constants match
- Map colors = HSSFColor.getIndexHash();
- for (Entry entry : colors.entrySet()) {
- int index = entry.getKey();
- HSSFColor c = entry.getValue();
- short[] rgbTriplet = c.getTriplet();
- byte[] paletteTriplet = palette.getColor((short) index);
- String msg = "Expected HSSFColor constant to match PaletteRecord at index" + (index == c.getIndex2() ? "2" : "") + " 0x"
- + Integer.toHexString(index);
- assertNotNull(paletteTriplet);
- assertEquals(rgbTriplet[0], paletteTriplet[0] & 0xff, msg);
- assertEquals(rgbTriplet[1], paletteTriplet[1] & 0xff, msg);
- assertEquals(rgbTriplet[2], paletteTriplet[2] & 0xff, msg);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestPaneRecord.java b/src/testcases/org/apache/poi/hssf/record/TestPaneRecord.java
deleted file mode 100644
index c20209cf5b..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestPaneRecord.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.hssf.record;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the PaneRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestPaneRecord {
- byte[] data = new byte[] {
- (byte)0x01, (byte)0x00,
- (byte)0x02, (byte)0x00,
- (byte)0x03, (byte)0x00,
- (byte)0x04, (byte)0x00,
- (byte)0x02, (byte)0x00,
- };
-
- @Test
- void testLoad() {
- PaneRecord record = new PaneRecord(TestcaseRecordInputStream.create(0x41, data));
-
- assertEquals( (short)1, record.getX());
- assertEquals( (short)2, record.getY());
- assertEquals( (short)3, record.getTopRow());
- assertEquals( (short)4, record.getLeftColumn());
- assertEquals( PaneRecord.ACTIVE_PANE_LOWER_LEFT, record.getActivePane());
-
- assertEquals( 14, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- PaneRecord record = new PaneRecord();
-
- record.setX( (short) 1);
- record.setY( (short) 2);
- record.setTopRow( (short) 3);
- record.setLeftColumn( (short) 4);
- record.setActivePane( PaneRecord.ACTIVE_PANE_LOWER_LEFT);
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(PaneRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java b/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java
deleted file mode 100644
index 670e2fe70c..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.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.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-final class TestRecalcIdRecord {
-
- private static RecalcIdRecord create(byte[] data) {
- RecordInputStream in = TestcaseRecordInputStream.create(RecalcIdRecord.sid, data);
- RecalcIdRecord result = new RecalcIdRecord(in);
- assertEquals(0, in.remaining());
- return result;
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testBasicDeserializeReserialize() {
-
- byte[] data = HexRead.readFromString(
- "C1 01" + // rt
- "00 00" + // reserved
- "1D EB 01 00"); // engine id
-
- RecalcIdRecord r = create(data);
- confirmRecordEncoding(RecalcIdRecord.sid, data, r.serialize());
- }
-
- @Test
- void testBadFirstField_bug48096() {
- /*
- * Data taken from the sample file referenced in Bugzilla 48096, file offset 0x0D45.
- * The apparent problem is that the first data short field has been written with the
- * wrong endianness. Excel seems to ignore whatever value is present in this
- * field, and always rewrites it as (C1, 01). POI now does the same.
- */
- byte[] badData = HexRead.readFromString("C1 01 08 00 01 C1 00 00 00 01 69 61");
- byte[] goodData = HexRead.readFromString("C1 01 08 00 C1 01 00 00 00 01 69 61");
-
- RecordInputStream in = TestcaseRecordInputStream.create(badData);
-
- // bug 48096 - expected 449 but got 49409
- RecalcIdRecord r = new RecalcIdRecord(in);
-
- assertEquals(0, in.remaining());
- assertArrayEquals(r.serialize(), goodData);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java b/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java
deleted file mode 100644
index 11f66367e1..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.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.hssf.record;
-
-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 java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the record factory
- */
-final class TestRecordFactory {
-
-
- /**
- * TEST NAME: Test Basic Record Construction
- * OBJECTIVE: Test that the RecordFactory given the required parameters for know
- * record types can construct the proper record w/values.
- * SUCCESS: Record factory creates the records with the expected values.
- * FAILURE: The wrong records are creates or contain the wrong values
- *
- */
- @Test
- void testBasicRecordConstruction() {
- short recType = BOFRecord.sid;
- byte[] data = {
- 0, 6, 5, 0, -2, 28, -51, 7, -55, 64, 0, 0, 6, 1, 0, 0
- };
- Record[] record = RecordFactory.createRecord(TestcaseRecordInputStream.create(recType, data));
-
- assertEquals(BOFRecord.class.getName(),
- record[ 0 ].getClass().getName());
- BOFRecord bofRecord = ( BOFRecord ) record[ 0 ];
-
- assertEquals(7422, bofRecord.getBuild());
- assertEquals(1997, bofRecord.getBuildYear());
- assertEquals(16585, bofRecord.getHistoryBitMask());
- assertEquals(20, bofRecord.getRecordSize());
- assertEquals(262, bofRecord.getRequiredVersion());
- assertEquals(2057, bofRecord.getSid());
- assertEquals(5, bofRecord.getType());
- assertEquals(1536, bofRecord.getVersion());
- recType = MMSRecord.sid;
- data = new byte[] {
- 0, 0
- };
- record = RecordFactory.createRecord(TestcaseRecordInputStream.create(recType, data));
- assertEquals(MMSRecord.class.getName(),
- record[ 0 ].getClass().getName());
- MMSRecord mmsRecord = ( MMSRecord ) record[ 0 ];
-
- assertEquals(0, mmsRecord.getAddMenuCount());
- assertEquals(0, mmsRecord.getDelMenuCount());
- assertEquals(6, mmsRecord.getRecordSize());
- assertEquals(193, mmsRecord.getSid());
- }
-
- /**
- * TEST NAME: Test Special Record Construction
- * OBJECTIVE: Test that the RecordFactory given the required parameters for
- * constructing a RKRecord will return a NumberRecord.
- * SUCCESS: Record factory creates the Number record with the expected values.
- * FAILURE: The wrong records are created or contain the wrong values
- *
- */
- @Test
- void testSpecial() {
- short recType = RKRecord.sid;
- byte[] data = {
- 0, 0, 0, 0, 21, 0, 0, 0, 0, 0
- };
- Record[] record = RecordFactory.createRecord(TestcaseRecordInputStream.create(recType, data));
-
- assertEquals(NumberRecord.class.getName(),
- record[ 0 ].getClass().getName());
- NumberRecord numberRecord = ( NumberRecord ) record[ 0 ];
-
- assertEquals(0, numberRecord.getColumn());
- assertEquals(18, numberRecord.getRecordSize());
- assertEquals(0, numberRecord.getRow());
- assertEquals(515, numberRecord.getSid());
- assertEquals(0.0, numberRecord.getValue(), 0.001);
- assertEquals(21, numberRecord.getXFIndex());
- }
-
- /**
- * TEST NAME: Test Creating ContinueRecords After Unknown Records From An InputStream
- * OBJECTIVE: Test that the RecordFactory given an InputStream
- * constructs the expected array of records.
- * SUCCESS: Record factory creates the expected records.
- * FAILURE: The wrong records are created or contain the wrong values
- */
- @Test
- void testContinuedUnknownRecord() {
- byte[] data = {
- 0, -1, 0, 0, // an unknown record with 0 length
- 0x3C , 0, 3, 0, 1, 2, 3, // a continuation record with 3 bytes of data
- 0x3C , 0, 1, 0, 4 // one more continuation record with 1 byte of data
- };
-
- ByteArrayInputStream bois = new ByteArrayInputStream(data);
- Record[] records = RecordFactory.createRecords(bois).toArray(new Record[0]);
- assertEquals(3, records.length, "Created record count");
- assertEquals(UnknownRecord.class.getName(), records[ 0 ].getClass().getName(), "1st record's type");
- assertEquals((short)-256, records[0].getSid(), "1st record's sid");
- assertEquals(ContinueRecord.class.getName(), records[ 1 ].getClass().getName(), "2nd record's type");
- ContinueRecord record = (ContinueRecord) records[1];
- assertEquals(0x3C, record.getSid(), "2nd record's sid");
- assertEquals(1, record.getData()[ 0 ], "1st data byte");
- assertEquals(2, record.getData()[ 1 ], "2nd data byte");
- assertEquals(3, record.getData()[ 2 ], "3rd data byte");
- assertEquals(ContinueRecord.class.getName(), records[ 2 ].getClass().getName(), "3rd record's type");
- record = (ContinueRecord) records[2];
- assertEquals(0x3C, record.getSid(), "3nd record's sid");
- assertEquals(4, record.getData()[ 0 ], "4th data byte");
- }
-
- /**
- * Drawing records have a very strange continue behaviour.
- * There can actually be OBJ records mixed between the continues.
- * Record factory must preserve this structure when reading records.
- */
- @Test
- void testMixedContinue() throws IOException {
- // Adapted from a real test sample file 39512.xls (Offset 0x4854).
- // See Bug 39512 for details.
- String dump =
- //OBJ
- "5D 00 48 00 15 00 12 00 0C 00 3C 00 11 00 A0 2E 03 01 CC 42 " +
- "CF 00 00 00 00 00 0A 00 0C 00 00 00 00 00 00 00 00 00 00 00 " +
- "03 00 0B 00 06 00 28 01 03 01 00 00 12 00 08 00 00 00 00 00 " +
- "00 00 03 00 11 00 04 00 3D 00 00 00 00 00 00 00 " +
- //MSODRAWING
- "EC 00 08 00 00 00 0D F0 00 00 00 00 " +
- //TXO (and 2 trailing CONTINUE records)
- "B6 01 12 00 22 02 00 00 00 00 00 00 00 00 10 00 10 00 00 00 00 00 " +
- "3C 00 11 00 00 4F 70 74 69 6F 6E 20 42 75 74 74 6F 6E 20 33 39 " +
- "3C 00 10 00 00 00 05 00 00 00 00 00 10 00 00 00 00 00 00 00 " +
- // another CONTINUE
- "3C 00 7E 00 0F 00 04 F0 7E 00 00 00 92 0C 0A F0 08 00 00 00 " +
- "3D 04 00 00 00 0A 00 00 A3 00 0B F0 3C 00 00 00 7F 00 00 01 " +
- "00 01 80 00 8C 01 03 01 85 00 01 00 00 00 8B 00 02 00 00 00 " +
- "BF 00 08 00 1A 00 7F 01 29 00 29 00 81 01 41 00 00 08 BF 01 " +
- "00 00 10 00 C0 01 40 00 00 08 FF 01 00 00 08 00 00 00 10 F0 " +
- "12 00 00 00 02 00 02 00 A0 03 18 00 B5 00 04 00 30 02 1A 00 " +
- "00 00 00 00 11 F0 00 00 00 00 " +
- //OBJ
- "5D 00 48 00 15 00 12 00 0C 00 3D 00 11 00 8C 01 03 01 C8 59 CF 00 00 " +
- "00 00 00 0A 00 0C 00 00 00 00 00 00 00 00 00 00 00 03 00 0B 00 06 00 " +
- "7C 16 03 01 00 00 12 00 08 00 00 00 00 00 00 00 03 00 11 00 04 00 01 " +
- "00 00 00 00 00 00 00";
- byte[] data = HexRead.readFromString(dump);
-
- List records = RecordFactory.createRecords(new ByteArrayInputStream(data));
- assertEquals(5, records.size());
- assertTrue(records.get(0) instanceof ObjRecord);
- assertTrue(records.get(1) instanceof DrawingRecord);
- assertTrue(records.get(2) instanceof TextObjectRecord);
- assertTrue(records.get(3) instanceof ContinueRecord);
- assertTrue(records.get(4) instanceof ObjRecord);
-
- //serialize and verify that the serialized data is the same as the original
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- for(org.apache.poi.hssf.record.Record rec : records){
- out.write(rec.serialize());
- }
-
- byte[] ser = out.toByteArray();
- assertEquals(data.length, ser.length);
- assertArrayEquals(data, ser);
- }
-
- @Test
- void testNonZeroPadding_bug46987() throws IOException {
- Record[] recs = {
- new BOFRecord(),
- new WriteAccessRecord(), // need *something* between BOF and EOF
- EOFRecord.instance,
- BOFRecord.createSheetBOF(),
- EOFRecord.instance,
- };
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- for (org.apache.poi.hssf.record.Record rec : recs) {
- try {
- baos.write(rec.serialize());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- //simulate the bad padding at the end of the workbook stream in attachment 23483 of bug 46987
- baos.write(0x00);
- baos.write(0x11);
- baos.write(0x00);
- baos.write(0x02);
- for (int i = 0; i < 192; i++) {
- baos.write(0x00);
- }
-
-
- POIFSFileSystem fs = new POIFSFileSystem();
- fs.createDocument(new ByteArrayInputStream(baos.toByteArray()), "dummy");
- InputStream is = fs.getRoot().createDocumentInputStream("dummy");
-
- List outRecs = RecordFactory.createRecords(is);
- // Buffer underrun - requested 512 bytes but 192 was available
- assertEquals(5, outRecs.size());
- fs.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java
deleted file mode 100644
index 9c7d6be428..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-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.ByteArrayInputStream;
-
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link RecordFactoryInputStream}
- *
- * @author Josh Micich
- */
-final class TestRecordFactoryInputStream {
- /**
- * Hex dump of a BOF record and most of a FILEPASS record.
- * A 16 byte saltHash should be added to complete the second record
- */
- private static final String COMMON_HEX_DATA = ""
- // BOF
- + "09 08 10 00"
- + "00 06 05 00 D3 10 CC 07 01 00 00 00 00 06 00 00"
- // FILEPASS
- + "2F 00 36 00"
- + "01 00 01 00 01 00"
- + "BAADF00D BAADF00D BAADF00D BAADF00D" // docId
- + "DEADBEEF DEADBEEF DEADBEEF DEADBEEF" // saltData
- ;
-
- /**
- * Hex dump of a sample WINDOW1 record
- */
- private static final String SAMPLE_WINDOW1 = "3D 00 12 00"
- + "00 00 00 00 40 38 55 23 38 00 00 00 00 00 01 00 58 02";
-
-
- /**
- * Makes sure that a default password mismatch condition is represented with {@link EncryptedDocumentException}
- */
- @Test
- void defaultPasswordWrong() {
- // This encodng depends on docId, password and stream position
- final String SAMPLE_WINDOW1_ENCR1 = "3D 00 12 00"
- + "C4, 9B, 02, 50, 86, E0, DF, 34, FB, 57, 0E, 8C, CE, 25, 45, E3, 80, 01";
-
- byte[] dataWrongDefault = HexRead.readFromString(""
- + COMMON_HEX_DATA
- + "00000000 00000000 00000000 00000001"
- + SAMPLE_WINDOW1_ENCR1
- );
-
- EncryptedDocumentException ex = assertThrows(
- EncryptedDocumentException.class,
- () -> createRFIS(dataWrongDefault)
- );
- assertTrue(ex.getMessage().contains("Default password is invalid for salt/verifier/verifierHash"));
- }
-
- @Test
- void defaultPasswordOK() {
- // This encodng depends on docId, password and stream position
- final String SAMPLE_WINDOW1_ENCR1 = "3D 00 12 00"
- + "C4, 9B, 02, 50, 86, E0, DF, 34, FB, 57, 0E, 8C, CE, 25, 45, E3, 80, 01";
-
- byte[] dataCorrectDefault = HexRead.readFromString(""
- + COMMON_HEX_DATA
- + "137BEF04 969A200B 306329DE 52254005" // correct saltHash for default password (and docId/saltHash)
- + SAMPLE_WINDOW1_ENCR1
- );
-
- RecordFactoryInputStream rfis = createRFIS(dataCorrectDefault);
- confirmReadInitialRecords(rfis);
- }
-
-
- /**
- * Makes sure that an incorrect user supplied password condition is represented with {@link EncryptedDocumentException}
- */
- @Test
- void suppliedPasswordWrong() {
- // This encoding depends on docId, password and stream position
- final String SAMPLE_WINDOW1_ENCR2 = "3D 00 12 00"
- + "45, B9, 90, FE, B6, C6, EC, 73, EE, 3F, 52, 45, 97, DB, E3, C1, D6, FE";
-
- byte[] dataWrongDefault = HexRead.readFromString(""
- + COMMON_HEX_DATA
- + "00000000 00000000 00000000 00000000"
- + SAMPLE_WINDOW1_ENCR2
- );
-
- Biff8EncryptionKey.setCurrentUserPassword("passw0rd");
- try {
- EncryptedDocumentException ex = assertThrows(
- EncryptedDocumentException.class,
- () -> createRFIS(dataWrongDefault)
- );
- assertEquals("Supplied password is invalid for salt/verifier/verifierHash", ex.getMessage());
- } finally {
- Biff8EncryptionKey.setCurrentUserPassword(null);
- }
- }
-
- @Test
- void suppliedPasswordOK() {
- // This encoding depends on docId, password and stream position
- final String SAMPLE_WINDOW1_ENCR2 = "3D 00 12 00"
- + "45, B9, 90, FE, B6, C6, EC, 73, EE, 3F, 52, 45, 97, DB, E3, C1, D6, FE";
-
- byte[] dataCorrectDefault = HexRead.readFromString(""
- + COMMON_HEX_DATA
- + "C728659A C38E35E0 568A338F C3FC9D70" // correct saltHash for supplied password (and docId/saltHash)
- + SAMPLE_WINDOW1_ENCR2
- );
-
- Biff8EncryptionKey.setCurrentUserPassword("passw0rd");
- try {
- RecordFactoryInputStream rfis = createRFIS(dataCorrectDefault);
- confirmReadInitialRecords(rfis);
- } finally {
- Biff8EncryptionKey.setCurrentUserPassword(null);
- }
- }
-
-
- /**
- * makes sure the record stream starts with {@link BOFRecord}, {@link FilePassRecord} and then {@link WindowOneRecord}
- * The third record is decrypted so this method also checks its content.
- */
- private void confirmReadInitialRecords(RecordFactoryInputStream rfis) {
- assertEquals(BOFRecord.class, rfis.nextRecord().getClass());
- FilePassRecord recFP = (FilePassRecord) rfis.nextRecord();
- WindowOneRecord rec1 = (WindowOneRecord) rfis.nextRecord();
- assertArrayEquals(HexRead.readFromString(SAMPLE_WINDOW1),rec1.serialize());
- }
-
- private static RecordFactoryInputStream createRFIS(byte[] data) {
- return new RecordFactoryInputStream(new ByteArrayInputStream(data), true);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java
deleted file mode 100644
index 0956350283..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.CsvSource;
-
-/**
- * Tests for {@link RecordInputStream}
- */
-final class TestRecordInputStream {
-
- /**
- * Data inspired by attachment 22626 of bug 45866
- * A unicode string of 18 chars, with a continue record where the compression flag changes
- */
- private static final String HED_DUMP1 = ""
- + "1A 59 00 8A 9E 8A " // 3 uncompressed unicode chars
- + "3C 00 " // Continue sid
- + "10 00 " // rec size 16 (1+15)
- + "00" // next chunk is compressed
- + "20 2D 20 4D 75 6C 74 69 6C 69 6E 67 75 61 6C " // 15 chars
- ;
- /**
- * same string re-arranged
- */
- private static final String HED_DUMP2 = ""
- // 15 chars at end of current record
- + "4D 75 6C 74 69 6C 69 6E 67 75 61 6C 20 2D 20"
- + "3C 00 " // Continue sid
- + "07 00 " // rec size 7 (1+6)
- + "01" // this bit uncompressed
- + "1A 59 00 8A 9E 8A " // 3 uncompressed unicode chars
- ;
-
-
- @Test
- void testChangeOfCompressionFlag_bug25866() {
- byte[] changingFlagSimpleData = HexRead.readFromString(""
- + "AA AA " // fake SID
- + "06 00 " // first rec len 6
- + HED_DUMP1
- );
- RecordInputStream in = TestcaseRecordInputStream.create(changingFlagSimpleData);
-
- // bug 45866 - compressByte in continue records must be 1 while reading unicode LE string
- String actual = in.readUnicodeLEString(18);
- assertEquals("\u591A\u8A00\u8A9E - Multilingual", actual);
- }
-
- @Test
- void testChangeFromUnCompressedToCompressed() {
- byte[] changingFlagSimpleData = HexRead.readFromString(""
- + "AA AA " // fake SID
- + "0F 00 " // first rec len 15
- + HED_DUMP2
- );
- RecordInputStream in = TestcaseRecordInputStream.create(changingFlagSimpleData);
- String actual = in.readCompressedUnicode(18);
- assertEquals("Multilingual - \u591A\u8A00\u8A9E", actual);
- }
-
- @Test
- void testReadString() {
- byte[] changingFlagFullData = HexRead.readFromString(""
- + "AA AA " // fake SID
- + "12 00 " // first rec len 18 (15 + next 3 bytes)
- + "12 00 " // total chars 18
- + "00 " // this bit compressed
- + HED_DUMP2
- );
- RecordInputStream in = TestcaseRecordInputStream.create(changingFlagFullData);
- String actual = in.readString();
- assertEquals("Multilingual - \u591A\u8A00\u8A9E", actual);
- }
-
- @ParameterizedTest
- @CsvSource({"1, 200", "0, 200", "999999999, 200", HeaderRecord.sid+", 200"})
- void testLeftoverDataException(int sid, int remainingByteCount) {
- // just ensure that the exception is created correctly, even with unknown sids
- assertDoesNotThrow(() -> new RecordInputStream.LeftoverDataException(sid, remainingByteCount));
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java
deleted file mode 100644
index 92e5abff02..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the SCLRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestSCLRecord {
- byte[] data = new byte[] {
- (byte)0x3,(byte)0x0,(byte)0x4,(byte)0x0
- };
-
- @Test
- void testLoad() {
- SCLRecord record = new SCLRecord(TestcaseRecordInputStream.create(0xa0, data));
- assertEquals( 3, record.getNumerator());
- assertEquals( 4, record.getDenominator());
-
- assertEquals( 8, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- SCLRecord record = new SCLRecord();
- record.setNumerator( (short)3 );
- record.setDenominator( (short)4 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(SCLRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java b/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java
deleted file mode 100644
index 7bde03cb06..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.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.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.common.UnicodeString;
-import org.apache.poi.util.HexRead;
-import org.apache.poi.util.IntMapper;
-import org.junit.jupiter.api.Test;
-
-/**
- * Exercise the SSTDeserializer class.
- *
- * @author Glen Stampoultzis (glens at apache.org)
- */
-final class TestSSTDeserializer {
- private static final int FAKE_SID = -5555;
-
- private static byte[] concat(byte[] a, byte[] b) {
- byte[] result = new byte[a.length + b.length];
- System.arraycopy(a, 0, result, 0, a.length);
- System.arraycopy(b, 0, result, a.length, b.length);
- return result;
- }
-
- private static byte[] readSampleHexData(String sampleFileName, String sectionName, int recSid)
- throws IOException {
- InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName);
- byte[] data = HexRead.readData(is, sectionName);
- byte[] result = TestcaseRecordInputStream.mergeDataAndSid(recSid, data.length, data);
- is.close();
- return result;
- }
-
- @Test
- void testSpanRichTextToPlainText() throws IOException {
- byte[] header = readSampleHexData("richtextdata.txt", "header", FAKE_SID);
- byte[] continueBytes = readSampleHexData("richtextdata.txt", "continue1", ContinueRecord.sid);
- RecordInputStream in = TestcaseRecordInputStream.create(concat(header, continueBytes));
-
-
- IntMapper strings = new IntMapper<>();
- SSTDeserializer deserializer = new SSTDeserializer( strings );
- deserializer.manufactureStrings(1, in );
-
- assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" );
- }
-
- @Test
- void testContinuationWithNoOverlap() throws IOException {
- byte[] header = readSampleHexData("evencontinuation.txt", "header", FAKE_SID);
- byte[] continueBytes = readSampleHexData("evencontinuation.txt", "continue1", ContinueRecord.sid);
- RecordInputStream in = TestcaseRecordInputStream.create(concat(header, continueBytes));
-
- IntMapper strings = new IntMapper<>();
- SSTDeserializer deserializer = new SSTDeserializer( strings );
- deserializer.manufactureStrings( 2, in);
-
- assertEquals( "At a dinner party or", strings.get( 0 ) + "" );
- assertEquals( "At a dinner party", strings.get( 1 ) + "" );
- }
-
- /**
- * Strings can actually span across more than one continuation.
- */
- @Test
- void testStringAcross2Continuations() throws IOException {
- byte[] header = readSampleHexData("stringacross2continuations.txt", "header", FAKE_SID);
- byte[] continue1 = readSampleHexData("stringacross2continuations.txt", "continue1", ContinueRecord.sid);
- byte[] continue2 = readSampleHexData("stringacross2continuations.txt", "continue2", ContinueRecord.sid);
-
- RecordInputStream in = TestcaseRecordInputStream.create(concat(header, concat(continue1, continue2)));
-
- IntMapper strings = new IntMapper<>();
- SSTDeserializer deserializer = new SSTDeserializer( strings );
- deserializer.manufactureStrings( 2, in);
-
- assertEquals( "At a dinner party or", strings.get( 0 ) + "" );
- assertEquals( "At a dinner partyAt a dinner party", strings.get( 1 ) + "" );
- }
-
- @Test
- void testExtendedStrings() throws IOException {
- byte[] header = readSampleHexData("extendedtextstrings.txt", "rich-header", FAKE_SID);
- byte[] continueBytes = readSampleHexData("extendedtextstrings.txt", "rich-continue1", ContinueRecord.sid);
- RecordInputStream in = TestcaseRecordInputStream.create(concat(header, continueBytes));
-
- IntMapper strings = new IntMapper<>();
- SSTDeserializer deserializer = new SSTDeserializer( strings );
- deserializer.manufactureStrings( 1, in);
-
- assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" );
-
-
- header = readSampleHexData("extendedtextstrings.txt", "norich-header", FAKE_SID);
- continueBytes = readSampleHexData("extendedtextstrings.txt", "norich-continue1", ContinueRecord.sid);
- in = TestcaseRecordInputStream.create(concat(header, continueBytes));
-
- strings = new IntMapper<>();
- deserializer = new SSTDeserializer( strings );
- deserializer.manufactureStrings( 1, in);
-
- assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" );
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java
deleted file mode 100644
index b2206b86b7..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java
+++ /dev/null
@@ -1,416 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-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.fail;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.Arrays;
-import java.util.Iterator;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.common.UnicodeString;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.apache.poi.util.HexRead;
-import org.apache.poi.util.LittleEndian;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.Test;
-
-final class TestSSTRecord {
-
- /**
- * decodes hexdump files and concatenates the results
- * @param hexDumpFileNames names of sample files in the hssf test data directory
- */
- private static byte[] concatHexDumps(String... hexDumpFileNames) throws IOException {
- int nFiles = hexDumpFileNames.length;
- ByteArrayOutputStream baos = new ByteArrayOutputStream(nFiles * 8228);
- for (String sampleFileName : hexDumpFileNames) {
- try (InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName)) {
- BufferedReader br = new BufferedReader(new InputStreamReader(is, LocaleUtil.CHARSET_1252));
-
- while (true) {
- String line = br.readLine();
- if (line == null) {
- break;
- }
- baos.write(HexRead.readFromString(line));
- }
- }
- }
-
- return baos.toByteArray();
- }
-
- /**
- * @param rawData serialization of one {@link SSTRecord} and zero or more {@link ContinueRecord}s
- */
- private static SSTRecord createSSTFromRawData(byte[] rawData) {
- RecordInputStream in = new RecordInputStream(new ByteArrayInputStream(rawData));
- in.nextRecord();
- SSTRecord result = new SSTRecord(in);
- assertEquals(0, in.remaining());
- assertFalse(in.hasNextRecord());
- return result;
- }
-
- /**
- * SST is often split over several {@link ContinueRecord}s
- */
- @Test
- void testContinuedRecord() throws IOException {
- byte[] origData;
- SSTRecord record;
- byte[] ser_output;
-
- origData = concatHexDumps("BigSSTRecord", "BigSSTRecordCR");
- record = createSSTFromRawData(origData);
- assertEquals( 1464, record.getNumStrings() );
- assertEquals( 688, record.getNumUniqueStrings() );
- assertEquals( 688, record.countStrings() );
- ser_output = record.serialize();
- assertArrayEquals(origData, ser_output);
-
- // testing based on new bug report
- origData = concatHexDumps("BigSSTRecord2", "BigSSTRecord2CR1", "BigSSTRecord2CR2", "BigSSTRecord2CR3",
- "BigSSTRecord2CR4", "BigSSTRecord2CR5", "BigSSTRecord2CR6", "BigSSTRecord2CR7");
- record = createSSTFromRawData(origData);
-
-
- assertEquals( 158642, record.getNumStrings() );
- assertEquals( 5249, record.getNumUniqueStrings() );
- assertEquals( 5249, record.countStrings() );
- ser_output = record.serialize();
-// if (false) { // set true to observe make sure areSameSSTs() is working
-// ser_output[11000] = 'X';
-// }
-
- SSTRecord rec2 = createSSTFromRawData(ser_output);
- assertRecordEquals(record, rec2);
-
-// if (false) {
-// // TODO - trivial differences in ContinueRecord break locations
-// // Sample data should be checked against what most recent Excel version produces.
-// // maybe tweaks are required in ContinuableRecordOutput
-// assertArrayEquals(origData, ser_output);
-// }
- }
-
- /**
- * Test capability of handling mondo big strings
- */
- @Test
- void testHugeStrings() {
- SSTRecord record = new SSTRecord();
- byte[][] bstrings =
- {
- new byte[9000], new byte[7433], new byte[9002],
- new byte[16998]
- };
- UnicodeString[] strings = new UnicodeString[bstrings.length];
- int total_length = 0;
-
- for ( int k = 0; k < bstrings.length; k++ )
- {
- Arrays.fill( bstrings[k], (byte) ( 'a' + k ) );
- strings[k] = new UnicodeString( new String(bstrings[k], LocaleUtil.CHARSET_1252) );
- record.addString( strings[k] );
- total_length += 3 + bstrings[k].length;
- }
-
- // add overhead of SST record
- total_length += 8;
-
- // add overhead of broken strings
- total_length += 4;
-
- // add overhead of six records
- total_length += ( 6 * 4 );
- byte[] content = new byte[record.getRecordSize()];
-
- record.serialize( 0, content );
- assertEquals( total_length, content.length );
-
- //Deserialize the record.
- RecordInputStream recStream = new RecordInputStream(new ByteArrayInputStream(content));
- recStream.nextRecord();
- record = new SSTRecord(recStream);
-
- assertEquals( strings.length, record.getNumStrings() );
- assertEquals( strings.length, record.getNumUniqueStrings() );
- assertEquals( strings.length, record.countStrings() );
- for ( int k = 0; k < strings.length; k++ )
- {
- assertEquals( strings[k], record.getString( k ) );
- }
- record = new SSTRecord();
- bstrings[1] = new byte[bstrings[1].length - 1];
- for ( int k = 0; k < bstrings.length; k++ )
- {
- if ( ( bstrings[k].length % 2 ) == 1 )
- {
- Arrays.fill( bstrings[k], (byte) ( 'a' + k ) );
- strings[k] = new UnicodeString( new String(bstrings[k], LocaleUtil.CHARSET_1252) );
- }
- else
- {
- char[] data = new char[bstrings[k].length / 2];
-
- Arrays.fill( data, (char) ( '\u2122' + k ) );
- strings[k] = new UnicodeString(new String( data ));
- }
- record.addString( strings[k] );
- }
- content = new byte[record.getRecordSize()];
- record.serialize( 0, content );
- total_length--;
- assertEquals( total_length, content.length );
-
- recStream = new RecordInputStream(new ByteArrayInputStream(content));
- recStream.nextRecord();
- record = new SSTRecord(recStream);
-
- assertEquals( strings.length, record.getNumStrings() );
- assertEquals( strings.length, record.getNumUniqueStrings() );
- assertEquals( strings.length, record.countStrings() );
- for ( int k = 0; k < strings.length; k++ )
- {
- assertEquals( strings[k], record.getString( k ) );
- }
- }
-
- /**
- * test SSTRecord boundary conditions
- */
- @Test
- void testSSTRecordBug() {
- // create an SSTRecord and write a certain pattern of strings
- // to it ... then serialize it and verify the content
- SSTRecord record = new SSTRecord();
-
- // the record will start with two integers, then this string
- // ... that will eat up 16 of the 8224 bytes that the record
- // can hold
- record.addString( new UnicodeString("Hello") );
-
- // now we have an additional 8208 bytes, which is an exact
- // multiple of 16 bytes
- long testvalue = 1000000000000L;
-
- for ( int k = 0; k < 2000; k++ )
- {
- record.addString( new UnicodeString(String.valueOf( testvalue++ )) );
- }
- byte[] content = new byte[record.getRecordSize()];
-
- record.serialize( 0, content );
- assertEquals(8224, LittleEndian.getShort(content, 2));
- assertEquals(ContinueRecord.sid, LittleEndian.getShort(content, 8228));
- assertEquals(8224, LittleEndian.getShort(content, 8228+2));
- assertEquals( (byte) 13, content[4 + 8228] );
- assertEquals(ContinueRecord.sid, LittleEndian.getShort(content, 2*8228));
- assertEquals(8224, LittleEndian.getShort(content, 8228*2+2));
- assertEquals( (byte) 13, content[4 + 8228 * 2] );
- assertEquals(ContinueRecord.sid, LittleEndian.getShort(content, 3*8228));
- assertEquals( (byte) 13, content[4 + 8228 * 3] );
- }
-
- /**
- * test simple addString
- */
- @Test
- void testSimpleAddString() {
- SSTRecord record = new SSTRecord();
- UnicodeString s1 = new UnicodeString("Hello world");
-
- // \u2122 is the encoding of the trademark symbol ...
- UnicodeString s2 = new UnicodeString("Hello world\u2122");
-
- assertEquals( 0, record.addString( s1 ) );
- assertEquals( s1, record.getString( 0 ) );
- assertEquals( 1, record.countStrings() );
- assertEquals( 1, record.getNumStrings() );
- assertEquals( 1, record.getNumUniqueStrings() );
- assertEquals( 0, record.addString( s1 ) );
- assertEquals( s1, record.getString( 0 ) );
- assertEquals( 1, record.countStrings() );
- assertEquals( 2, record.getNumStrings() );
- assertEquals( 1, record.getNumUniqueStrings() );
- assertEquals( 1, record.addString( s2 ) );
- assertEquals( s2, record.getString( 1 ) );
- assertEquals( 2, record.countStrings() );
- assertEquals( 3, record.getNumStrings() );
- assertEquals( 2, record.getNumUniqueStrings() );
- Iterator iter = record.getStrings();
-
- while ( iter.hasNext() ) {
- UnicodeString ucs = iter.next();
-
- if ( ucs.equals( s1 ) )
- {
- assertEquals( (byte) 0, ucs.getOptionFlags() );
- }
- else if ( ucs.equals( s2 ) )
- {
- assertEquals( (byte) 1, ucs.getOptionFlags() );
- }
- else
- {
- fail( "cannot match string: " + ucs.getString() );
- }
- }
- }
-
- /**
- * test simple constructor
- */
- @Test
- void testSimpleConstructor() {
- SSTRecord record = new SSTRecord();
-
- assertEquals( 0, record.getNumStrings() );
- assertEquals( 0, record.getNumUniqueStrings() );
- assertEquals( 0, record.countStrings() );
- byte[] output = record.serialize();
- byte[] expected = {
- (byte) record.getSid(), (byte) ( record.getSid() >> 8 ),
- (byte) 8, (byte) 0, (byte) 0, (byte) 0, (byte) 0,
- (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0
- };
-
- assertArrayEquals(expected, output);
- }
-
- /**
- * Tests that workbooks with rich text that duplicates a non rich text cell can be read and written.
- */
- @Test
- void testReadWriteDuplicatedRichText1() throws Exception {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("duprich1.xls")) {
- HSSFSheet sheet = wb.getSheetAt(1);
- assertEquals("01/05 (Wed)", sheet.getRow(0).getCell(8).getStringCellValue());
- assertEquals("01/05 (Wed)", sheet.getRow(1).getCell(8).getStringCellValue());
-
- HSSFTestDataSamples.writeOutAndReadBack(wb).close();
- }
-
- // test the second file.
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("duprich2.xls")) {
- HSSFSheet sheet = wb.getSheetAt(0);
- int row = 0;
- assertEquals("Testing", sheet.getRow(row++).getCell(0).getStringCellValue());
- assertEquals("rich", sheet.getRow(row++).getCell(0).getStringCellValue());
- assertEquals("text", sheet.getRow(row++).getCell(0).getStringCellValue());
- assertEquals("strings", sheet.getRow(row++).getCell(0).getStringCellValue());
- assertEquals("Testing", sheet.getRow(row++).getCell(0).getStringCellValue());
- assertEquals("Testing", sheet.getRow(row).getCell(0).getStringCellValue());
-
- HSSFTestDataSamples.writeOutAndReadBack(wb).close();
- }
- }
-
-
- /**
- * deep comparison of two SST records
- */
- private static void assertRecordEquals(SSTRecord expected, SSTRecord actual){
- assertEquals(expected.getNumStrings(), actual.getNumStrings(), "number of strings");
- assertEquals(expected.getNumUniqueStrings(), actual.getNumUniqueStrings(), "number of unique strings");
- assertEquals(expected.countStrings(), actual.countStrings(), "count of strings");
-
- Iterator iterA = expected.getStrings();
- Iterator iterB = actual.getStrings();
- while (iterA.hasNext()) {
- assertEquals(iterA.next(), iterB.next());
- }
- }
-
- @Test
- void test50779_1() throws IOException {
- byte[] bytes = RawDataUtil.decompress("H4sIAAAAAAAAAL3aO2gVQRQG4HO5XkEZ8AESi4DBKoXFP+8IVioSvahcLxKC" +
- "iRIRc9FEUZExCL4IYnyQqIi9SEATFUHRTkSQaBFsrEQLG8EiFgGrCM6uIGiff5c5e3ZY9l8W9mt2FqSjoyEixTBSW5kPm7EV29CNHa" +
- "hjJ3ajgSb2oge92Id+HMAADuEwWjiCoxjCMI7hOE7iNM7gLM7hPC7gIi5hFJdxBWO4imu4jhsYxy3cBqTYtVRESU28/NnqMFJZ/Fgj" +
- "lBjLiXGcGM+JCZyYyInp4sRsZMTo8sshxGhODEUBzVFAcxTQHAU0RwHNUUBzFNAcBQxHAcNRwHAUMBwFDEcBw1HAcBQwHAUMRwHDUc" +
- "ByFLAcBSxHActRwHIUsBwFLEcBy1HAchSwHAUcRwHHUcBxFHAcBRxHAcdRwHEUcBwFHEcBx1HAcxTwHAU8RwHPUcBzFPAcBTxHAc9R" +
- "wHMU8BwFAkeBwFEgcBQIHAUCR4HAUSBwFAgcBQJHgcBRIHIUiBwFIkeByFEgchSIHAUiR4HIUSBmBdZJ7aWItDXTcHNiz925lkoP+u" +
- "oHVRof+dmnUrXVOajSQs/YKZVODE7v+jWxpbl9VKX9I929n/tVSndmb6pUkWfl//Tl5ZN/whtM4T7eYRL38BBf8R1PMZ9nfuBt2X3E" +
- "E7zAl7KfwWs8Lrvn+YpXf2cn8Qjfcp3ZJI1KvuZDOT+F95jO9yn6opstu+IvflWW5lEVVR5XybJc2/JZVdplRa7rZXWunbIm1w2yVp" +
- "bkN9yee9Kyg5gp/HfZAW3FQ1ce/694+A14Ha5/eSEAAA==");
-
- RecordInputStream in = TestcaseRecordInputStream.create(bytes);
- assertEquals(SSTRecord.sid, in.getSid());
- SSTRecord src = new SSTRecord(in);
- assertEquals(81, src.getNumStrings());
-
- byte[] serialized = src.serialize();
-
- in = TestcaseRecordInputStream.create(serialized);
- assertEquals(SSTRecord.sid, in.getSid());
- SSTRecord dst = new SSTRecord(in);
- assertEquals(81, dst.getNumStrings());
-
- assertRecordEquals(src, dst);
- }
-
- @Test
- void test50779_2() throws IOException {
- byte[] bytes = RawDataUtil.decompress("H4sIAAAAAAAAAL3Uu2sVQRjG4e9wOKKw4gUkKSyCVQqLd2d2ZhOwiiLqQSUe" +
- "JIgRUcQc1ERUZBXBG0GMFxIiaC8S8I6FWIoIop2NlWBhI1hoIVhFcM6Cgn+Avx3m2+HbXd5hYJ9FGxgYNbPedNYY0SZt1hZtU1vbtV" +
- "Oj6mi3xrRHe7VP+3VAh3RYXR3RUR3TpKZ0XCd1Wmd0Tud1QRd1SZc1rSu6qhld03Xd0E3Nal63JOuNnIlxTIxnYgomJjAxkYkpmZgh" +
- "JmaYiMnrPweIQRTIGQVyRoGcUSBnFMgZBXJGgZxRIGcUcIwCjlHAMQo4RgHHKOAYBRyjgGMUcIwCjlHAMwp4RgHPKOAZBTyjgGcU8I" +
- "wCnlHAMwp4RoGCUaBgFCgYBQpGgYJRoGAUKBgFCkaBglGgYBQIjAKBUSAwCgRGgcAoEBgFAqNAYBQIjAKBUSAyCkRGgcgoEBkFIqNA" +
- "ZBSIjAKRUSAyCkRGgZJRoGQUKBkFSkaBklGgZBQoGQVKRoEyKdBvrdtm1tepJjtzu+5862bV/fH2wayaPftzPKua3cGJrFocmzmVVS" +
- "cmHu34Nbexs3U6qxo2b6105kttfRof9VoPdU/vtKC7eqDP+qpn+pE63/WmXn3QU73Qp3r9Vq/0pF49T2+8/Ntd0GN9SbX3/H3dSxuz" +
- "pi1Js2lZfV9ly1Lt22DLG6nTtLW2ItV1tjrVQVuTqrPWyvTZ/z+7YettoXcIfy4oeijNf6Pb+g0SIvVzNSEAAA==");
-
- RecordInputStream in = TestcaseRecordInputStream.create(bytes);
- assertEquals(SSTRecord.sid, in.getSid());
- SSTRecord src = new SSTRecord(in);
- assertEquals(81, src.getNumStrings());
-
- byte[] serialized = src.serialize();
-
- in = TestcaseRecordInputStream.create(serialized);
- assertEquals(SSTRecord.sid, in.getSid());
- SSTRecord dst = new SSTRecord(in);
- assertEquals(81, dst.getNumStrings());
-
- assertRecordEquals(src, dst);
- }
-
- @Test
- void test57456() {
- byte[] bytes = HexRead.readFromString("FC, 00, 08, 00, 00, 00, 00, 00, E1, 06, 00, 00");
- RecordInputStream in = TestcaseRecordInputStream.create(bytes);
- assertEquals(SSTRecord.sid, in.getSid());
- SSTRecord src = new SSTRecord(in);
- assertEquals(0, src.getNumStrings());
- assertEquals(0, src.getNumUniqueStrings());
-
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java b/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java
deleted file mode 100644
index db0593f344..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.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.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.common.UnicodeString;
-import org.apache.poi.hssf.record.cont.ContinuableRecordOutput;
-import org.apache.poi.util.IntMapper;
-import org.apache.poi.util.LittleEndianConsts;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests that records size calculates correctly.
- */
-final class TestSSTRecordSizeCalculator {
- private static final String SMALL_STRING = "Small string";
- private static final int COMPRESSED_PLAIN_STRING_OVERHEAD = 3;
- private static final int OPTION_FIELD_SIZE = 1;
-
- private final IntMapper strings = new IntMapper<>();
-
-
- /** standard record overhead: two shorts (record id plus data space size)*/
- private static final int STD_RECORD_OVERHEAD = 2 * LittleEndianConsts.SHORT_SIZE;
-
- /** SST overhead: the standard record overhead, plus the number of strings and the number of unique strings -- two ints */
- private static final int SST_RECORD_OVERHEAD = STD_RECORD_OVERHEAD + 2 * LittleEndianConsts.INT_SIZE;
-
- /** how much data can we stuff into an SST record? That would be _max minus the standard SST record overhead */
- private static final int MAX_DATA_SPACE = RecordInputStream.MAX_RECORD_DATA_SIZE - 8;
-
-
- private void confirmSize(int expectedSize) {
- ContinuableRecordOutput cro = ContinuableRecordOutput.createForCountingOnly();
- SSTSerializer ss = new SSTSerializer(strings, 0, 0);
- ss.serialize(cro);
- assertEquals(expectedSize, cro.getTotalSize());
- }
-
- @Test
- void testBasic() {
- strings.add(makeUnicodeString(SMALL_STRING));
- confirmSize(SST_RECORD_OVERHEAD
- + COMPRESSED_PLAIN_STRING_OVERHEAD
- + SMALL_STRING.length());
- }
-
- @Test
- void testBigStringAcrossUnicode() {
- int bigString = MAX_DATA_SPACE + 100;
- strings.add(makeUnicodeString(bigString));
- confirmSize(SST_RECORD_OVERHEAD
- + COMPRESSED_PLAIN_STRING_OVERHEAD
- + MAX_DATA_SPACE
- + STD_RECORD_OVERHEAD
- + OPTION_FIELD_SIZE
- + 100);
- }
-
- @Test
- void testPerfectFit() {
- int perfectFit = MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD;
- strings.add(makeUnicodeString(perfectFit));
- confirmSize(SST_RECORD_OVERHEAD
- + COMPRESSED_PLAIN_STRING_OVERHEAD
- + perfectFit);
- }
-
- @Test
- void testJustOversized() {
- int tooBig = MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD + 1;
- strings.add(makeUnicodeString(tooBig));
- confirmSize(SST_RECORD_OVERHEAD
- + COMPRESSED_PLAIN_STRING_OVERHEAD
- + tooBig - 1
- // continue record
- + STD_RECORD_OVERHEAD
- + OPTION_FIELD_SIZE + 1);
-
- }
-
- @Test
- void testSecondStringStartsOnNewContinuation() {
- int perfectFit = MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD;
- strings.add(makeUnicodeString(perfectFit));
- strings.add(makeUnicodeString(SMALL_STRING));
- confirmSize(SST_RECORD_OVERHEAD
- + MAX_DATA_SPACE
- // second string
- + STD_RECORD_OVERHEAD
- + COMPRESSED_PLAIN_STRING_OVERHEAD
- + SMALL_STRING.length());
- }
-
- @Test
- void testHeaderCrossesNormalContinuePoint() {
- int almostPerfectFit = MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD - 2;
- strings.add(makeUnicodeString(almostPerfectFit));
- String oneCharString = new String(new char[1]);
- strings.add(makeUnicodeString(oneCharString));
- confirmSize(SST_RECORD_OVERHEAD
- + COMPRESSED_PLAIN_STRING_OVERHEAD
- + almostPerfectFit
- // second string
- + STD_RECORD_OVERHEAD
- + COMPRESSED_PLAIN_STRING_OVERHEAD
- + oneCharString.length());
-
- }
-
- private static UnicodeString makeUnicodeString(int size) {
- String s = new String(new char[size]);
- return makeUnicodeString(s);
- }
-
- private static UnicodeString makeUnicodeString(String s) {
- UnicodeString st = new UnicodeString(s);
- st.setOptionFlags((byte) 0);
- return st;
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java
deleted file mode 100644
index 17855c08de..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-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 java.util.stream.Stream;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
-import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.ss.SpreadsheetVersion;
-import org.apache.poi.ss.formula.FormulaParser;
-import org.apache.poi.ss.formula.FormulaRenderer;
-import org.apache.poi.ss.formula.FormulaType;
-import org.apache.poi.ss.formula.SharedFormula;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.formula.ptg.RefPtg;
-import org.apache.poi.ss.usermodel.CellType;
-import org.apache.poi.ss.usermodel.CellValue;
-import org.apache.poi.util.LittleEndianInput;
-import org.junit.jupiter.api.Test;
-
-final class TestSharedFormulaRecord {
-
- /**
- * A sample spreadsheet known to have one sheet with 4 shared formula ranges
- */
- private static final String SHARED_FORMULA_TEST_XLS = "SharedFormulaTest.xls";
- /**
- * Binary data for an encoded formula. Taken from attachment 22062 (bugzilla 45123/45421).
- * The shared formula is in Sheet1!C6:C21, with text "SUMPRODUCT(--(End_Acct=$C6),--(End_Bal))"
- * This data is found at offset 0x1A4A (within the shared formula record).
- * The critical thing about this formula is that it contains shared formula tokens (tRefN*,
- * tAreaN*) with operand class 'array'.
- */
- private static final byte[] SHARED_FORMULA_WITH_REF_ARRAYS_DATA = {
- 0x1A, 0x00,
- 0x63, 0x02, 0x00, 0x00, 0x00,
- 0x6C, 0x00, 0x00, 0x02, (byte)0x80, // tRefNA
- 0x0B,
- 0x15,
- 0x13,
- 0x13,
- 0x63, 0x03, 0x00, 0x00, 0x00,
- 0x15,
- 0x13,
- 0x13,
- 0x42, 0x02, (byte)0xE4, 0x00,
- };
-
- /**
- * The method SharedFormulaRecord.convertSharedFormulas() converts formulas from
- * 'shared formula' to 'single cell formula' format. It is important that token operand
- * classes are preserved during this transformation, because Excel may not tolerate the
- * incorrect encoding. The formula here is one such example (Excel displays #VALUE!).
- */
- @Test
- void testConvertSharedFormulasOperandClasses_bug45123() {
-
- LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(SHARED_FORMULA_WITH_REF_ARRAYS_DATA);
- int encodedLen = in.readUShort();
- Ptg[] sharedFormula = Ptg.readTokens(encodedLen, in);
-
- SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97);
- Ptg[] convertedFormula = sf.convertSharedFormulas(sharedFormula, 100, 200);
-
- RefPtg refPtg = (RefPtg) convertedFormula[1];
- assertEquals("$C101", refPtg.toFormulaString());
- assertNotEquals(Ptg.CLASS_REF, refPtg.getPtgClass(), "Identified bug 45123");
- confirmOperandClasses(sharedFormula, convertedFormula);
- }
-
- private static void confirmOperandClasses(Ptg[] originalPtgs, Ptg[] convertedPtgs) {
- int[] exp = Stream.of(originalPtgs).map(Ptg::getPtgClass).mapToInt(Byte::intValue).toArray();
- int[] act = Stream.of(convertedPtgs).map(Ptg::getPtgClass).mapToInt(Byte::intValue).toArray();
- assertArrayEquals(exp, act, "Different operand class");
- }
-
- @Test
- void testConvertSharedFormulas() {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFEvaluationWorkbook fpb = HSSFEvaluationWorkbook.create(wb);
- Ptg[] sharedFormula, convertedFormula;
-
- SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97);
-
- sharedFormula = FormulaParser.parse("A2", fpb, FormulaType.CELL, -1);
- convertedFormula = sf.convertSharedFormulas(sharedFormula, 0, 0);
- confirmOperandClasses(sharedFormula, convertedFormula);
- //conversion relative to [0,0] should return the original formula
- assertEquals("A2", FormulaRenderer.toFormulaString(fpb, convertedFormula));
-
- convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 0);
- confirmOperandClasses(sharedFormula, convertedFormula);
- //one row down
- assertEquals("A3", FormulaRenderer.toFormulaString(fpb, convertedFormula));
-
- convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 1);
- confirmOperandClasses(sharedFormula, convertedFormula);
- //one row down and one cell right
- assertEquals("B3", FormulaRenderer.toFormulaString(fpb, convertedFormula));
-
- sharedFormula = FormulaParser.parse("SUM(A1:C1)", fpb, FormulaType.CELL, -1);
- convertedFormula = sf.convertSharedFormulas(sharedFormula, 0, 0);
- confirmOperandClasses(sharedFormula, convertedFormula);
- assertEquals("SUM(A1:C1)", FormulaRenderer.toFormulaString(fpb, convertedFormula));
-
- convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 0);
- confirmOperandClasses(sharedFormula, convertedFormula);
- assertEquals("SUM(A2:C2)", FormulaRenderer.toFormulaString(fpb, convertedFormula));
-
- convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 1);
- confirmOperandClasses(sharedFormula, convertedFormula);
- assertEquals("SUM(B2:D2)", FormulaRenderer.toFormulaString(fpb, convertedFormula));
- }
-
- /**
- * Make sure that POI preserves {@link SharedFormulaRecord}s
- */
- @Test
- void testPreserveOnReserialize() {
- HSSFWorkbook wb;
- HSSFSheet sheet;
- HSSFCell cellB32769;
- HSSFCell cellC32769;
-
- // Reading directly from XLS file
- wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS);
- sheet = wb.getSheetAt(0);
- cellB32769 = sheet.getRow(32768).getCell(1);
- cellC32769 = sheet.getRow(32768).getCell(2);
- // check reading of formulas which are shared (two cells from a 1R x 8C range)
- assertEquals("B32770*2", cellB32769.getCellFormula());
- assertEquals("C32770*2", cellC32769.getCellFormula());
- confirmCellEvaluation(wb, cellB32769, 4);
- confirmCellEvaluation(wb, cellC32769, 6);
- // Confirm this example really does have SharedFormulas.
- // there are 3 others besides the one at A32769:H32769
- assertEquals(4, countSharedFormulas(sheet));
-
-
- // Re-serialize and check again
- wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sheet = wb.getSheetAt(0);
- cellB32769 = sheet.getRow(32768).getCell(1);
- cellC32769 = sheet.getRow(32768).getCell(2);
- assertEquals("B32770*2", cellB32769.getCellFormula());
- assertEquals("C32770*2", cellC32769.getCellFormula());
- confirmCellEvaluation(wb, cellB32769, 4);
- assertEquals(4, countSharedFormulas(sheet));
- }
-
- @Test
- void testUnshareFormulaDueToChangeFormula() {
- HSSFWorkbook wb;
- HSSFSheet sheet;
- HSSFCell cellB32769;
- HSSFCell cellC32769;
-
- wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS);
- sheet = wb.getSheetAt(0);
- cellB32769 = sheet.getRow(32768).getCell(1);
- cellC32769 = sheet.getRow(32768).getCell(2);
-
- // Updating cell formula, causing it to become unshared
- cellB32769.setCellFormula("1+1");
- confirmCellEvaluation(wb, cellB32769, 2);
- // currently (Oct 2008) POI handles this by exploding the whole shared formula group
- assertEquals(3, countSharedFormulas(sheet)); // one less now
- // check that nearby cell of the same group still has the same formula
- assertEquals("C32770*2", cellC32769.getCellFormula());
- confirmCellEvaluation(wb, cellC32769, 6);
- }
-
- @Test
- void testUnshareFormulaDueToDelete() {
- HSSFWorkbook wb;
- HSSFSheet sheet;
- HSSFCell cell;
- final int ROW_IX = 2;
-
- // changing shared formula cell to blank
- wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS);
- sheet = wb.getSheetAt(0);
-
- assertEquals("A$1*2", sheet.getRow(ROW_IX).getCell(1).getCellFormula());
- cell = sheet.getRow(ROW_IX).getCell(1);
- cell.setBlank();
- assertEquals(3, countSharedFormulas(sheet));
-
- wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sheet = wb.getSheetAt(0);
- assertEquals("A$1*2", sheet.getRow(ROW_IX+1).getCell(1).getCellFormula());
-
- // deleting shared formula cell
- wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS);
- sheet = wb.getSheetAt(0);
-
- assertEquals("A$1*2", sheet.getRow(ROW_IX).getCell(1).getCellFormula());
- cell = sheet.getRow(ROW_IX).getCell(1);
- sheet.getRow(ROW_IX).removeCell(cell);
- assertEquals(3, countSharedFormulas(sheet));
-
- wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sheet = wb.getSheetAt(0);
- assertEquals("A$1*2", sheet.getRow(ROW_IX+1).getCell(1).getCellFormula());
- }
-
- private static void confirmCellEvaluation(HSSFWorkbook wb, HSSFCell cell, double expectedValue) {
- HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
- CellValue cv = fe.evaluate(cell);
- assertEquals(CellType.NUMERIC, cv.getCellType());
- assertEquals(expectedValue, cv.getNumberValue(), 0.0);
- }
-
- /**
- * @return the number of {@link SharedFormulaRecord}s encoded for the specified sheet
- */
- private static int countSharedFormulas(HSSFSheet sheet) {
- int[] count = { 0 };
- sheet.getSheet().visitContainedRecords(r -> count[0] += r instanceof SharedFormulaRecord ? 1 : 0, 0);
- return count[0];
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java b/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java
deleted file mode 100644
index 18d345213e..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.IOException;
-
-import org.apache.poi.util.HexRead;
-import org.apache.poi.util.LittleEndian;
-import org.apache.poi.util.LittleEndianByteArrayInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the StringRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestStringRecord {
- private static final byte[] data = HexRead.readFromString(
- "0B 00 " + // length
- "00 " + // option
- // string
- "46 61 68 72 7A 65 75 67 74 79 70"
- );
-
- @Test
- void testLoad() {
-
- StringRecord record = new StringRecord(TestcaseRecordInputStream.create(0x207, data));
- assertEquals( "Fahrzeugtyp", record.getString());
-
- assertEquals( 18, record.getRecordSize() );
- }
-
- @Test
- void testStore() {
- StringRecord record = new StringRecord();
- record.setString("Fahrzeugtyp");
-
- byte [] recordBytes = record.serialize();
- assertEquals(recordBytes.length - 4, data.length);
- for (int i = 0; i < data.length; i++) {
- assertEquals(data[i], recordBytes[i+4], "At offset " + i);
- }
- }
-
- @Test
- void testContinue() throws IOException {
- int MAX_BIFF_DATA = RecordInputStream.MAX_RECORD_DATA_SIZE;
- int TEXT_LEN = MAX_BIFF_DATA + 1000; // deliberately over-size
- String textChunk = "ABCDEGGHIJKLMNOP"; // 16 chars
- StringBuilder sb = new StringBuilder(16384);
- while (sb.length() < TEXT_LEN) {
- sb.append(textChunk);
- }
- sb.setLength(TEXT_LEN);
-
- StringRecord sr = new StringRecord();
- sr.setString(sb.toString());
- byte[] ser = sr.serialize();
- assertEquals(StringRecord.sid, LittleEndian.getUShort(ser, 0));
- assertTrue(LittleEndian.getUShort(ser, 2) <= MAX_BIFF_DATA,
- "StringRecord should have been split with a continue record");
- // Confirm expected size of first record, and ushort strLen.
- assertEquals(MAX_BIFF_DATA, LittleEndian.getUShort(ser, 2));
- assertEquals(TEXT_LEN, LittleEndian.getUShort(ser, 4));
-
- // Confirm first few bytes of ContinueRecord
- LittleEndianByteArrayInputStream crIn = new LittleEndianByteArrayInputStream(ser, (MAX_BIFF_DATA + 4));
- int nCharsInFirstRec = MAX_BIFF_DATA - (2 + 1); // strLen, optionFlags
- int nCharsInSecondRec = TEXT_LEN - nCharsInFirstRec;
- assertEquals(ContinueRecord.sid, crIn.readUShort());
- assertEquals(1 + nCharsInSecondRec, crIn.readUShort());
- assertEquals(0, crIn.readUByte());
- assertEquals('N', crIn.readUByte());
- assertEquals('O', crIn.readUByte());
-
- // re-read and make sure string value is the same
- RecordInputStream in = TestcaseRecordInputStream.create(ser);
- StringRecord sr2 = new StringRecord(in);
- assertEquals(sb.toString(), sr2.getString());
- crIn.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java b/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java
deleted file mode 100644
index ed47560caf..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link StyleRecord}
- */
-final class TestStyleRecord {
- @Test
- void testUnicodeReadName() {
- byte[] data = HexRead.readFromString(
- "11 00 09 00 01 38 5E C4 89 5F 00 53 00 68 00 65 00 65 00 74 00 31 00");
- RecordInputStream in = TestcaseRecordInputStream.create(StyleRecord.sid, data);
- StyleRecord sr = new StyleRecord(in);
- assertEquals("\u5E38\u89C4_Sheet1", sr.getName()); // "_Sheet1"
- // bug 46385 - Incorrect number of bytes written - expected 27 but got 18
- byte[] ser = sr.serialize();
- confirmRecordEncoding(StyleRecord.sid, data, ser);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java
deleted file mode 100644
index b10800d5a3..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-
-package org.apache.poi.hssf.record;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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 java.util.Arrays;
-
-import org.apache.poi.util.HexRead;
-import org.apache.poi.util.LittleEndian;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests Subrecord components of an OBJ record. Test data taken directly
- * from a real Excel file.
- */
-final class TestSubRecord {
- /*
- The following is a dump of the OBJ record corresponding to an auto-filter
- drop-down list. The 3rd subrecord beginning at offset 0x002e (type=0x0013)
- does not conform to the documentation, because the length field is 0x1fee,
- which is longer than the entire OBJ record.
-
- 00000000 15 00 12 00 14 00 01 00 01 21 00 00 00 00 3C 13 .........!....<. Type=0x15 Len=0x0012 ftCmo
- 00000010 F4 03 00 00 00 00
- 0C 00 14 00 00 00 00 00 00 00 ................ Type=0x0c Len=0x0014 ftSbs
- 00000020 00 00 00 00 01 00 08 00 00 00 10 00 00 00
- 13 00 ................ Type=0x13 Len=0x1FEE ftLbsData
- 00000030 EE 1F 00 00 08 00 08 00 01 03 00 00 0A 00 14 00 ................
- 00000040 6C 00
- 00 00 00 00 l..... Type=0x00 Len=0x0000 ftEnd
- */
-
- private static final byte[] dataAutoFilter
- = HexRead.readFromString(""
- + "5D 00 46 00 " // ObjRecord.sid, size=70
- // ftCmo
- + "15 00 12 00 "
- + "14 00 01 00 01 00 01 21 00 00 3C 13 F4 03 00 00 00 00 "
- // ftSbs (currently UnknownSubrecord)
- + "0C 00 14 00 "
- + "00 00 00 00 00 00 00 00 00 00 01 00 08 00 00 00 10 00 00 00 "
- // ftLbsData (currently UnknownSubrecord)
- + "13 00 EE 1F 00 00 "
- + "08 00 08 00 01 03 00 00 0A 00 14 00 6C 00 "
- // ftEnd
- + "00 00 00 00"
- );
-
-
- /**
- * Make sure that ftLbsData (which has abnormal size info) is parsed correctly.
- * If the size field is interpreted incorrectly, the resulting ObjRecord becomes way too big.
- * At the time of fixing (Oct-2008 svn r707447) {@link RecordInputStream} allowed buffer
- * read overruns, so the bug was mostly silent.
- */
- @Test
- void testReadAll_bug45778() {
- RecordInputStream in = TestcaseRecordInputStream.create(dataAutoFilter);
- ObjRecord or = new ObjRecord(in);
- byte[] data2 = or.serialize();
- assertNotEquals(8228, data2.length, "Identified bug 45778");
- assertEquals(74, data2.length);
- assertArrayEquals(dataAutoFilter, data2);
- }
-
- @Test
- void testReadManualComboWithFormula() {
- byte[] data = HexRead.readFromString(""
- + "5D 00 66 00 "
- + "15 00 12 00 14 00 02 00 11 20 00 00 00 00 "
- + "20 44 C6 04 00 00 00 00 0C 00 14 00 04 F0 C6 04 "
- + "00 00 00 00 00 00 01 00 06 00 00 00 10 00 00 00 "
- + "0E 00 0C 00 05 00 80 44 C6 04 24 09 00 02 00 02 "
- + "13 00 DE 1F 10 00 09 00 80 44 C6 04 25 0A 00 0F "
- + "00 02 00 02 00 02 06 00 03 00 08 00 00 00 00 00 "
- + "08 00 00 00 00 00 00 00 " // TODO sometimes last byte is non-zero
- );
-
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- ObjRecord or = new ObjRecord(in);
- byte[] data2 = or.serialize();
- assertNotEquals(8228, data2.length, "Identified bug 45778");
- assertEquals(data.length, data2.length, "Encoded length");
- assertArrayEquals(data, data2, "Encoded data differs");
- }
-
- /**
- * Some versions of POI (e.g. 3.1 - prior to svn r707450 / bug 45778) interpreted the ftLbs
- * subrecord second short (0x1FEE) as a length, and hence read lots of extra padding. This
- * buffer-overrun in {@link RecordInputStream} happened silently due to problems later fixed
- * in svn 707778. When the ObjRecord is written, the extra padding is written too, making the
- * record 8224 bytes long instead of 70.
- * (An aside: It seems more than a coincidence that this problem creates a record of exactly
- * {@link RecordInputStream#MAX_RECORD_DATA_SIZE} but not enough is understood about
- * subrecords to explain this.)
- *
- * Excel reads files with this excessive padding OK. It also truncates the over-sized
- * ObjRecord back to the proper size. POI should do the same.
- */
- @Test
- void testWayTooMuchPadding_bug46545() {
- byte[] data = HexRead.readFromString(""
- + "15 00 12 00 14 00 13 00 01 21 00 00 00"
- + "00 98 0B 5B 09 00 00 00 00 0C 00 14 00 00 00 00 00 00 00 00"
- + "00 00 00 01 00 01 00 00 00 10 00 00 00 "
- // ftLbs
- + "13 00 EE 1F 00 00 "
- + "01 00 00 00 01 06 00 00 02 00 08 00 75 00 "
- // ftEnd
- + "00 00 00 00"
- );
- final int LBS_START_POS = 0x002E;
- final int WRONG_LBS_SIZE = 0x1FEE;
- assertEquals(0x0013, LittleEndian.getShort(data, LBS_START_POS));
- assertEquals(WRONG_LBS_SIZE, LittleEndian.getShort(data, LBS_START_POS+2));
- int wrongTotalSize = LBS_START_POS + 4 + WRONG_LBS_SIZE;
- byte[] wrongData = Arrays.copyOf(data, wrongTotalSize);
- // wrongData has the ObjRecord data as would have been written by v3.1
-
- RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, wrongData);
- // bug 46545 - Leftover 8154 bytes in subrecord data
- ObjRecord or = new ObjRecord(in);
- // make sure POI properly truncates the ObjRecord data
- byte[] data2 = or.serialize();
- confirmRecordEncoding(ObjRecord.sid, data, data2);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java
deleted file mode 100644
index 1766c514dd..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.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.hssf.record;
-
-
-import static org.apache.poi.hssf.record.SupBookRecord.CH_ALT_STARTUP_DIR;
-import static org.apache.poi.hssf.record.SupBookRecord.CH_DOWN_DIR;
-import static org.apache.poi.hssf.record.SupBookRecord.CH_LIB_DIR;
-import static org.apache.poi.hssf.record.SupBookRecord.CH_SAME_VOLUME;
-import static org.apache.poi.hssf.record.SupBookRecord.CH_STARTUP_DIR;
-import static org.apache.poi.hssf.record.SupBookRecord.CH_UP_DIR;
-import static org.apache.poi.hssf.record.SupBookRecord.CH_VOLUME;
-import static org.apache.poi.hssf.record.SupBookRecord.PATH_SEPERATOR;
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the SupBook record
- * class works correctly.
- */
-final class TestSupBookRecord {
- /**
- * This contains a fake data section of a SubBookRecord
- */
- byte[] dataIR = new byte[] {
- (byte)0x04,(byte)0x00,(byte)0x01,(byte)0x04,
- };
- byte[] dataAIF = new byte[] {
- (byte)0x01,(byte)0x00,(byte)0x01,(byte)0x3A,
- };
- byte[] dataER = new byte[] {
- (byte)0x02,(byte)0x00,
- (byte)0x07,(byte)0x00, (byte)0x00,
- (byte)'t', (byte)'e', (byte)'s', (byte)'t', (byte)'U', (byte)'R', (byte)'L',
- (byte)0x06,(byte)0x00, (byte)0x00,
- (byte)'S', (byte)'h', (byte)'e', (byte)'e', (byte)'t', (byte)'1',
- (byte)0x06,(byte)0x00, (byte)0x00,
- (byte)'S', (byte)'h', (byte)'e', (byte)'e', (byte)'t', (byte)'2',
- };
-
- /**
- * tests that we can load the record
- */
- @Test
- void testLoadIR() {
- SupBookRecord record = new SupBookRecord(TestcaseRecordInputStream.create(0x01AE, dataIR));
- assertTrue( record.isInternalReferences() ); //expected flag
- assertEquals( 0x4, record.getNumberOfSheets() ); //expected # of sheets
-
- assertEquals( 8, record.getRecordSize() ); //sid+size+data
- }
-
- /**
- * tests that we can load the record
- */
- @Test
- void testLoadER() {
- SupBookRecord record = new SupBookRecord(TestcaseRecordInputStream.create(0x01AE, dataER));
- assertTrue( record.isExternalReferences() ); //expected flag
- assertEquals( 0x2, record.getNumberOfSheets() ); //expected # of sheets
-
- assertEquals( 34, record.getRecordSize() ); //sid+size+data
-
- assertEquals("testURL", record.getURL());
- String[] sheetNames = record.getSheetNames();
- assertEquals(2, sheetNames.length);
- assertEquals("Sheet1", sheetNames[0]);
- assertEquals("Sheet2", sheetNames[1]);
- }
-
- /**
- * tests that we can load the record
- */
- @Test
- void testLoadAIF() {
- SupBookRecord record = new SupBookRecord(TestcaseRecordInputStream.create(0x01AE, dataAIF));
- assertTrue( record.isAddInFunctions() ); //expected flag
- assertEquals( 0x1, record.getNumberOfSheets() ); //expected # of sheets
- assertEquals( 8, record.getRecordSize() ); //sid+size+data
- }
-
- /**
- * Tests that we can store the record
- */
- @SuppressWarnings("squid:S2699")
- @Test
- void testStoreIR() {
- SupBookRecord record = SupBookRecord.createInternalReferences((short)4);
-
- confirmRecordEncoding(0x01AE, dataIR, record.serialize());
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStoreER() {
- String url = "testURL";
- String[] sheetNames = { "Sheet1", "Sheet2", };
- SupBookRecord record = SupBookRecord.createExternalReferences(url, sheetNames);
-
- confirmRecordEncoding(0x01AE, dataER, record.serialize());
- }
-
- @Test
- void testStoreAIF() {
- SupBookRecord record = SupBookRecord.createAddInFunctions();
- assertEquals(1, record.getNumberOfSheets());
- assertTrue(record.isAddInFunctions());
- confirmRecordEncoding(0x01AE, dataAIF, record.serialize());
- }
-
- @Test
- void testExternalReferenceUrl() {
- String[] sheetNames = new String[]{"SampleSheet"};
- final char startMarker = (char)1;
-
- SupBookRecord record;
-
- record = new SupBookRecord(startMarker + "test.xls", sheetNames);
- assertEquals("test.xls", record.getURL());
-
- //UNC path notation
- record = new SupBookRecord(startMarker + "" + CH_VOLUME + "@servername" + CH_DOWN_DIR + "test.xls", sheetNames);
- assertEquals("\\\\servername" + PATH_SEPERATOR + "test.xls", record.getURL());
-
- //Absolute path notation - different device
- record = new SupBookRecord(startMarker + "" + CH_VOLUME + "D" + CH_DOWN_DIR + "test.xls", sheetNames);
- assertEquals("D:" + PATH_SEPERATOR + "test.xls", record.getURL());
-
- //Absolute path notation - same device
- record = new SupBookRecord(startMarker + "" + CH_SAME_VOLUME + "folder" + CH_DOWN_DIR + "test.xls", sheetNames);
- assertEquals(PATH_SEPERATOR + "folder" + PATH_SEPERATOR + "test.xls", record.getURL());
-
- //Relative path notation - down
- record = new SupBookRecord(startMarker + "folder" + CH_DOWN_DIR + "test.xls", sheetNames);
- assertEquals("folder" + PATH_SEPERATOR + "test.xls", record.getURL());
-
- //Relative path notation - up
- record = new SupBookRecord(startMarker +""+ CH_UP_DIR + "test.xls", sheetNames);
- assertEquals(".." + PATH_SEPERATOR + "test.xls", record.getURL());
-
- //Relative path notation - for EXCEL.exe - fallback
- record = new SupBookRecord(startMarker +""+ CH_STARTUP_DIR + "test.xls", sheetNames);
- assertEquals("." + PATH_SEPERATOR + "test.xls", record.getURL());
-
- //Relative path notation - for EXCEL lib folder - fallback
- record = new SupBookRecord(startMarker +""+ CH_LIB_DIR + "test.xls", sheetNames);
- assertEquals("." + PATH_SEPERATOR + "test.xls", record.getURL());
-
- //Relative path notation - for alternative EXCEL.exe - fallback
- record = new SupBookRecord(startMarker +""+ CH_ALT_STARTUP_DIR+ "test.xls", sheetNames);
- assertEquals("." + PATH_SEPERATOR + "test.xls", record.getURL());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java
deleted file mode 100644
index 58cd682df2..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.util.CellRangeAddress8Bit;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the TableRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestTableRecord {
- byte[] header = new byte[] {
- 0x36, 02, 0x10, 00, // sid=x236, 16 bytes long
- };
- byte[] data = new byte[] {
- 03, 00, // from row 3
- 8, 00, // to row 8
- 04, // from col 4
- 06, // to col 6
- 00, 00, // no flags set
- 04, 00, // row inp row 4
- 01, 00, // col inp row 1
- 0x76, 0x40, // row inp col 0x4076 (!)
- 00, 00 // col inp col 0
- };
-
- @Test
- void testLoad() {
-
- TableRecord record = new TableRecord(TestcaseRecordInputStream.create(0x236, data));
-
- CellRangeAddress8Bit range = record.getRange();
- assertEquals(3, range.getFirstRow());
- assertEquals(8, range.getLastRow());
- assertEquals(4, range.getFirstColumn());
- assertEquals(6, range.getLastColumn());
- assertEquals(0, record.getFlags());
- assertEquals(4, record.getRowInputRow());
- assertEquals(1, record.getColInputRow());
- assertEquals(0x4076, record.getRowInputCol());
- assertEquals(0, record.getColInputCol());
-
- assertEquals( 16 + 4, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore()
- {
-// Offset 0x3bd9 (15321)
-// recordid = 0x236, size = 16
-// [TABLE]
-// .row from = 3
-// .row to = 8
-// .column from = 4
-// .column to = 6
-// .flags = 0
-// .always calc =false
-// .reserved = 0
-// .row input row = 4
-// .col input row = 1
-// .row input col = 4076
-// .col input col = 0
-// [/TABLE]
-
- CellRangeAddress8Bit crab = new CellRangeAddress8Bit(3, 8, 4, 6);
- TableRecord record = new TableRecord(crab);
- record.setFlags((byte)0);
- record.setRowInputRow(4);
- record.setColInputRow(1);
- record.setRowInputCol(0x4076);
- record.setColInputCol(0);
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(TableRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java
deleted file mode 100644
index 6af2622dcb..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.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.hssf.record;
-
-
-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 org.apache.poi.hssf.usermodel.HSSFRichTextString;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the TextObjectBaseRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestTextObjectBaseRecord {
- /** data for one TXO rec and two continue recs */
- private static final byte[] data = HexRead.readFromString(
- "B6 01 " + // TextObjectRecord.sid
- "12 00 " + // size 18
- "44 02 02 00 00 00 00 00" +
- "00 00 " +
- "02 00 " + // strLen 2
- "10 00 " + // 16 bytes for 2 format runs
- "00 00" +
- "00 00 " +
- "3C 00 " + // ContinueRecord.sid
- "03 00 " + // size 3
- "00 " + // unicode compressed
- "41 42 " + // 'AB'
- "3C 00 " + // ContinueRecord.sid
- "10 00 " + // size 16
- "00 00 18 00 00 00 00 00 " +
- "02 00 00 00 00 00 00 00 "
- );
-
- @Test
- void testLoad() {
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- TextObjectRecord record = new TextObjectRecord(in);
-
- assertEquals(TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_CENTERED, record.getHorizontalTextAlignment());
- assertEquals(TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_JUSTIFY, record.getVerticalTextAlignment());
- assertTrue(record.isTextLocked());
- assertEquals(TextObjectRecord.TEXT_ORIENTATION_ROT_RIGHT, record.getTextOrientation());
-
- assertEquals(49, record.getRecordSize() );
- }
-
- @Test
- void testStore() {
- TextObjectRecord record = new TextObjectRecord();
-
- HSSFRichTextString str = new HSSFRichTextString("AB");
- str.applyFont(0, 2, (short)0x0018);
- str.applyFont(2, 2, (short)0x0320);
-
- record.setHorizontalTextAlignment(TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_CENTERED);
- record.setVerticalTextAlignment(TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_JUSTIFY);
- record.setTextLocked(true);
- record.setTextOrientation(TextObjectRecord.TEXT_ORIENTATION_ROT_RIGHT);
- record.setStr(str);
-
- byte [] recordBytes = record.serialize();
- assertArrayEquals(data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java
deleted file mode 100644
index 272b1802e1..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.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.hssf.record;
-
-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.ByteArrayInputStream;
-
-import org.apache.poi.hssf.usermodel.HSSFRichTextString;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.formula.ptg.RefPtg;
-import org.apache.poi.util.HexRead;
-import org.apache.poi.util.LittleEndian;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests that serialization and deserialization of the TextObjectRecord .
- * Test data taken directly from a real Excel file.
- *
- * @author Yegor Kozlov
- */
-final class TestTextObjectRecord {
-
- private static final byte[] simpleData = HexRead.readFromString(
- "B6 01 12 00 " +
- "12 02 00 00 00 00 00 00" +
- "00 00 0D 00 08 00 00 00" +
- "00 00 " +
- "3C 00 0E 00 " +
- "00 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 " +
- "3C 00 08 " +
- "00 0D 00 00 00 00 00 00 00"
- );
-
- @Test
- void testRead() {
-
- RecordInputStream is =TestcaseRecordInputStream.create(simpleData);
- TextObjectRecord record = new TextObjectRecord(is);
-
- assertEquals(TextObjectRecord.sid, record.getSid());
- assertEquals(TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED, record.getHorizontalTextAlignment());
- assertEquals(TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_TOP, record.getVerticalTextAlignment());
- assertEquals(TextObjectRecord.TEXT_ORIENTATION_NONE, record.getTextOrientation());
- assertEquals("Hello, World!", record.getStr().getString());
- }
-
- @Test
- void testWrite() {
- HSSFRichTextString str = new HSSFRichTextString("Hello, World!");
-
- TextObjectRecord record = new TextObjectRecord();
- record.setStr(str);
- record.setHorizontalTextAlignment( TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED );
- record.setVerticalTextAlignment( TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_TOP );
- record.setTextLocked( true );
- record.setTextOrientation( TextObjectRecord.TEXT_ORIENTATION_NONE );
-
- byte [] ser = record.serialize();
- assertEquals(ser.length , simpleData.length);
-
- assertArrayEquals(simpleData, ser);
-
- //read again
- RecordInputStream is = TestcaseRecordInputStream.create(simpleData);
- record = new TextObjectRecord(is);
- assertNotNull(record);
- }
-
- /**
- * Zero {@link ContinueRecord}s follow a {@link TextObjectRecord} if the text is empty
- */
- @Test
- void testWriteEmpty() {
- HSSFRichTextString str = new HSSFRichTextString("");
-
- TextObjectRecord record = new TextObjectRecord();
- record.setStr(str);
-
- byte [] ser = record.serialize();
-
- int formatDataLen = LittleEndian.getUShort(ser, 16);
- assertEquals(0, formatDataLen, "formatDataLength");
-
- assertEquals(22, ser.length); // just the TXO record
-
- //read again
- RecordInputStream is = TestcaseRecordInputStream.create(ser);
- record = new TextObjectRecord(is);
- assertEquals(0, record.getStr().length());
- }
-
- /**
- * Test that TextObjectRecord serializes logs records properly.
- */
- @Test
- void testLongRecords() {
- int[] lengths = {1024, 2048, 4096, 8192, 16384}; //test against strings of different length
- for (int length : lengths) {
- StringBuilder buff = new StringBuilder(length);
- for (int j = 0; j < length; j++) {
- buff.append("x");
- }
- HSSFRichTextString str = new HSSFRichTextString(buff.toString());
-
- TextObjectRecord obj = new TextObjectRecord();
- obj.setStr(str);
-
- byte [] data = obj.serialize();
- RecordInputStream is = new RecordInputStream(new ByteArrayInputStream(data));
- is.nextRecord();
- TextObjectRecord record = new TextObjectRecord(is);
- str = record.getStr();
-
- assertEquals(buff.length(), str.length());
- assertEquals(buff.toString(), str.getString());
- }
- }
-
- /**
- * Test cloning
- */
- @Test
- void testClone() {
- String text = "Hello, World";
- HSSFRichTextString str = new HSSFRichTextString(text);
-
- TextObjectRecord obj = new TextObjectRecord();
- obj.setStr( str );
-
-
- TextObjectRecord cloned = obj.copy();
- assertEquals(obj.getRecordSize(), cloned.getRecordSize());
- assertEquals(obj.getHorizontalTextAlignment(), cloned.getHorizontalTextAlignment());
- assertEquals(obj.getStr().getString(), cloned.getStr().getString());
-
- //finally check that the serialized data is the same
- byte[] src = obj.serialize();
- byte[] cln = cloned.serialize();
- assertArrayEquals(src, cln);
- }
-
- /** similar to {@link #simpleData} but with link formula at end of TXO rec*/
- private static final byte[] linkData = HexRead.readFromString(
- "B6 01 " + // TextObjectRecord.sid
- "1E 00 " + // size 18
- "44 02 02 00 00 00 00 00" +
- "00 00 " +
- "02 00 " + // strLen 2
- "10 00 " + // 16 bytes for 2 format runs
- "00 00 00 00 " +
-
- "05 00 " + // formula size
- "D4 F0 8A 03 " + // unknownInt
- "24 01 00 13 C0 " + //tRef(T2)
- "13 " + // ??
-
- "3C 00 " + // ContinueRecord.sid
- "03 00 " + // size 3
- "00 " + // unicode compressed
- "41 42 " + // 'AB'
- "3C 00 " + // ContinueRecord.sid
- "10 00 " + // size 16
- "00 00 18 00 00 00 00 00 " +
- "02 00 00 00 00 00 00 00 "
- );
-
- @Test
- void testLinkFormula() {
- RecordInputStream is = new RecordInputStream(new ByteArrayInputStream(linkData));
- is.nextRecord();
- TextObjectRecord rec = new TextObjectRecord(is);
-
- Ptg ptg = rec.getLinkRefPtg();
- assertNotNull(ptg);
- assertEquals(RefPtg.class, ptg.getClass());
- RefPtg rptg = (RefPtg) ptg;
- assertEquals("T2", rptg.toFormulaString());
-
- byte [] data2 = rec.serialize();
- assertEquals(linkData.length, data2.length);
- assertArrayEquals(linkData, data2);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java
deleted file mode 100644
index 773b8666c1..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.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.hssf.record;
-
-
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import java.io.IOException;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.junit.jupiter.api.Test;
-
-final class TestUnicodeNameRecord {
-
- @Test
- void testReadBook() throws IOException {
- // This bit used to crash
- try (HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("unicodeNameRecord.xls")) {
- HSSFSheet sheet = book.getSheetAt(0);
- assertNotNull(sheet);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java b/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java
deleted file mode 100644
index 364e478932..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link WriteAccessRecord}
- */
-final class TestWriteAccessRecord {
-
- private static final String HEX_SIXTYFOUR_SPACES = ""
- + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
- + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
- + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
- + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20";
-
- @Test
- void testMissingStringHeader_bug47001a() {
- /*
- * Data taken from offset 0x0224 in
- * attachment 23468 from bugzilla 47001
- */
- byte[] data = HexRead.readFromString(""
- + "5C 00 70 00 "
- + "4A 61 76 61 20 45 78 63 65 6C 20 41 50 49 20 76 "
- + "32 2E 36 2E 34"
- + "20 20 20 20 20 20 20 20 20 20 20 "
- + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
- + HEX_SIXTYFOUR_SPACES);
-
- RecordInputStream in = TestcaseRecordInputStream.create(data);
-
- // bug 47001a - Not enough data (0) to read requested (1) bytes
- WriteAccessRecord rec = new WriteAccessRecord(in);
- assertEquals("Java Excel API v2.6.4", rec.getUsername());
-
-
- byte[] expectedEncoding = HexRead.readFromString(""
- + "15 00 00 4A 61 76 61 20 45 78 63 65 6C 20 41 50 "
- + "49 20 76 32 2E 36 2E 34"
- + "20 20 20 20 20 20 20 20 "
- + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 "
- + HEX_SIXTYFOUR_SPACES);
-
- confirmRecordEncoding(WriteAccessRecord.sid, expectedEncoding, rec.serialize());
- }
-
- @Test
- void testShortRecordWrittenByMSAccess() {
- /*
- * Data taken from two example files
- * ex42564-21435.xls
- * bug_42794.xls (from bug 42794 attachment 20429)
- * In both cases, this data is found at offset 0x0C1C.
- */
- byte[] data = HexRead.readFromString(""
- + "5C 00 39 00 "
- + "36 00 00 41 20 73 61 74 69 73 66 69 65 64 20 4D "
- + "69 63 72 6F 73 6F 66 74 20 4F 66 66 69 63 65 39 "
- + "20 55 73 65 72"
- + "20 20 20 20 20 20 20 20 20 20 20 "
- + "20 20 20 20 20 20 20 20 20");
-
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- WriteAccessRecord rec = new WriteAccessRecord(in);
- assertEquals("A satisfied Microsoft Office9 User", rec.getUsername());
- byte[] expectedEncoding = HexRead.readFromString(""
- + "22 00 00 41 20 73 61 74 69 73 66 69 65 64 20 4D "
- + "69 63 72 6F 73 6F 66 74 20 4F 66 66 69 63 65 39 "
- + "20 55 73 65 72"
- + "20 20 20 20 20 20 20 20 20 20 20 "
- + HEX_SIXTYFOUR_SPACES);
-
- confirmRecordEncoding(WriteAccessRecord.sid, expectedEncoding, rec.serialize());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java
deleted file mode 100644
index 93c62912a9..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record;
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.Arrays;
-
-import org.apache.poi.util.LittleEndian;
-import org.apache.poi.util.LittleEndianByteArrayInputStream;
-import org.apache.poi.util.LittleEndianInput;
-
-/**
- * A Record Input Stream derivative that makes access to byte arrays used in the
- * test cases work a bit easier.
- * Creates the stream and moves to the first record.
- *
- * @author Jason Height (jheight at apache.org)
- */
-public final class TestcaseRecordInputStream {
-
- private TestcaseRecordInputStream() {
- // no instances of this class
- }
-
- /**
- * Prepends a mock record identifier to the supplied data and opens a record input stream
- */
- public static LittleEndianInput createLittleEndian(byte[] data) {
- return new LittleEndianByteArrayInputStream(data);
-
- }
- public static RecordInputStream create(int sid, byte[] data) {
- return create(mergeDataAndSid(sid, data.length, data));
- }
- /**
- * First 4 bytes of data are assumed to be record identifier and length. The supplied
- * data can contain multiple records (sequentially encoded in the same way)
- */
- public static RecordInputStream create(byte[] data) {
- InputStream is = new ByteArrayInputStream(data);
- RecordInputStream result = new RecordInputStream(is);
- result.nextRecord();
- return result;
- }
-
- public static byte[] mergeDataAndSid(int sid, int length, byte[] data) {
- byte[] result = new byte[data.length + 4];
- LittleEndian.putUShort(result, 0, sid);
- LittleEndian.putUShort(result, 2, length);
- System.arraycopy(data, 0, result, 4, data.length);
- return result;
- }
- /**
- * Confirms data sections are equal
- * @param expectedData - just raw data (without sid or size short ints)
- * @param actualRecordBytes this includes 4 prefix bytes (sid & size)
- */
- public static void confirmRecordEncoding(int expectedSid, byte[] expectedData, byte[] actualRecordBytes) {
- confirmRecordEncoding(null, expectedSid, expectedData, actualRecordBytes);
- }
- /**
- * Confirms data sections are equal
- * @param msgPrefix message prefix to be displayed in case of failure
- * @param expectedData - just raw data (without ushort sid, ushort size)
- * @param actualRecordBytes this includes 4 prefix bytes (sid & size)
- */
- public static void confirmRecordEncoding(String msgPrefix, int expectedSid, byte[] expectedData, byte[] actualRecordBytes) {
- int expectedDataSize = expectedData.length;
- assertEquals(actualRecordBytes.length - 4, expectedDataSize, "Size of encode data mismatch");
- assertEquals(expectedSid, LittleEndian.getShort(actualRecordBytes, 0));
- assertEquals(expectedDataSize, LittleEndian.getShort(actualRecordBytes, 2));
- assertArrayEquals(expectedData, cut(actualRecordBytes, 4));
- }
-
- public static byte[] cut( byte[] data, int fromInclusive ) {
- return cut(data, fromInclusive, data.length);
- }
-
- public static byte[] cut(byte[] data, int fromInclusive, int toExclusive) {
- return Arrays.copyOfRange(data, fromInclusive, toExclusive);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java
deleted file mode 100644
index b400b76c24..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.aggregates;
-
-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.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.poi.hssf.model.RecordStream;
-import org.apache.poi.hssf.record.CFHeaderBase;
-import org.apache.poi.hssf.record.CFHeaderRecord;
-import org.apache.poi.hssf.record.CFRule12Record;
-import org.apache.poi.hssf.record.CFRuleBase;
-import org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator;
-import org.apache.poi.hssf.record.CFRuleRecord;
-import org.apache.poi.hssf.record.RecordFactory;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.apache.poi.util.LittleEndian;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the CFRecordsAggregate
- * class works correctly.
- */
-@SuppressWarnings("resource")
-final class TestCFRecordsAggregate {
- @Test
- void testCFRecordsAggregate() {
- HSSFWorkbook workbook = new HSSFWorkbook();
- HSSFSheet sheet = workbook.createSheet();
-
- List recs = new ArrayList<>();
- CFHeaderBase header = new CFHeaderRecord();
- CFRuleBase rule1 = CFRuleRecord.create(sheet, "7");
- CFRuleBase rule2 = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5");
- CFRuleBase rule3 = CFRuleRecord.create(sheet, ComparisonOperator.GE, "100", null);
- header.setNumberOfConditionalFormats(3);
- CellRangeAddress[] cellRanges = {
- new CellRangeAddress(0,1,0,0),
- new CellRangeAddress(0,1,2,2),
- };
- header.setCellRanges(cellRanges);
- recs.add(header);
- recs.add(rule1);
- recs.add(rule2);
- recs.add(rule3);
- CFRecordsAggregate record = CFRecordsAggregate.createCFAggregate(new RecordStream(recs, 0));
-
- // Serialize
- byte [] serializedRecord = new byte[record.getRecordSize()];
- record.serialize(0, serializedRecord);
- InputStream in = new ByteArrayInputStream(serializedRecord);
-
- //Parse
- recs = RecordFactory.createRecords(in);
-
- // Verify
- assertNotNull(recs);
- assertEquals(4, recs.size());
-
- header = (CFHeaderRecord)recs.get(0);
- rule1 = (CFRuleRecord)recs.get(1);
- assertNotNull(rule1);
- rule2 = (CFRuleRecord)recs.get(2);
- assertNotNull(rule2);
- rule3 = (CFRuleRecord)recs.get(3);
- assertNotNull(rule3);
- cellRanges = header.getCellRanges();
-
- assertEquals(2, cellRanges.length);
- assertEquals(3, header.getNumberOfConditionalFormats());
- assertFalse(header.getNeedRecalculation());
-
- record = CFRecordsAggregate.createCFAggregate(new RecordStream(recs, 0));
-
- record = record.cloneCFAggregate();
-
- assertNotNull(record.getHeader());
- assertEquals(3,record.getNumberOfRules());
-
- header = record.getHeader();
- rule1 = record.getRule(0);
- assertNotNull(rule1);
- rule2 = record.getRule(1);
- assertNotNull(rule2);
- rule3 = record.getRule(2);
- assertNotNull(rule3);
- cellRanges = header.getCellRanges();
-
- assertEquals(2, cellRanges.length);
- assertEquals(3, header.getNumberOfConditionalFormats());
- assertFalse(header.getNeedRecalculation());
- }
-
- /**
- * Make sure that the CF Header record is properly updated with the number of rules
- */
- @Test
- void testNRules() {
- HSSFWorkbook workbook = new HSSFWorkbook();
- HSSFSheet sheet = workbook.createSheet();
- CellRangeAddress[] cellRanges = {
- new CellRangeAddress(0,1,0,0),
- new CellRangeAddress(0,1,2,2),
- };
- CFRuleRecord[] rules = {
- CFRuleRecord.create(sheet, "7"),
- CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5"),
- };
- CFRecordsAggregate agg = new CFRecordsAggregate(cellRanges, rules);
- byte[] serializedRecord = new byte[agg.getRecordSize()];
- agg.serialize(0, serializedRecord);
-
- int nRules = LittleEndian.getUShort(serializedRecord, 4);
- assertNotEquals(0, nRules, "Identified bug 45682 b");
- assertEquals(rules.length, nRules);
- }
-
- @Test
- void testCantMixTypes() {
- HSSFWorkbook workbook = new HSSFWorkbook();
- HSSFSheet sheet = workbook.createSheet();
- CellRangeAddress[] cellRanges = {
- new CellRangeAddress(0,1,0,0),
- new CellRangeAddress(0,1,2,2),
- };
- CFRuleBase[] rules1 = {
- CFRuleRecord.create(sheet, "7"),
- CFRule12Record.create(sheet, ComparisonOperator.BETWEEN, "2", "5"),
- };
-
- assertThrows(IllegalArgumentException.class, () -> new CFRecordsAggregate(cellRanges, rules1),
- "Shouldn't be able to mix between types");
-
-
- CFRuleBase[] rules2 = { CFRuleRecord.create(sheet, "7") };
- CFRecordsAggregate agg = new CFRecordsAggregate(cellRanges, rules2);
- assertTrue(agg.getHeader().getNeedRecalculation());
-
- assertThrows(IllegalArgumentException.class, () -> agg.addRule(CFRule12Record.create(sheet, "7")),
- "Shouldn't be able to mix between types");
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.java
deleted file mode 100644
index 6fae73f041..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.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.hssf.record.aggregates;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.poi.hssf.record.ColumnInfoRecord;
-import org.apache.poi.hssf.record.RecordBase;
-import org.junit.jupiter.api.Test;
-
-final class TestColumnInfoRecordsAggregate {
-
- @Test
- void testGetRecordSize() {
- ColumnInfoRecordsAggregate agg = new ColumnInfoRecordsAggregate();
- agg.insertColumn(createColInfo(1, 3));
- agg.insertColumn(createColInfo(4, 7));
- agg.insertColumn(createColInfo(8, 8));
- agg.groupColumnRange((short) 2, (short) 5, true);
- assertEquals(4, agg.getNumColumns());
-
- confirmSerializedSize(agg);
-
- agg = new ColumnInfoRecordsAggregate();
- agg.groupColumnRange((short) 3, (short) 6, true);
- confirmSerializedSize(agg);
- }
-
- private static void confirmSerializedSize(RecordBase cirAgg) {
- int estimatedSize = cirAgg.getRecordSize();
- byte[] buf = new byte[estimatedSize];
- int serializedSize = cirAgg.serialize(0, buf);
- assertEquals(estimatedSize, serializedSize);
- }
-
- private static ColumnInfoRecord createColInfo(int firstCol, int lastCol) {
- ColumnInfoRecord columnInfoRecord = new ColumnInfoRecord();
- columnInfoRecord.setFirstColumn((short) firstCol);
- columnInfoRecord.setLastColumn((short) lastCol);
- return columnInfoRecord;
- }
-
- @Test
- void testGroupColumns_bug45639() {
- ColumnInfoRecordsAggregate agg = new ColumnInfoRecordsAggregate();
- agg.groupColumnRange( 7, 9, true);
- agg.groupColumnRange( 4, 12, true);
-
- // bug 45639 - ArrayIndexOutOfBoundsException
- agg.groupColumnRange( 1, 15, true);
-
- List cirs = new ArrayList<>();
- agg.visitContainedRecords(cirs::add);
-
- assertEquals(5, cirs.size());
- confirmCIR(cirs, 0, 1, 3, 1, false, false);
- confirmCIR(cirs, 1, 4, 6, 2, false, false);
- confirmCIR(cirs, 2, 7, 9, 3, false, false);
- confirmCIR(cirs, 3, 10, 12, 2, false, false);
- confirmCIR(cirs, 4, 13, 15, 1, false, false);
- }
-
- /**
- * Check that an inner group remains hidden
- */
- @Test
- void testHiddenAfterExpanding() {
- ColumnInfoRecordsAggregate agg = new ColumnInfoRecordsAggregate();
- agg.groupColumnRange(1, 15, true);
- agg.groupColumnRange(4, 12, true);
-
- List cirs = new ArrayList<>();
-
- // collapse both inner and outer groups
- agg.collapseColumn(6);
- agg.collapseColumn(3);
-
- agg.visitContainedRecords(cirs::add);
- assertEquals(5, cirs.size());
- confirmCIR(cirs, 0, 1, 3, 1, true, false);
- confirmCIR(cirs, 1, 4, 12, 2, true, false);
- confirmCIR(cirs, 2, 13, 13, 1, true, true);
- confirmCIR(cirs, 3, 14, 15, 1, true, false);
- confirmCIR(cirs, 4, 16, 16, 0, false, true);
-
- // just expand the inner group
- agg.expandColumn(6);
-
- cirs.clear();
- agg.visitContainedRecords(cirs::add);
- assertEquals(4, cirs.size());
- assertTrue(((ColumnInfoRecord)cirs.get(1)).getHidden(), "Inner group should still be hidden");
- confirmCIR(cirs, 0, 1, 3, 1, true, false);
- confirmCIR(cirs, 1, 4, 12, 2, true, false);
- confirmCIR(cirs, 2, 13, 15, 1, true, false);
- confirmCIR(cirs, 3, 16, 16, 0, false, true);
- }
-
- private static void confirmCIR(List cirs, int ix, int startColIx, int endColIx, int level, boolean isHidden, boolean isCollapsed) {
- assertTrue(cirs.get(ix) instanceof ColumnInfoRecord);
- ColumnInfoRecord cir = (ColumnInfoRecord)cirs.get(ix);
- assertEquals(startColIx, cir.getFirstColumn(), "startColIx");
- assertEquals(endColIx, cir.getLastColumn(), "endColIx");
- assertEquals(level, cir.getOutlineLevel(), "level");
- assertEquals(isHidden, cir.getHidden(), "hidden");
- assertEquals(isCollapsed, cir.getCollapsed(), "collapsed");
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.java
deleted file mode 100644
index 8bfc6576c2..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.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.hssf.record.aggregates;
-
-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.ArrayList;
-import java.util.List;
-
-import org.apache.poi.hssf.model.HSSFFormulaParser;
-import org.apache.poi.hssf.record.FormulaRecord;
-import org.apache.poi.hssf.record.StringRecord;
-import org.apache.poi.ss.formula.FormulaRenderer;
-import org.apache.poi.ss.formula.FormulaType;
-import org.apache.poi.ss.formula.ptg.ExpPtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.junit.jupiter.api.Test;
-
-final class TestFormulaRecordAggregate {
-
- @Test
- void testBasic() {
- FormulaRecord f = new FormulaRecord();
- f.setCachedResultTypeString();
- StringRecord s = new StringRecord();
- s.setString("abc");
- FormulaRecordAggregate fagg = new FormulaRecordAggregate(f, s, SharedValueManager.createEmpty());
- assertEquals("abc", fagg.getStringValue());
- assertFalse(fagg.isPartOfArrayFormula());
- }
-
- /**
- * Sometimes a {@link StringRecord} appears after a {@link FormulaRecord} even though the
- * formula has evaluated to a text value. This might be more likely to occur when the formula
- * can evaluate to a text value.
- * Bug 46213 attachment 22874 has such an extra {@link StringRecord} at stream offset 0x5765.
- * This file seems to open in Excel (2007) with no trouble. When it is re-saved, Excel omits
- * the extra record. POI should do the same.
- */
- @Test
- void testExtraStringRecord_bug46213() {
- FormulaRecord fr = new FormulaRecord();
- fr.setValue(2.0);
- StringRecord sr = new StringRecord();
- sr.setString("NA");
- SharedValueManager svm = SharedValueManager.createEmpty();
- // bug 46213 -> String record was supplied but formula record flag is not set
- FormulaRecordAggregate fra = new FormulaRecordAggregate(fr, sr, svm);
- List vraRecs = new ArrayList<>();
- fra.visitContainedRecords(vraRecs::add);
- assertEquals(1, vraRecs.size());
- assertEquals(fr, vraRecs.get(0));
- }
-
- @Test
- void testArrayFormulas() {
- int rownum = 4;
- int colnum = 4;
-
- FormulaRecord fr = new FormulaRecord();
- fr.setRow(rownum);
- fr.setColumn((short)colnum);
-
- FormulaRecordAggregate agg = new FormulaRecordAggregate(fr, null, SharedValueManager.createEmpty());
- Ptg[] ptgsForCell = {new ExpPtg(rownum, colnum)};
- agg.setParsedExpression(ptgsForCell);
-
- String formula = "SUM(A1:A3*B1:B3)";
- Ptg[] ptgs = HSSFFormulaParser.parse(formula, null, FormulaType.ARRAY, 0);
- agg.setArrayFormula(new CellRangeAddress(rownum, rownum, colnum, colnum), ptgs);
-
- assertTrue(agg.isPartOfArrayFormula());
- assertEquals("E5", agg.getArrayFormulaRange().formatAsString());
- Ptg[] ptg = agg.getFormulaTokens();
- String fmlaSer = FormulaRenderer.toFormulaString(null, ptg);
- assertEquals(formula, fmlaSer);
-
- agg.removeArrayFormula(rownum, colnum);
- assertFalse(agg.isPartOfArrayFormula());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java
deleted file mode 100644
index 243e1adc2e..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java
+++ /dev/null
@@ -1,425 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.aggregates;
-
-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.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Stream;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.InternalSheet;
-import org.apache.poi.hssf.model.RecordStream;
-import org.apache.poi.hssf.record.BOFRecord;
-import org.apache.poi.hssf.record.BottomMarginRecord;
-import org.apache.poi.hssf.record.ContinueRecord;
-import org.apache.poi.hssf.record.DimensionsRecord;
-import org.apache.poi.hssf.record.EOFRecord;
-import org.apache.poi.hssf.record.FooterRecord;
-import org.apache.poi.hssf.record.HCenterRecord;
-import org.apache.poi.hssf.record.HeaderFooterRecord;
-import org.apache.poi.hssf.record.HeaderRecord;
-import org.apache.poi.hssf.record.IndexRecord;
-import org.apache.poi.hssf.record.NumberRecord;
-import org.apache.poi.hssf.record.Record;
-import org.apache.poi.hssf.record.SelectionRecord;
-import org.apache.poi.hssf.record.UnknownRecord;
-import org.apache.poi.hssf.record.UserSViewBegin;
-import org.apache.poi.hssf.record.UserSViewEnd;
-import org.apache.poi.hssf.record.VCenterRecord;
-import org.apache.poi.hssf.record.WindowTwoRecord;
-import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.util.HexRead;
-import org.apache.poi.util.RecordFormatException;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tess for {@link PageSettingsBlock}
- */
-final class TestPageSettingsBlock {
- @Test
- void testPrintSetup_bug46548() {
- // PageSettingBlock in this file contains PLS (sid=x004D) record
- // followed by ContinueRecord (sid=x003C)
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex46548-23133.xls");
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFPrintSetup ps = sheet.getPrintSetup();
-
- // bug 46548: PageSettingBlock missing PrintSetupRecord record
- assertEquals(1, ps.getCopies());
- }
-
- /**
- * Bug 46840 occurred because POI failed to recognise HEADERFOOTER as part of the
- * {@link PageSettingsBlock}.
- */
- @Test
- void testHeaderFooter_bug46840() {
-
- int rowIx = 5;
- int colIx = 6;
- NumberRecord nr = new NumberRecord();
- nr.setRow(rowIx);
- nr.setColumn((short) colIx);
- nr.setValue(3.0);
-
- org.apache.poi.hssf.record.Record[] recs = {
- BOFRecord.createSheetBOF(),
- new HeaderRecord("&LSales Figures"),
- new FooterRecord("&LJanuary"),
- new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 C4 60 00 00 00 00 00 00 00 00")),
- new DimensionsRecord(),
- new WindowTwoRecord(),
- new UserSViewBegin(HexRead.readFromString("ED 77 3B 86 BC 3F 37 4C A9 58 60 23 43 68 54 4B 01 00 00 00 64 00 00 00 40 00 00 00 02 00 00 00 3D 80 04 00 00 00 00 00 00 00 0C 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 F0 3F FF FF 01 00")),
- new HeaderRecord("&LSales Figures"),
- new FooterRecord("&LJanuary"),
- new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 C4 60 00 00 00 00 00 00 00 00")),
- new UserSViewEnd(HexRead.readFromString("01, 00")),
-
- EOFRecord.instance,
- };
- RecordStream rs = new RecordStream(Arrays.asList(recs), 0);
- // bug 46480- two Page Settings Blocks found in the same sheet
- InternalSheet sheet = InternalSheet.createSheet(rs);
-
- List outRecs = new ArrayList<>();
- sheet.visitContainedRecords(outRecs::add, rowIx);
- assertEquals(13, outRecs.size());
- }
-
- /**
- * Bug 46953 occurred because POI didn't handle late PSB records properly.
- */
- @Test
- void testLateHeaderFooter_bug46953() {
-
- int rowIx = 5;
- int colIx = 6;
- NumberRecord nr = new NumberRecord();
- nr.setRow(rowIx);
- nr.setColumn((short) colIx);
- nr.setValue(3.0);
-
- org.apache.poi.hssf.record.Record[] recs = {
- BOFRecord.createSheetBOF(),
- new HeaderRecord("&LSales Figures"),
- new FooterRecord("&LJanuary"),
- new DimensionsRecord(),
- new WindowTwoRecord(),
- new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 C4 60 00 00 00 00 00 00 00 00")),
- EOFRecord.instance,
- };
- RecordStream rs = new RecordStream(Arrays.asList(recs), 0);
- InternalSheet sheet = InternalSheet.createSheet(rs);
-
- List outRecs = new ArrayList<>();
- sheet.visitContainedRecords(outRecs::add, 0);
- // Identified bug 46953 - EOF incorrectly appended to PSB
- assertNotEquals(EOFRecord.instance, outRecs.get(4));
- assertEquals(recs.length+1, outRecs.size()); // +1 for index record
-
- Class>[] act = outRecs.stream().map(Object::getClass).toArray(Class[]::new);
- Class>[] exp = { BOFRecord.class, IndexRecord.class, HeaderRecord.class, FooterRecord.class,
- HeaderFooterRecord.class, DimensionsRecord.class, WindowTwoRecord.class, EOFRecord.class };
- assertArrayEquals(exp, act);
- }
- /**
- * Bug 47199 was due to the margin records being located well after the initial PSB records.
- * The example file supplied (attachment 23710) had three non-PSB record types
- * between the PRINTSETUP record and first MARGIN record:
- *
- * - PRINTSETUP(0x00A1)
- * - DEFAULTCOLWIDTH(0x0055)
- * - COLINFO(0x007D)
- * - DIMENSIONS(0x0200)
- * - BottomMargin(0x0029)
- *
- */
- @Test
- void testLateMargins_bug47199() {
-
- BottomMarginRecord bottomMargin = new BottomMarginRecord();
- bottomMargin.setMargin(0.787F);
-
- org.apache.poi.hssf.record.Record[] recs = {
- BOFRecord.createSheetBOF(),
- new HeaderRecord("&LSales Figures"),
- new FooterRecord("&LJanuary"),
- new DimensionsRecord(),
- bottomMargin,
- new WindowTwoRecord(),
- EOFRecord.instance,
- };
- RecordStream rs = new RecordStream(Arrays.asList(recs), 0);
-
- // bug 47199a - failed to process late margins records
- InternalSheet sheet = InternalSheet.createSheet(rs);
-
- List outRecs = new ArrayList<>();
- sheet.visitContainedRecords(outRecs::add, 0);
- assertEquals(recs.length+1, outRecs.size()); // +1 for index record
-
- Class>[] act = outRecs.stream().map(Object::getClass).toArray(Class[]::new);
- Class>[] exp = { BOFRecord.class, IndexRecord.class, HeaderRecord.class, FooterRecord.class,
- BottomMarginRecord.class, DimensionsRecord.class, WindowTwoRecord.class, EOFRecord.class };
- assertArrayEquals(exp, act);
- }
-
- /**
- * The PageSettingsBlock should not allow multiple copies of the same record. This extra assertion
- * was added while fixing bug 47199. All existing POI test samples comply with this requirement.
- */
- @Test
- void testDuplicatePSBRecord_bug47199() {
- // Hypothetical setup of PSB records which should cause POI to crash
- org.apache.poi.hssf.record.Record[] recs = {
- new HeaderRecord("&LSales Figures"),
- new HeaderRecord("&LInventory"),
- };
- RecordStream rs = new RecordStream(Arrays.asList(recs), 0);
-
- RecordFormatException ex = assertThrows(
- RecordFormatException.class,
- () -> new PageSettingsBlock(rs)
- );
- assertEquals("Duplicate PageSettingsBlock record (sid=0x14)", ex.getMessage());
- }
-
- /**
- * Excel tolerates missing header / footer records, but adds them (empty) in when re-saving.
- * This is not critical functionality but it has been decided to keep POI consistent with
- * Excel in this regard.
- */
- @Test
- void testMissingHeaderFooter() {
- // initialise PSB with some records, but not the header / footer
- org.apache.poi.hssf.record.Record[] recs = {
- new HCenterRecord(),
- new VCenterRecord(),
- };
- RecordStream rs = new RecordStream(Arrays.asList(recs), 0);
- PageSettingsBlock psb = new PageSettingsBlock(rs);
-
- // serialize the PSB to see what records come out
- List outRecs = new ArrayList<>();
- psb.visitContainedRecords(outRecs::add);
-
- assertNotEquals(2, outRecs.size(), "PageSettingsBlock didn't add missing header/footer records");
-
- Class>[] act = outRecs.stream().map(Object::getClass).toArray(Class[]::new);
- Class>[] exp = { HeaderRecord.class, FooterRecord.class, HCenterRecord.class, VCenterRecord.class};
- assertArrayEquals(exp, act);
-
- // make sure the added header / footer records are empty
- HeaderRecord hr = (HeaderRecord) outRecs.get(0);
- assertEquals("", hr.getText());
- FooterRecord fr = (FooterRecord) outRecs.get(1);
- assertEquals("", fr.getText());
- }
-
- /**
- * Apparently it's OK to have more than one PLS record.
- * Attachment 23866 from bug 47415 had a PageSettingsBlock with two PLS records. This file
- * seems to open OK in Excel(2007) but both PLS records are removed (perhaps because the
- * specified printers were not available on the testing machine). Since the example file does
- * not upset Excel, POI will preserve multiple PLS records.
- *
- * As of June 2009, PLS is still uninterpreted by POI
- */
- @Test
- void testDuplicatePLS_bug47415() {
- Record plsA = new UnknownRecord(UnknownRecord.PLS_004D, HexRead.readFromString("BA AD F0 0D"));
- Record plsB = new UnknownRecord(UnknownRecord.PLS_004D, HexRead.readFromString("DE AD BE EF"));
- Record contB1 = new ContinueRecord(HexRead.readFromString("FE ED"));
- Record contB2 = new ContinueRecord(HexRead.readFromString("FA CE"));
- org.apache.poi.hssf.record.Record[] recs = {
- new HeaderRecord("&LSales Figures"),
- new FooterRecord("&LInventory"),
- new HCenterRecord(),
- new VCenterRecord(),
- plsA,
- plsB, contB1, contB2, // make sure continuing PLS is still OK
- };
- RecordStream rs = new RecordStream(Arrays.asList(recs), 0);
- // bug 47415 - Duplicate PageSettingsBlock record (sid=0x4d)
- PageSettingsBlock psb = new PageSettingsBlock(rs);
-
- // serialize the PSB to see what records come out
- List outRecs = new ArrayList<>();
- psb.visitContainedRecords(outRecs::add);
-
- // records were assembled in standard order, so this simple check is OK
- assertArrayEquals(recs, outRecs.toArray(new Record[0]));
- }
-
- @Test
- void testDuplicateHeaderFooter_bug48026() {
-
- org.apache.poi.hssf.record.Record[] recs = {
- BOFRecord.createSheetBOF(),
- new IndexRecord(),
-
- //PageSettingsBlock
- new HeaderRecord("&LDecember"),
- new FooterRecord("&LJanuary"),
- new DimensionsRecord(),
-
- new WindowTwoRecord(),
-
- //CustomViewSettingsRecordAggregate
- new UserSViewBegin(HexRead.readFromString("53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 01 00 00 00 64 00 00 00 40 00 00 00 03 00 00 00 7D 00 00 20 00 00 34 00 00 00 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF FF FF")),
- new SelectionRecord(0, 0),
- new UserSViewEnd(HexRead.readFromString("01 00")),
-
- // two HeaderFooterRecord records, the first one has zero GUID (16 bytes at offset 12) and belongs to the PSB,
- // the other is matched with a CustomViewSettingsRecordAggregate having UserSViewBegin with the same GUID
- new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 34 33 00 00 00 00 00 00 00 00")),
- new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 34 33 00 00 00 00 00 00 00 00")),
-
- EOFRecord.instance,
- };
- RecordStream rs = new RecordStream(Arrays.asList(recs), 0);
- // bug 48026 - Duplicate PageSettingsBlock record (sid=0x89c)
- InternalSheet sheet = InternalSheet.createSheet(rs);
-
- List outRecs = new ArrayList<>();
- sheet.visitContainedRecords(outRecs::add, 0);
-
- assertEquals(recs.length, outRecs.size());
- //expected order of records:
- Record[] expectedRecs = {
- recs[0], //BOFRecord
- recs[1], //IndexRecord
-
- //PageSettingsBlock
- recs[2], //HeaderRecord
- recs[3], //FooterRecord
- recs[9], //HeaderFooterRecord
- recs[4], // DimensionsRecord
- recs[5], // WindowTwoRecord
-
- //CustomViewSettingsRecordAggregate
- recs[6], // UserSViewBegin
- recs[7], // SelectionRecord
- recs[10], // HeaderFooterRecord
- recs[8], // UserSViewEnd
-
- recs[11], //EOFRecord
- };
-
- assertArrayEquals(
- Stream.of(expectedRecs).map(Object::getClass).toArray(Class[]::new),
- outRecs.stream().map(Object::getClass).toArray(Class[]::new)
- );
-
- HeaderFooterRecord hd1 = (HeaderFooterRecord)expectedRecs[4];
- //GUID is zero
- assertArrayEquals(new byte[16], hd1.getGuid());
- assertTrue(hd1.isCurrentSheet());
-
- UserSViewBegin svb = (UserSViewBegin)expectedRecs[7];
- HeaderFooterRecord hd2 = (HeaderFooterRecord)expectedRecs[9];
- assertFalse(hd2.isCurrentSheet());
- //GUIDs of HeaderFooterRecord and UserSViewBegin must be the same
- assertArrayEquals(svb.getGuid(), hd2.getGuid());
- }
-
- @Test
- void testDuplicateHeaderFooterInside_bug48026() {
-
- Record[] recs = {
- BOFRecord.createSheetBOF(),
- new IndexRecord(),
-
- //PageSettingsBlock
- new HeaderRecord("&LDecember"),
- new FooterRecord("&LJanuary"),
- new DimensionsRecord(),
-
- new WindowTwoRecord(),
-
- //CustomViewSettingsRecordAggregate
- new UserSViewBegin(HexRead.readFromString("53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 01 00 00 00 64 00 00 00 40 00 00 00 03 00 00 00 7D 00 00 20 00 00 34 00 00 00 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF FF FF")),
- new SelectionRecord(0, 0),
-
- // two HeaderFooterRecord records, the first one has zero GUID (16 bytes at offset 12) and belongs to the PSB,
- // the other is matched with a CustomViewSettingsRecordAggregate having UserSViewBegin with the same GUID
- new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 34 33 00 00 00 00 00 00 00 00")),
- new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 34 33 00 00 00 00 00 00 00 00")),
-
- new UserSViewEnd(HexRead.readFromString("01 00")),
-
- EOFRecord.instance,
- };
- RecordStream rs = new RecordStream(Arrays.asList(recs), 0);
- // Bug 48026 : Duplicate PageSettingsBlock record (sid=0x89c)
- InternalSheet sheet = InternalSheet.createSheet(rs);
-
- List outRecs = new ArrayList<>();
- sheet.visitContainedRecords(outRecs::add, 0);
-
- assertEquals(recs.length+1, outRecs.size());
- //expected order of records:
- Record[] expectedRecs = {
- recs[0], //BOFRecord
- recs[1], //IndexRecord
-
- //PageSettingsBlock
- recs[2], //HeaderRecord
- recs[3], //FooterRecord
- recs[4], // DimensionsRecord
- recs[5], // WindowTwoRecord
-
- //CustomViewSettingsRecordAggregate
- recs[6], // UserSViewBegin
- recs[7], // SelectionRecord
- recs[2], //HeaderRecord
- recs[3], //FooterRecord
- recs[8], // HeaderFooterRecord
-// recs[9], //HeaderFooterRecord
- recs[10], // UserSViewEnd
-
- recs[11], //EOFRecord
- };
-
- assertArrayEquals(
- Stream.of(expectedRecs).map(Object::getClass).toArray(Class[]::new),
- outRecs.stream().map(Object::getClass).toArray(Class[]::new)
- );
-
- HeaderFooterRecord hd1 = (HeaderFooterRecord)expectedRecs[10];
- //GUID is zero
- assertArrayEquals(new byte[16], hd1.getGuid());
- assertTrue(hd1.isCurrentSheet());
-
- UserSViewBegin svb = (UserSViewBegin)expectedRecs[6];
- HeaderFooterRecord hd2 = (HeaderFooterRecord)recs[9];
- assertFalse(hd2.isCurrentSheet());
- //GUIDs of HeaderFooterRecord and UserSViewBegin must be the same
- assertArrayEquals(svb.getGuid(), hd2.getGuid());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java
deleted file mode 100644
index 41ad8fbcb5..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.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.hssf.record.aggregates;
-
-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.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.RecordStream;
-import org.apache.poi.hssf.record.ArrayRecord;
-import org.apache.poi.hssf.record.ContinueRecord;
-import org.apache.poi.hssf.record.FormulaRecord;
-import org.apache.poi.hssf.record.NumberRecord;
-import org.apache.poi.hssf.record.Record;
-import org.apache.poi.hssf.record.RowRecord;
-import org.apache.poi.hssf.record.SharedFormulaRecord;
-import org.apache.poi.hssf.record.SharedValueRecordBase;
-import org.apache.poi.hssf.record.TableRecord;
-import org.apache.poi.hssf.record.UnknownRecord;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.hssf.util.CellRangeAddress8Bit;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link RowRecordsAggregate}
- */
-final class TestRowRecordsAggregate {
-
- @Test
- void testRowGet() {
- RowRecordsAggregate rra = new RowRecordsAggregate();
- RowRecord rr = new RowRecord(4);
- rra.insertRow(rr);
- rra.insertRow(new RowRecord(1));
-
- RowRecord rr1 = rra.getRow(4);
-
- assertNotNull(rr1);
- assertEquals(4, rr1.getRowNumber(), "Row number is 1");
- assertSame(rr1, rr, "Row record retrieved is identical ");
- }
-
- /**
- * Prior to Aug 2008, POI would re-serialize spreadsheets with {@link ArrayRecord}s or
- * {@link TableRecord}s with those records out of order. Similar to
- * {@link SharedFormulaRecord}s, these records should appear immediately after the first
- * {@link FormulaRecord}s that they apply to (and only once).
- */
- @Test
- void testArraysAndTables() throws Exception {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testArraysAndTables.xls")) {
- final List sheetRecs = new ArrayList<>();
- wb.getSheetAt(0).getSheet().visitContainedRecords(sheetRecs::add, 0);
-
- int countArrayFormulas = verifySharedValues(sheetRecs, ArrayRecord.class);
- assertEquals(5, countArrayFormulas);
- int countTableFormulas = verifySharedValues(sheetRecs, TableRecord.class);
- assertEquals(3, countTableFormulas);
-
- // Note - SharedFormulaRecords are currently not re-serialized by POI (each is extracted
- // into many non-shared formulas), but if they ever were, the same rules would apply.
- int countSharedFormulas = verifySharedValues(sheetRecs, SharedFormulaRecord.class);
- assertEquals(0, countSharedFormulas);
-
-
-// if (false) { // set true to observe re-serialized file
-// File f = new File(System.getProperty("java.io.tmpdir") + "/testArraysAndTables-out.xls");
-// try {
-// OutputStream os = new FileOutputStream(f);
-// wb.write(os);
-// os.close();
-// } catch (IOException e) {
-// throw new RuntimeException(e);
-// }
-// System.out.println("Output file to " + f.getAbsolutePath());
-// }
-
- }
- }
-
- private static int verifySharedValues(List recs, Class extends SharedValueRecordBase> shfClass) {
-
- int result =0;
- for(int i=0; i
- * The functionality change being tested here is actually not critical to the overall fix
- * for bug 46280, since the fix involved making sure the that offending PivotTable
- * records do not get into {@link RowRecordsAggregate}.
- * This fix in {@link RowRecordsAggregate} was implemented anyway since any {@link
- * UnknownRecord} has the potential of being 'continued'.
- */
- @Test
- void testUnknownContinue_bug46280() {
- org.apache.poi.hssf.record.Record[] inRecs = {
- new RowRecord(0),
- new NumberRecord(),
- new UnknownRecord(0x5555, "dummydata".getBytes(LocaleUtil.CHARSET_1252)),
- new ContinueRecord("moredummydata".getBytes(LocaleUtil.CHARSET_1252)),
- };
- RecordStream rs = new RecordStream(Arrays.asList(inRecs), 0);
- RowRecordsAggregate rra;
- try {
- rra = new RowRecordsAggregate(rs, SharedValueManager.createEmpty());
- } catch (RuntimeException e) {
- if (e.getMessage().startsWith("Unexpected record type")) {
- fail("Identified bug 46280a");
- }
- throw e;
- }
-
- List outRecs = new ArrayList<>();
- rra.visitContainedRecords(outRecs::add);
- assertEquals(5, outRecs.size());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java
deleted file mode 100644
index 31b4f92548..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.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.hssf.record.aggregates;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-
-import java.util.Collection;
-import java.util.HashMap;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.SharedFormulaRecord;
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link SharedValueManager}
- */
-final class TestSharedValueManager {
-
- /**
- * This Excel workbook contains two sheets that each have a pair of overlapping shared formula
- * ranges. The first sheet has one row and one column shared formula ranges which intersect.
- * The second sheet has two column shared formula ranges - one contained within the other.
- * These shared formula ranges were created by fill-dragging a single cell formula across the
- * desired region. The larger shared formula ranges were placed first.
- *
- * There are probably many ways to produce similar effects, but it should be noted that Excel
- * is quite temperamental in this regard. Slight variations in technique can cause the shared
- * formulas to spill out into plain formula records (which would make these tests pointless).
- *
- */
- private static final String SAMPLE_FILE_NAME = "overlapSharedFormula.xls";
- /**
- * Some of these bugs are intermittent, and the test author couldn't think of a way to write
- * test code to hit them bug deterministically. The reason for the unpredictability is that
- * the bugs depended on the {@link SharedFormulaRecord}s being searched in a particular order.
- * At the time of writing of the test, the order was being determined by the call to {@link
- * Collection#toArray(Object[])} on {@link HashMap#values()} where the items in the map were
- * using default {@link Object#hashCode()}
- */
- private static final int MAX_ATTEMPTS=5;
-
- /**
- * This bug happened when there were two or more shared formula ranges that overlapped. POI
- * would sometimes associate formulas in the overlapping region with the wrong shared formula
- */
- @Test
- void testPartiallyOverlappingRanges() {
-
-
- for (int attempt=1; attempt < MAX_ATTEMPTS; attempt++) {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_FILE_NAME);
-
- HSSFSheet sheet = wb.getSheetAt(0);
- assertEquals("1+1", sheet.getRow(2).getCell(0).getCellFormula());
- String act = sheet.getRow(3).getCell(0).getCellFormula();
- assertNotEquals("wrong shared formula record chosen", "1+1", act);
- act = sheet.getRow(3).getCell(0).getCellFormula();
- assertEquals("2+2", act);
-
- int[] count = { 0 };
- sheet.getSheet().visitContainedRecords(r -> count[0] += r instanceof SharedFormulaRecord ? 1 : 0, 0);
- assertEquals(2, count[0]);
- }
- }
-
- /**
- * This bug occurs for similar reasons to the bug in {@link #testPartiallyOverlappingRanges()}
- * but the symptoms are much uglier - serialization fails with {@link NullPointerException}.
- */
- @Test
- void testCompletelyOverlappedRanges() {
- for (int attempt=1; attempt < MAX_ATTEMPTS; attempt++) {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_FILE_NAME);
-
- HSSFSheet sheet = wb.getSheetAt(1);
-
- int[] count = { 0 };
-
- // NullPointerException -> cannot reserialize completely overlapped shared formula
- sheet.getSheet().visitContainedRecords(r -> count[0] += r instanceof SharedFormulaRecord ? 1 : 0, 0);
- assertEquals(2, count[0]);
- }
- }
-
- /**
- * Tests fix for a bug in the way shared formula cells are associated with shared formula
- * records. Prior to this fix, POI would attempt to use the upper left corner of the
- * shared formula range as the locator cell. The correct cell to use is the 'first cell'
- * in the shared formula group which is not always the top left cell. This is possible
- * because shared formula groups may be sparse and may overlap.
- *
- * Two existing sample files (15228.xls and ex45046-21984.xls) had similar issues.
- * These were not explored fully, but seem to be fixed now.
- */
- @Test
- void testRecalculateFormulas47747() {
-
- /*
- * ex47747-sharedFormula.xls is a heavily cut-down version of the spreadsheet from
- * the attachment (id=24176) in Bugzilla 47747. This was done to make the sample
- * file smaller, which hopefully allows the special data encoding condition to be
- * seen more easily. Care must be taken when modifying this file since the
- * special conditions are easily destroyed (which would make this test useless).
- * It seems that removing the worksheet protection has made this more so - if the
- * current file is re-saved in Excel(2007) the bug condition disappears.
- *
- *
- * Using BiffViewer, one can see that there are two shared formula groups representing
- * the essentially same formula over ~20 cells. The shared group ranges overlap and
- * are A12:Q20 and A20:Q27. The locator cell ('first cell') for the second group is
- * Q20 which is not the top left cell of the enclosing range. It is this specific
- * condition which caused the bug to occur
- */
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex47747-sharedFormula.xls");
-
- // pick out a cell from within the second shared formula group
- HSSFCell cell = wb.getSheetAt(0).getRow(23).getCell(0);
- // bug occurs if the formula record has been associated
- // with the first (and not the second) shared formula group
- String formulaText = cell.getCellFormula();
- assertEquals("$AF24*A$7", formulaText);
- }
-
- @Test
- void testBug52527() {
- HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("52527.xls");
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
-
- assertEquals("IF(H3,LINEST(N9:N14,K9:M14,FALSE),LINEST(N8:N14,K8:M14,FALSE))",
- wb1.getSheetAt(0).getRow(4).getCell(11).getCellFormula());
- assertEquals("IF(H3,LINEST(N9:N14,K9:M14,FALSE),LINEST(N8:N14,K8:M14,FALSE))",
- wb2.getSheetAt(0).getRow(4).getCell(11).getCellFormula());
-
- assertEquals("1/SQRT(J9)",
- wb1.getSheetAt(0).getRow(8).getCell(10).getCellFormula());
- assertEquals("1/SQRT(J9)",
- wb2.getSheetAt(0).getRow(8).getCell(10).getCellFormula());
-
- assertEquals("1/SQRT(J26)",
- wb1.getSheetAt(0).getRow(25).getCell(10).getCellFormula());
- assertEquals("1/SQRT(J26)",
- wb2.getSheetAt(0).getRow(25).getCell(10).getCellFormula());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java
deleted file mode 100644
index 38018f3627..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java
+++ /dev/null
@@ -1,411 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.aggregates;
-
-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.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.zip.CRC32;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.RecordStream;
-import org.apache.poi.hssf.model.RowBlocksReader;
-import org.apache.poi.hssf.record.BlankRecord;
-import org.apache.poi.hssf.record.CellValueRecordInterface;
-import org.apache.poi.hssf.record.FormulaRecord;
-import org.apache.poi.hssf.record.MulBlankRecord;
-import org.apache.poi.hssf.record.Record;
-import org.apache.poi.hssf.record.SharedFormulaRecord;
-import org.apache.poi.hssf.record.WindowTwoRecord;
-import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor;
-import org.apache.poi.hssf.usermodel.HSSFRow;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link ValueRecordsAggregate}
- */
-final class TestValueRecordsAggregate {
- private static final String ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE = "AbnormalSharedFormulaFlag.xls";
- private final ValueRecordsAggregate valueRecord = new ValueRecordsAggregate();
-
- private List getValueRecords() {
- List list = new ArrayList<>();
- for ( CellValueRecordInterface rec : valueRecord ) {
- list.add(rec);
- }
- return Collections.unmodifiableList(list);
- }
-
- /**
- * Make sure the shared formula DOESNT makes it to the FormulaRecordAggregate when being parsed
- * as part of the value records
- */
- @Test
- void testSharedFormula() {
- List records = new ArrayList<>();
- records.add(new FormulaRecord());
- records.add(new SharedFormulaRecord());
- records.add(new WindowTwoRecord());
-
- constructValueRecord(records);
- List cvrs = getValueRecords();
- //Ensure that the SharedFormulaRecord has been converted
- assertEquals(1, cvrs.size());
-
- CellValueRecordInterface record = cvrs.get(0);
- assertNotNull( record, "Row contains a value" );
- assertTrue( ( record instanceof FormulaRecordAggregate ), "First record is a FormulaRecordsAggregate");
- }
-
- private void constructValueRecord(List records) {
- RowBlocksReader rbr = new RowBlocksReader(new RecordStream(records, 0));
- SharedValueManager sfrh = rbr.getSharedFormulaManager();
- RecordStream rs = rbr.getPlainRecordStream();
- while(rs.hasNext()) {
- Record rec = rs.getNext();
- valueRecord.construct((CellValueRecordInterface)rec, rs, sfrh);
- }
- }
-
- private static List testData() {
- List records = new ArrayList<>();
- FormulaRecord formulaRecord = new FormulaRecord();
- BlankRecord blankRecord = new BlankRecord();
- formulaRecord.setRow(1);
- formulaRecord.setColumn((short) 1);
- blankRecord.setRow(2);
- blankRecord.setColumn((short) 2);
- records.add(formulaRecord);
- records.add(blankRecord);
- records.add(new WindowTwoRecord());
- return records;
- }
-
- @Test
- void testInsertCell() {
- assertEquals(0, getValueRecords().size());
-
- BlankRecord blankRecord = newBlankRecord();
- valueRecord.insertCell( blankRecord );
- assertEquals(1, getValueRecords().size());
- }
-
- @Test
- void testRemoveCell() {
- BlankRecord blankRecord1 = newBlankRecord();
- valueRecord.insertCell( blankRecord1 );
- BlankRecord blankRecord2 = newBlankRecord();
- valueRecord.removeCell( blankRecord2 );
- assertEquals(0, getValueRecords().size());
-
- // removing an already empty cell just falls through
- valueRecord.removeCell( blankRecord2 );
- }
-
- @Test
- void testGetPhysicalNumberOfCells() {
- assertEquals(0, valueRecord.getPhysicalNumberOfCells());
- BlankRecord blankRecord1 = newBlankRecord();
- valueRecord.insertCell( blankRecord1 );
- assertEquals(1, valueRecord.getPhysicalNumberOfCells());
- valueRecord.removeCell( blankRecord1 );
- assertEquals(0, valueRecord.getPhysicalNumberOfCells());
- }
-
- @Test
- void testGetFirstCellNum() {
- assertEquals( -1, valueRecord.getFirstCellNum() );
- valueRecord.insertCell( newBlankRecord( 2, 2 ) );
- assertEquals( 2, valueRecord.getFirstCellNum() );
- valueRecord.insertCell( newBlankRecord( 3, 3 ) );
- assertEquals( 2, valueRecord.getFirstCellNum() );
-
- // Note: Removal doesn't currently reset the first column. It probably should but it doesn't.
- valueRecord.removeCell( newBlankRecord( 2, 2 ) );
- assertEquals( 2, valueRecord.getFirstCellNum() );
- }
-
- @Test
- void testGetLastCellNum() {
- assertEquals( -1, valueRecord.getLastCellNum() );
- valueRecord.insertCell( newBlankRecord( 2, 2 ) );
- assertEquals( 2, valueRecord.getLastCellNum() );
- valueRecord.insertCell( newBlankRecord( 3, 3 ) );
- assertEquals( 3, valueRecord.getLastCellNum() );
-
- // Note: Removal doesn't currently reset the last column. It probably should but it doesn't.
- valueRecord.removeCell( newBlankRecord( 3, 3 ) );
- assertEquals( 3, valueRecord.getLastCellNum() );
-
- }
-
-
- private static final class SerializerVisitor implements RecordVisitor {
- private final byte[] _buf;
- private int _writeIndex;
- public SerializerVisitor(byte[] buf) {
- _buf = buf;
- _writeIndex = 0;
-
- }
- @Override
- public void visitRecord(org.apache.poi.hssf.record.Record r) {
- r.serialize(_writeIndex, _buf);
- _writeIndex += r.getRecordSize();
- }
- public int getWriteIndex() {
- return _writeIndex;
- }
- }
-
- @Test
- void testSerialize() {
- byte[] expectedArray = HexRead.readFromString(""
- + "06 00 16 00 " // Formula
- + "01 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 "
- + "01 02 06 00 " // Blank
- + "02 00 02 00 00 00");
- byte[] actualArray = new byte[expectedArray.length];
- List records = testData();
- constructValueRecord(records);
-
- SerializerVisitor sv = new SerializerVisitor(actualArray);
- valueRecord.visitCellsForRow(1, sv);
- valueRecord.visitCellsForRow(2, sv);
- assertEquals(actualArray.length, sv.getWriteIndex());
- assertArrayEquals(expectedArray, actualArray);
- }
-
- private static BlankRecord newBlankRecord() {
- return newBlankRecord( 2, 2 );
- }
-
- private static BlankRecord newBlankRecord(int col, int row) {
- BlankRecord blankRecord = new BlankRecord();
- blankRecord.setRow( row );
- blankRecord.setColumn( (short) col );
- return blankRecord;
- }
-
- /**
- * Sometimes the 'shared formula' flag (FormulaRecord.isSharedFormula()) is set when
- * there is no corresponding SharedFormulaRecord available. SharedFormulaRecord definitions do
- * not span multiple sheets. They are are only defined within a sheet, and thus they do not
- * have a sheet index field (only row and column range fields).
- * So it is important that the code which locates the SharedFormulaRecord for each
- * FormulaRecord does not allow matches across sheets.
- *
- * Prior to bugzilla 44449 (Feb 2008), POI ValueRecordsAggregate.construct(int, List)
- * allowed SharedFormulaRecords to be erroneously used across sheets. That incorrect
- * behaviour is shown by this test.
- *
- * Notes on how to produce the test spreadsheet:
- * The setup for this test (AbnormalSharedFormulaFlag.xls) is rather fragile, insomuchas
- * re-saving the file (either with Excel or POI) clears the flag.
- *
- * - A new spreadsheet was created in Excel (File | New | Blank Workbook).
- * - Sheet3 was deleted.
- * - Sheet2!A1 formula was set to '="second formula"', and fill-dragged through A1:A8.
- * - Sheet1!A1 formula was set to '="first formula"', and also fill-dragged through A1:A8.
- * - Four rows on Sheet1 "5" through "8" were deleted ('delete rows' alt-E D, not 'clear' Del).
- * - The spreadsheet was saved as AbnormalSharedFormulaFlag.xls.
- *
- * Prior to the row delete action the spreadsheet has two SharedFormulaRecords. One
- * for each sheet. To expose the bug, the shared formulas have been made to overlap.
- * The row delete action (as described here) seems to to delete the
- * SharedFormulaRecord from Sheet1 (but not clear the 'shared formula' flags.
- * There are other variations on this theme to create the same effect.
- *
- */
- @Test
- void testSpuriousSharedFormulaFlag() throws Exception {
-
- long actualCRC = getFileCRC(HSSFTestDataSamples.openSampleFileStream(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE));
- long expectedCRC = 2277445406L;
- if(actualCRC != expectedCRC) {
- System.err.println("Expected crc " + expectedCRC + " but got " + actualCRC);
- throw failUnexpectedTestFileChange();
- }
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE);
-
- HSSFSheet s = wb.getSheetAt(0); // Sheet1
-
- String cellFormula;
- cellFormula = getFormulaFromFirstCell(s, 0); // row "1"
- // the problem is not observable in the first row of the shared formula
- assertEquals("\"first formula\"", cellFormula, "Something else wrong with this test case");
-
- // but the problem is observable in rows 2,3,4
- cellFormula = getFormulaFromFirstCell(s, 1); // row "2"
- assertNotEquals("\"second formula\"", cellFormula, "found bug 44449 (Wrong SharedFormulaRecord was used).");
-
- assertEquals("\"first formula\"", cellFormula, "Something else wrong with this test case");
-
- wb.close();
- }
- private static String getFormulaFromFirstCell(HSSFSheet s, int rowIx) {
- return s.getRow(rowIx).getCell(0).getCellFormula();
- }
-
- /**
- * If someone opened this particular test file in Excel and saved it, the peculiar condition
- * which causes the target bug would probably disappear. This test would then just succeed
- * regardless of whether the fix was present. So a CRC check is performed to make it less easy
- * for that to occur.
- */
- private static RuntimeException failUnexpectedTestFileChange() {
- String msg = "Test file '" + ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE + "' has changed. "
- + "This junit may not be properly testing for the target bug. "
- + "Either revert the test file or ensure that the new version "
- + "has the right characteristics to test the target bug.";
- // A breakpoint in ValueRecordsAggregate.handleMissingSharedFormulaRecord(FormulaRecord)
- // should get hit during parsing of Sheet1.
- // If the test spreadsheet is created as directed, this condition should occur.
- // It is easy to upset the test spreadsheet (for example re-saving will destroy the
- // peculiar condition we are testing for).
- throw new RuntimeException(msg);
- }
-
- /**
- * gets a CRC checksum for the content of a file
- */
- private static long getFileCRC(InputStream is) {
- CRC32 crc = new CRC32();
- byte[] buf = new byte[2048];
- try {
- while(true) {
- int bytesRead = is.read(buf);
- if(bytesRead < 1) {
- break;
- }
- crc.update(buf, 0, bytesRead);
- }
- is.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- return crc.getValue();
- }
-
- @Test
- void testRemoveNewRow_bug46312() throws IOException {
- // To make bug occur, rowIndex needs to be >= ValueRecordsAggregate.records.length
- int rowIndex = 30;
-
- ValueRecordsAggregate vra = new ValueRecordsAggregate();
- // bug 46312 - Specified rowIndex 30 is outside the allowable range (0..30)
- assertDoesNotThrow(() -> vra.removeAllCellsValuesForRow(rowIndex));
-
- // same bug as demonstrated through usermodel API
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- HSSFRow row = sheet.createRow(rowIndex);
-
- // must not add any cells to the new row if we want to see the bug
- // row.createCell(0); // this causes ValueRecordsAggregate.records to auto-extend
- assertDoesNotThrow(() -> sheet.createRow(rowIndex));
- }
- }
-
- /**
- * Tests various manipulations of blank cells, to make sure that {@link MulBlankRecord}s
- * are use appropriately
- */
- @Test
- void testMultipleBlanks() {
- BlankRecord brA2 = newBlankRecord(0, 1);
- BlankRecord brB2 = newBlankRecord(1, 1);
- BlankRecord brC2 = newBlankRecord(2, 1);
- BlankRecord brD2 = newBlankRecord(3, 1);
- BlankRecord brE2 = newBlankRecord(4, 1);
- BlankRecord brB3 = newBlankRecord(1, 2);
- BlankRecord brC3 = newBlankRecord(2, 2);
-
- valueRecord.insertCell(brA2);
- valueRecord.insertCell(brB2);
- valueRecord.insertCell(brD2);
- confirmMulBlank(3, 1, 1);
-
- valueRecord.insertCell(brC3);
- confirmMulBlank(4, 1, 2);
-
- valueRecord.insertCell(brB3);
- valueRecord.insertCell(brE2);
- confirmMulBlank(6, 3, 0);
-
- valueRecord.insertCell(brC2);
- confirmMulBlank(7, 2, 0);
-
- valueRecord.removeCell(brA2);
- confirmMulBlank(6, 2, 0);
-
- valueRecord.removeCell(brC2);
- confirmMulBlank(5, 2, 1);
-
- valueRecord.removeCell(brC3);
- confirmMulBlank(4, 1, 2);
- }
-
- private void confirmMulBlank(int expectedTotalBlankCells,
- int expectedNumberOfMulBlankRecords, int expectedNumberOfSingleBlankRecords) {
- // assumed row ranges set-up by caller:
- final int firstRow = 1;
- final int lastRow = 2;
-
-
- final class BlankStats {
- public int countBlankCells;
- public int countMulBlankRecords;
- public int countSingleBlankRecords;
- }
-
- final BlankStats bs = new BlankStats();
- RecordVisitor rv = r -> {
- if (r instanceof MulBlankRecord) {
- MulBlankRecord mbr = (MulBlankRecord) r;
- bs.countMulBlankRecords++;
- bs.countBlankCells += mbr.getNumColumns();
- } else if (r instanceof BlankRecord) {
- bs.countSingleBlankRecords++;
- bs.countBlankCells++;
- }
- };
-
- for (int rowIx = firstRow; rowIx <=lastRow; rowIx++) {
- if (valueRecord.rowHasCells(rowIx)) {
- valueRecord.visitCellsForRow(rowIx, rv);
- }
- }
- assertEquals(expectedTotalBlankCells, bs.countBlankCells);
- assertEquals(expectedNumberOfMulBlankRecords, bs.countMulBlankRecords);
- assertEquals(expectedNumberOfSingleBlankRecords, bs.countSingleBlankRecords);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java b/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java
deleted file mode 100644
index cb0a6a548b..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java
+++ /dev/null
@@ -1,274 +0,0 @@
-/* ====================================================================
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You under the Apache License, Version 2.0
-(the "License"); you may not use this file except in compliance with
-the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.cf;
-
-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.Arrays;
-
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.apache.poi.ss.util.CellRangeUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests CellRange operations.
- */
-final class TestCellRange {
- private static final CellRangeAddress biggest = createCR( 0, -1, 0,-1);
- private static final CellRangeAddress tenthColumn = createCR( 0, -1,10,10);
- private static final CellRangeAddress tenthRow = createCR(10, 10, 0,-1);
- private static final CellRangeAddress box10x10 = createCR( 0, 10, 0,10);
- private static final CellRangeAddress box9x9 = createCR( 0, 9, 0, 9);
- private static final CellRangeAddress box10to20c = createCR( 0, 10,10,20);
- private static final CellRangeAddress oneCell = createCR(10, 10,10,10);
-
- private static final CellRangeAddress[] sampleRanges = {
- biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell,
- };
-
- /** cross-reference of contains() operations for sampleRanges against itself */
- private static final boolean [][] containsExpectedResults =
- {
- // biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell
- /*biggest */ {true, true , true , true , true , true , true},
- /*tenthColumn*/ {false, true , false, false, false, false, true},
- /*tenthRow */ {false, false, true , false, false, false, true},
- /*box10x10 */ {false, false, false, true , true , false, true},
- /*box9x9 */ {false, false, false, false, true , false, false},
- /*box10to20c */ {false, false, false, false, false, true , true},
- /*oneCell */ {false, false, false, false, false, false, true},
- } ;
-
- /**
- * @param lastRow pass -1 for max row index
- * @param lastCol pass -1 for max col index
- */
- private static CellRangeAddress createCR(int firstRow, int lastRow, int firstCol, int lastCol) {
- // max row & max col limit as per BIFF8
- return new CellRangeAddress(
- firstRow,
- lastRow == -1 ? 0xFFFF : lastRow,
- firstCol,
- lastCol == -1 ? 0x00FF : lastCol);
- }
-
- @Test
- void testContainsMethod()
- {
- CellRangeAddress [] ranges = sampleRanges;
- for(int i=0; i!=ranges.length;i++)
- {
- for(int j=0; j!=ranges.length;j++)
- {
- boolean expectedResult = containsExpectedResults[i][j];
- assertEquals(expectedResult, CellRangeUtil.contains(ranges[i], ranges[j]), "("+i+","+j+"): ");
- }
- }
- }
-
- private static final CellRangeAddress col1 = createCR( 0, -1, 1,1);
- private static final CellRangeAddress col2 = createCR( 0, -1, 2,2);
- private static final CellRangeAddress row1 = createCR( 1, 1, 0,-1);
- private static final CellRangeAddress row2 = createCR( 2, 2, 0,-1);
-
- private static final CellRangeAddress box0 = createCR( 0, 2, 0,2);
- private static final CellRangeAddress box1 = createCR( 0, 1, 0,1);
- private static final CellRangeAddress box2 = createCR( 0, 1, 2,3);
- private static final CellRangeAddress box3 = createCR( 2, 3, 0,1);
- private static final CellRangeAddress box4 = createCR( 2, 3, 2,3);
- private static final CellRangeAddress box5 = createCR( 1, 3, 1,3);
-
- @Test
- void testHasSharedBorderMethod() {
- assertFalse(CellRangeUtil.hasExactSharedBorder(col1, col1));
- assertFalse(CellRangeUtil.hasExactSharedBorder(col2, col2));
- assertTrue(CellRangeUtil.hasExactSharedBorder(col1, col2));
- assertTrue(CellRangeUtil.hasExactSharedBorder(col2, col1));
-
- assertFalse(CellRangeUtil.hasExactSharedBorder(row1, row1));
- assertFalse(CellRangeUtil.hasExactSharedBorder(row2, row2));
- assertTrue(CellRangeUtil.hasExactSharedBorder(row1, row2));
- assertTrue(CellRangeUtil.hasExactSharedBorder(row2, row1));
-
- assertFalse(CellRangeUtil.hasExactSharedBorder(row1, col1));
- assertFalse(CellRangeUtil.hasExactSharedBorder(row1, col2));
- assertFalse(CellRangeUtil.hasExactSharedBorder(col1, row1));
- assertFalse(CellRangeUtil.hasExactSharedBorder(col2, row1));
- assertFalse(CellRangeUtil.hasExactSharedBorder(row2, col1));
- assertFalse(CellRangeUtil.hasExactSharedBorder(row2, col2));
- assertFalse(CellRangeUtil.hasExactSharedBorder(col1, row2));
- assertFalse(CellRangeUtil.hasExactSharedBorder(col2, row2));
- assertTrue(CellRangeUtil.hasExactSharedBorder(col2, col1));
-
- assertFalse(CellRangeUtil.hasExactSharedBorder(box1, box1));
- assertTrue(CellRangeUtil.hasExactSharedBorder(box1, box2));
- assertTrue(CellRangeUtil.hasExactSharedBorder(box1, box3));
- assertFalse(CellRangeUtil.hasExactSharedBorder(box1, box4));
-
- assertTrue(CellRangeUtil.hasExactSharedBorder(box2, box1));
- assertFalse(CellRangeUtil.hasExactSharedBorder(box2, box2));
- assertFalse(CellRangeUtil.hasExactSharedBorder(box2, box3));
- assertTrue(CellRangeUtil.hasExactSharedBorder(box2, box4));
-
- assertTrue(CellRangeUtil.hasExactSharedBorder(box3, box1));
- assertFalse(CellRangeUtil.hasExactSharedBorder(box3, box2));
- assertFalse(CellRangeUtil.hasExactSharedBorder(box3, box3));
- assertTrue(CellRangeUtil.hasExactSharedBorder(box3, box4));
-
- assertFalse(CellRangeUtil.hasExactSharedBorder(box4, box1));
- assertTrue(CellRangeUtil.hasExactSharedBorder(box4, box2));
- assertTrue(CellRangeUtil.hasExactSharedBorder(box4, box3));
- assertFalse(CellRangeUtil.hasExactSharedBorder(box4, box4));
- }
-
- @Test
- void testIntersectMethod() {
- assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(box0, box5));
- assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(box5, box0));
- assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box1, box4));
- assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box4, box1));
- assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box2, box3));
- assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box3, box2));
- assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(box0, box1));
- assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(box0, box0));
- assertEquals(CellRangeUtil.ENCLOSES, CellRangeUtil.intersect(box1, box0));
- assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(tenthColumn, oneCell));
- assertEquals(CellRangeUtil.ENCLOSES, CellRangeUtil.intersect(oneCell, tenthColumn));
- assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(tenthColumn, tenthRow));
- assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(tenthRow, tenthColumn));
- assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(tenthColumn, tenthColumn));
- assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(tenthRow, tenthRow));
-
- // Bug 55380
- assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(
- CellRangeAddress.valueOf("C1:D2"), CellRangeAddress.valueOf("C2:C3")));
- }
-
- /**
- * Cell ranges like the following are valid
- * =$C:$IV,$B$1:$B$8,$B$10:$B$65536,$A:$A
- */
- @Test
- void testCreate() {
- CellRangeAddress cr = createCR(0, -1, 2, 255); // $C:$IV
-
- assertFalse(cr.isFullRowRange(), "isFullRowRange");
- assertTrue(cr.isFullColumnRange(), "isFullColumnRange");
-
- createCR(0, 7, 1, 1); // $B$1:$B$8
-
- // bug 44739 - invalid cell range
- createCR(9, -1, 1, 1); // $B$65536
-
- createCR(0, -1, 0, 0); // $A:$A
- }
-
- @Test
- void testNumberOfCells() {
- assertEquals(1, oneCell.getNumberOfCells());
- assertEquals(100, box9x9.getNumberOfCells());
- assertEquals(121, box10to20c.getNumberOfCells());
- }
-
- @SuppressWarnings("RedundantArrayCreation")
- @Test
- void testMergeCellRanges() {
- // no result on empty
- cellRangeTest(new String[]{ });
-
- // various cases with two ranges
- cellRangeTest(new String[]{"A1:B1", "A2:B2"}, "A1:B2");
- cellRangeTest(new String[]{"A1:B1" }, "A1:B1");
- cellRangeTest(new String[]{"A1:B2", "A2:B2"}, "A1:B2");
- cellRangeTest(new String[]{"A1:B3", "A2:B2"}, "A1:B3");
- cellRangeTest(new String[]{"A1:C1", "A2:B2"}, new String[] {"A1:C1", "A2:B2"});
-
- // cases with three ranges
- cellRangeTest(new String[]{"A1:A1", "A2:B2", "A1:C1"}, new String[] {"A1:C1", "A2:B2"});
- cellRangeTest(new String[]{"A1:C1", "A2:B2", "A1:A1"}, new String[] {"A1:C1", "A2:B2"});
-
- // "standard" cases
- // enclose
- cellRangeTest(new String[]{"A1:D4", "B2:C3"}, new String[] {"A1:D4"});
- // inside
- cellRangeTest(new String[]{"B2:C3", "A1:D4"}, new String[] {"A1:D4"});
- cellRangeTest(new String[]{"B2:C3", "A1:D4"}, new String[] {"A1:D4"});
- // disjunct
- cellRangeTest(new String[]{"A1:B2", "C3:D4"}, new String[] {"A1:B2", "C3:D4"});
- cellRangeTest(new String[]{"A1:B2", "A3:D4"}, new String[] {"A1:B2", "A3:D4"});
- // overlap that cannot be merged
- cellRangeTest(new String[]{"C1:D2", "C2:C3"}, new String[] {"C1:D2", "C2:C3"});
- // overlap which could theoretically be merged, but isn't because the implementation was buggy and therefore was removed
- cellRangeTest(new String[]{"A1:C3", "B1:D3"}, new String[] {"A1:C3", "B1:D3"}); // could be one region "A1:D3"
- cellRangeTest(new String[]{"A1:C3", "B1:D1"}, new String[] {"A1:C3", "B1:D1"}); // could be one region "A1:D3"
- }
-
- @SuppressWarnings("RedundantArrayCreation")
- @Test
- void testMergeCellRanges55380() {
- cellRangeTest(new String[]{"C1:D2", "C2:C3"}, new String[] {"C1:D2", "C2:C3"});
- cellRangeTest(new String[]{"A1:C3", "B2:D2"}, new String[] {"A1:C3", "B2:D2"});
- cellRangeTest(new String[]{"C9:D30", "C7:C31"}, new String[] {"C9:D30", "C7:C31"});
- }
-
-// void testResolveRangeOverlap() {
-// resolveRangeOverlapTest("C1:D2", "C2:C3");
-// }
-
- private void cellRangeTest(String[] input, String... expectedOutput) {
- CellRangeAddress[] inputArr = new CellRangeAddress[input.length];
- for(int i = 0;i < input.length;i++) {
- inputArr[i] = CellRangeAddress.valueOf(input[i]);
- }
- CellRangeAddress[] result = CellRangeUtil.mergeCellRanges(inputArr);
- verifyExpectedResult(result, expectedOutput);
- }
-
-// private void resolveRangeOverlapTest(String a, String b, String...expectedOutput) {
-// CellRangeAddress rangeA = CellRangeAddress.valueOf(a);
-// CellRangeAddress rangeB = CellRangeAddress.valueOf(b);
-// CellRangeAddress[] result = CellRangeUtil.resolveRangeOverlap(rangeA, rangeB);
-// verifyExpectedResult(result, expectedOutput);
-// }
-
- private void verifyExpectedResult(CellRangeAddress[] result, String... expectedOutput) {
- assertEquals(expectedOutput.length, result.length,
- "\nExpected: " + Arrays.toString(expectedOutput) + "\nHad: " + Arrays.toString(result));
- for(int i = 0;i < expectedOutput.length;i++) {
- assertEquals(expectedOutput[i], result[i].formatAsString(),
- "\nExpected: " + Arrays.toString(expectedOutput) + "\nHad: " + Arrays.toString(result));
- }
- }
-
- @Test
- void testValueOf() {
- CellRangeAddress cr1 = CellRangeAddress.valueOf("A1:B1");
- assertEquals(0, cr1.getFirstColumn());
- assertEquals(0, cr1.getFirstRow());
- assertEquals(1, cr1.getLastColumn());
- assertEquals(0, cr1.getLastRow());
-
- CellRangeAddress cr2 = CellRangeAddress.valueOf("B1");
- assertEquals(1, cr2.getFirstColumn());
- assertEquals(0, cr2.getFirstRow());
- assertEquals(1, cr2.getLastColumn());
- assertEquals(0, cr2.getLastRow());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java
deleted file mode 100644
index c0cb666800..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the AreaFormatRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestAreaFormatRecord {
- byte[] data = new byte[] {
- (byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0x00, // forecolor
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // backcolor
- (byte)0x01,(byte)0x00, // pattern
- (byte)0x01,(byte)0x00, // format
- (byte)0x4E,(byte)0x00, // forecolor index
- (byte)0x4D,(byte)0x00 // backcolor index
-
- };
-
- @Test
- void testLoad() {
- AreaFormatRecord record = new AreaFormatRecord(TestcaseRecordInputStream.create(0x100a, data));
- assertEquals( 0xFFFFFF, record.getForegroundColor());
- assertEquals( 0x000000, record.getBackgroundColor());
- assertEquals( 1, record.getPattern());
- assertEquals( 1, record.getFormatFlags());
- assertTrue(record.isAutomatic());
- assertFalse(record.isInvert());
- assertEquals( 0x4e, record.getForecolorIndex());
- assertEquals( 0x4d, record.getBackcolorIndex());
-
-
- assertEquals( 20, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- AreaFormatRecord record = new AreaFormatRecord();
- record.setForegroundColor( 0xFFFFFF );
- record.setBackgroundColor( 0x000000 );
- record.setPattern( (short)1 );
- record.setAutomatic( true );
- record.setInvert( false );
- record.setForecolorIndex( (short)0x4e );
- record.setBackcolorIndex( (short)0x4d );
-
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(AreaFormatRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java
deleted file mode 100644
index 638b32635c..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the AreaRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestAreaRecord {
- byte[] data = new byte[] {
- (byte)0x02,(byte)0x00 // format flags
- };
-
- @Test
- void testLoad() {
-
- AreaRecord record = new AreaRecord(TestcaseRecordInputStream.create(0x101A, data));
- assertEquals( 2, record.getFormatFlags());
- assertFalse(record.isStacked());
- assertTrue(record.isDisplayAsPercentage());
- assertFalse(record.isShadow());
-
- assertEquals( 6, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- AreaRecord record = new AreaRecord();
- record.setStacked( false );
- record.setDisplayAsPercentage( true );
- record.setShadow( false );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(AreaRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java
deleted file mode 100644
index 7e1a07f651..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the AxisLineFormatRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestAxisLineFormatRecord {
- byte[] data = new byte[] {
- (byte)0x01,(byte)0x00
- };
-
- @Test
- void testLoad() {
- AxisLineFormatRecord record = new AxisLineFormatRecord(TestcaseRecordInputStream.create(0x1021, data));
- assertEquals( AxisLineFormatRecord.AXIS_TYPE_MAJOR_GRID_LINE, record.getAxisType());
-
- assertEquals( 6, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- AxisLineFormatRecord record = new AxisLineFormatRecord();
- record.setAxisType( AxisLineFormatRecord.AXIS_TYPE_MAJOR_GRID_LINE );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(AxisLineFormatRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java
deleted file mode 100644
index 06c03ee0ca..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the AxisOptionsRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestAxisOptionsRecord {
- private static final byte[] data = {
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01,
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01,(byte)0x00,
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
- (byte)0x00,(byte)0xEF,(byte)0x00
- };
-
- @Test
- void testLoad() {
- AxisOptionsRecord record = new AxisOptionsRecord(TestcaseRecordInputStream.create(0x1062, data));
- assertEquals( 0, record.getMinimumCategory());
- assertEquals( 0, record.getMaximumCategory());
- assertEquals( 1, record.getMajorUnitValue());
- assertEquals( 0, record.getMajorUnit());
- assertEquals( 1, record.getMinorUnitValue());
- assertEquals( 0, record.getMinorUnit());
- assertEquals( 0, record.getBaseUnit());
- assertEquals( 0, record.getCrossingPoint());
- assertEquals( 239, record.getOptions());
- assertTrue(record.isDefaultMinimum());
- assertTrue(record.isDefaultMaximum());
- assertTrue(record.isDefaultMajor());
- assertTrue(record.isDefaultMinorUnit());
- assertFalse(record.isIsDate());
- assertTrue(record.isDefaultBase());
- assertTrue(record.isDefaultCross());
- assertTrue(record.isDefaultDateSettings());
-
- assertEquals( 22, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- AxisOptionsRecord record = new AxisOptionsRecord();
- record.setMinimumCategory( (short)0 );
- record.setMaximumCategory( (short)0 );
- record.setMajorUnitValue( (short)1 );
- record.setMajorUnit( (short)0 );
- record.setMinorUnitValue( (short)1 );
- record.setMinorUnit( (short)0 );
- record.setBaseUnit( (short)0 );
- record.setCrossingPoint( (short)0 );
- record.setOptions( (short)239 );
- record.setDefaultMinimum( true );
- record.setDefaultMaximum( true );
- record.setDefaultMajor( true );
- record.setDefaultMinorUnit( true );
- record.setIsDate( false );
- record.setDefaultBase( true );
- record.setDefaultCross( true );
- record.setDefaultDateSettings( true );
-
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(AxisOptionsRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java
deleted file mode 100644
index 0c77fbcf2d..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the AxisParentRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestAxisParentRecord {
- byte[] data = new byte[] {
- (byte)0x00,(byte)0x00, // axis type
- (byte)0x1D,(byte)0x02,(byte)0x00,(byte)0x00, // x
- (byte)0xDD,(byte)0x00,(byte)0x00,(byte)0x00, // y
- (byte)0x31,(byte)0x0B,(byte)0x00,(byte)0x00, // width
- (byte)0x56,(byte)0x0B,(byte)0x00,(byte)0x00 // height
- };
-
- @Test
- void testLoad() {
- AxisParentRecord record = new AxisParentRecord(TestcaseRecordInputStream.create(0x1041, data));
- assertEquals( AxisParentRecord.AXIS_TYPE_MAIN, record.getAxisType());
- assertEquals( 0x021d, record.getX());
- assertEquals( 0xdd, record.getY());
- assertEquals( 0x0b31, record.getWidth());
- assertEquals( 0x0b56, record.getHeight());
-
- assertEquals( 22, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- AxisParentRecord record = new AxisParentRecord();
- record.setAxisType( AxisParentRecord.AXIS_TYPE_MAIN );
- record.setX( 0x021d );
- record.setY( 0xdd );
- record.setWidth( 0x0b31 );
- record.setHeight( 0x0b56 );
-
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(AxisParentRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java
deleted file mode 100644
index 70b504c6ac..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the AxisRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestAxisRecord {
- byte[] data = new byte[] {
- (byte)0x00,(byte)0x00, // type
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00
- };
-
- @Test
- void testLoad() {
- AxisRecord record = new AxisRecord(TestcaseRecordInputStream.create(0x101d, data));
- assertEquals( AxisRecord.AXIS_TYPE_CATEGORY_OR_X_AXIS, record.getAxisType());
- assertEquals( 0, record.getReserved1());
- assertEquals( 0, record.getReserved2());
- assertEquals( 0, record.getReserved3());
- assertEquals( 0, record.getReserved4());
-
- assertEquals( 4 + 18, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- AxisRecord record = new AxisRecord();
- record.setAxisType( AxisRecord.AXIS_TYPE_CATEGORY_OR_X_AXIS );
- record.setReserved1( 0 );
- record.setReserved2( 0 );
- record.setReserved3( 0 );
- record.setReserved4( 0 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(AxisRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java
deleted file mode 100644
index 4a494d2f8b..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the AxisUsedRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestAxisUsedRecord {
- byte[] data = new byte[] {
- (byte)0x01,(byte)0x00,
- };
-
- @Test
- void testLoad() {
- AxisUsedRecord record = new AxisUsedRecord(TestcaseRecordInputStream.create(0x1046, data));
- assertEquals( 1, record.getNumAxis());
-
- assertEquals( 6, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- AxisUsedRecord record = new AxisUsedRecord();
- record.setNumAxis( (short)1 );
-
- byte[] recordBytes = record.serialize();
- confirmRecordEncoding(AxisUsedRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java
deleted file mode 100644
index 975f6c998f..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the BarRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestBarRecord {
- byte[] data = new byte[] {
- (byte)0x00,(byte)0x00, // bar space
- (byte)0x96,(byte)0x00, // category space
- (byte)0x00,(byte)0x00 // format flags
- };
-
- @Test
- void testLoad() {
- BarRecord record = new BarRecord(TestcaseRecordInputStream.create(0x1017, data));
- assertEquals( 0, record.getBarSpace());
- assertEquals( 0x96, record.getCategorySpace());
- assertEquals( 0, record.getFormatFlags());
- assertFalse(record.isHorizontal());
- assertFalse(record.isStacked());
- assertFalse(record.isDisplayAsPercentage());
- assertFalse(record.isShadow());
-
- assertEquals( 10, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- BarRecord record = new BarRecord();
- record.setBarSpace( (short)0 );
- record.setCategorySpace( (short)0x96 );
- record.setHorizontal( false );
- record.setStacked( false );
- record.setDisplayAsPercentage( false );
- record.setShadow( false );
-
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(BarRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java
deleted file mode 100644
index 87f020479b..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the CategorySeriesAxisRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestCategorySeriesAxisRecord {
- byte[] data = new byte[] {
- (byte)0x01,(byte)0x00, // crossing point
- (byte)0x01,(byte)0x00, // label frequency
- (byte)0x01,(byte)0x00, // tick mark frequency
- (byte)0x01,(byte)0x00 // options
- };
-
- @Test
- void testLoad() {
- CategorySeriesAxisRecord record = new CategorySeriesAxisRecord(TestcaseRecordInputStream.create(0x1020, data));
- assertEquals( 1, record.getCrossingPoint());
- assertEquals( 1, record.getLabelFrequency());
- assertEquals( 1, record.getTickMarkFrequency());
- assertEquals( 1, record.getOptions());
- assertTrue(record.isValueAxisCrossing());
- assertFalse(record.isCrossesFarRight());
- assertFalse(record.isReversed());
-
- assertEquals( 4 + 8, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- CategorySeriesAxisRecord record = new CategorySeriesAxisRecord();
- record.setCrossingPoint( (short)1 );
- record.setLabelFrequency( (short)1 );
- record.setTickMarkFrequency( (short)1 );
- record.setValueAxisCrossing( true );
- record.setCrossesFarRight( false );
- record.setReversed( false );
-
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(CategorySeriesAxisRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java
deleted file mode 100644
index 1341bce4b8..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.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.hssf.record.chart;
-
-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 org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link ChartFormatRecord} Test data taken directly from a real
- * Excel file.
- */
-final class TestChartFormatRecord {
- /**
- * This rather uninteresting data came from attachment 23347 of bug 46693 at
- * offsets 0x6BB2 and 0x7BAF
- */
- private static final byte[] data = HexRead.readFromString(
- "14 10 14 00 " // BIFF header
- + "00 00 00 00 00 00 00 00 "
- + "00 00 00 00 00 00 00 00 "
- + "00 00 00 00");
-
- /**
- * The correct size of a {@link ChartFormatRecord} is 20 bytes (not including header).
- */
- @Test
- void testLoad() {
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- ChartFormatRecord record = new ChartFormatRecord(in);
- assertNotEquals(2, in.remaining(), "Identified bug 44693d");
- assertEquals(0, in.remaining());
- assertEquals(24, record.getRecordSize());
-
- byte[] data2 = record.serialize();
- assertArrayEquals(data, data2);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java
deleted file mode 100644
index a2eaa8fa43..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the ChartRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestChartRecord {
- byte[] data = new byte[] {
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
- (byte)0xE8,(byte)0xFF,(byte)0xD0,(byte)0x01,
- (byte)0xC8,(byte)0xCC,(byte)0xE5,(byte)0x00
- };
-
- @Test
- void testLoad() {
- ChartRecord record = new ChartRecord(TestcaseRecordInputStream.create(0x1002, data));
- assertEquals( 0, record.getX());
- assertEquals( 0, record.getY());
- assertEquals( 30474216, record.getWidth());
- assertEquals( 15060168, record.getHeight());
-
- assertEquals( 20, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- ChartRecord record = new ChartRecord();
- record.setX( 0 );
- record.setY( 0 );
- record.setWidth( 30474216 );
- record.setHeight( 15060168 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(ChartRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java
deleted file mode 100644
index e719910ddf..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
-import org.apache.poi.hssf.eventusermodel.HSSFListener;
-import org.apache.poi.hssf.eventusermodel.HSSFRequest;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.junit.jupiter.api.Test;
-
-final class TestChartTitleFormatRecord {
-
- @Test
- void testRecord() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(
- HSSFTestDataSamples.getSampleFile("WithFormattedGraphTitle.xls"));
-
- // Check we can open the file via usermodel
- HSSFWorkbook hssf = new HSSFWorkbook(fs);
-
- // Now process it through eventusermodel, and
- // look out for the title records
- ChartTitleFormatRecordGrabber grabber = new ChartTitleFormatRecordGrabber();
- InputStream din = fs.createDocumentInputStream("Workbook");
- HSSFRequest req = new HSSFRequest();
- req.addListenerForAllRecords(grabber);
- HSSFEventFactory factory = new HSSFEventFactory();
- factory.processEvents(req, din);
- din.close();
-
- // Should've found one
- assertEquals(1, grabber.chartTitleFormatRecords.size());
- // And it should be of something interesting
- ChartTitleFormatRecord r = grabber.chartTitleFormatRecords.get(0);
- assertEquals(3, r.getFormatCount());
-
- hssf.close();
- fs.close();
-
- }
-
- private static final class ChartTitleFormatRecordGrabber implements HSSFListener {
- private final List chartTitleFormatRecords;
-
- ChartTitleFormatRecordGrabber() {
- chartTitleFormatRecords = new ArrayList<>();
- }
-
- @Override
- public void processRecord(org.apache.poi.hssf.record.Record record) {
- if(record instanceof ChartTitleFormatRecord) {
- chartTitleFormatRecords.add((ChartTitleFormatRecord)record);
- }
- }
-
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.java
deleted file mode 100644
index 8511d1cdf5..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the DatRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestDatRecord {
- byte[] data = new byte[] {
- (byte)0x0D,(byte)0x00 // options
- };
-
- @Test
- void testLoad() {
- DatRecord record = new DatRecord(TestcaseRecordInputStream.create(0x1063, data));
- assertEquals( 0xD, record.getOptions());
- assertTrue(record.isHorizontalBorder());
- assertFalse(record.isVerticalBorder());
- assertTrue(record.isBorder());
- assertTrue(record.isShowSeriesKey());
-
- assertEquals( 6, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- DatRecord record = new DatRecord();
- record.setHorizontalBorder( true );
- record.setVerticalBorder( false );
- record.setBorder( true );
- record.setShowSeriesKey( true );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(DatRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java
deleted file mode 100644
index a146408400..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the DataFormatRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestDataFormatRecord {
- byte[] data = new byte[] {
- (byte)0xFF,(byte)0xFF, // point number
- (byte)0x00,(byte)0x00, // series index
- (byte)0x00,(byte)0x00, // series number
- (byte)0x00,(byte)0x00 // format flags
- };
-
- @Test
- void testLoad() {
- DataFormatRecord record = new DataFormatRecord(TestcaseRecordInputStream.create(0x1006, data));
- assertEquals( (short)0xFFFF, record.getPointNumber());
- assertEquals( 0, record.getSeriesIndex());
- assertEquals( 0, record.getSeriesNumber());
- assertEquals( 0, record.getFormatFlags());
- assertFalse(record.isUseExcel4Colors());
-
- assertEquals( 12, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- DataFormatRecord record = new DataFormatRecord();
- record.setPointNumber( (short)0xFFFF );
- record.setSeriesIndex( (short)0 );
- record.setSeriesNumber( (short)0 );
- record.setFormatFlags( (short)0 );
- record.setUseExcel4Colors( false );
-
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(DataFormatRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java
deleted file mode 100644
index 6ebf3a6191..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the DefaultDataLabelTextPropertiesRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestDefaultDataLabelTextPropertiesRecord {
- byte[] data = new byte[] {
- (byte)0x02,(byte)0x00
- };
-
- @Test
- void testLoad() {
-
- DefaultDataLabelTextPropertiesRecord record = new DefaultDataLabelTextPropertiesRecord(TestcaseRecordInputStream.create(0x1024, data));
- assertEquals( 2, record.getCategoryDataType());
-
- assertEquals( 6, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- DefaultDataLabelTextPropertiesRecord record = new DefaultDataLabelTextPropertiesRecord();
- record.setCategoryDataType( (short)2 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(DefaultDataLabelTextPropertiesRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java
deleted file mode 100644
index 5042e5663d..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the FontBasisRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestFontBasisRecord {
- byte[] data = new byte[] {
- (byte)0x28,(byte)0x1A, // x basis
- (byte)0x9C,(byte)0x0F, // y basis
- (byte)0xC8,(byte)0x00, // height basis
- (byte)0x00,(byte)0x00, // scale
- (byte)0x05,(byte)0x00 // index to font table
- };
-
- @Test
- void testLoad() {
- FontBasisRecord record = new FontBasisRecord(TestcaseRecordInputStream.create(0x1060, data));
- assertEquals( 0x1a28, record.getXBasis());
- assertEquals( 0x0f9c, record.getYBasis());
- assertEquals( 0xc8, record.getHeightBasis());
- assertEquals( 0x00, record.getScale());
- assertEquals( 0x05, record.getIndexToFontTable());
-
- assertEquals( 14, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- FontBasisRecord record = new FontBasisRecord();
- record.setXBasis( (short)0x1a28 );
- record.setYBasis( (short)0x0f9c );
- record.setHeightBasis( (short)0xc8 );
- record.setScale( (short)0x00 );
- record.setIndexToFontTable( (short)0x05 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(FontBasisRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java
deleted file mode 100644
index ca92378c8c..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the FontIndexRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestFontIndexRecord {
- byte[] data = new byte[] {
- (byte)0x05,(byte)0x00
- };
-
- @Test
- void testLoad() {
-
- FontIndexRecord record = new FontIndexRecord(TestcaseRecordInputStream.create(0x1026, data));
- assertEquals( 5, record.getFontIndex());
-
- assertEquals( 6, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- FontIndexRecord record = new FontIndexRecord();
- record.setFontIndex( (short)5 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(FontIndexRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java
deleted file mode 100644
index ca8ec3ca9b..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the FrameRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestFrameRecord {
- byte[] data = new byte[] {
- (byte)0x00,(byte)0x00, // border type
- (byte)0x02,(byte)0x00 // options
- };
-
- @Test
- void testLoad() {
- FrameRecord record = new FrameRecord(TestcaseRecordInputStream.create(0x1032, data));
- assertEquals( FrameRecord.BORDER_TYPE_REGULAR, record.getBorderType());
- assertEquals( 2, record.getOptions());
- assertFalse(record.isAutoSize());
- assertTrue(record.isAutoPosition());
-
- assertEquals( 8, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- FrameRecord record = new FrameRecord();
- record.setBorderType( FrameRecord.BORDER_TYPE_REGULAR );
- record.setOptions( (short)2 );
- record.setAutoSize( false );
- record.setAutoPosition( true );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(FrameRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java
deleted file mode 100644
index d5c995fd5b..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.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.hssf.record.chart;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the LegendRecord class works
- * correctly. Test data taken directly from a real Excel file.
- */
-final class TestLegendRecord {
- byte[] data = new byte[] { (byte) 0x76, (byte) 0x0E, (byte) 0x00, (byte) 0x00, (byte) 0x86,
- (byte) 0x07, (byte) 0x00, (byte) 0x00, (byte) 0x19, (byte) 0x01, (byte) 0x00,
- (byte) 0x00, (byte) 0x8B, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03,
- (byte) 0x01, (byte) 0x1F, (byte) 0x00 };
-
- @Test
- void testLoad() {
- LegendRecord record = new LegendRecord(TestcaseRecordInputStream.create(0x1015, data));
-
- assertEquals(0xe76, record.getXAxisUpperLeft());
-
- assertEquals(0x786, record.getYAxisUpperLeft());
-
- assertEquals(0x119, record.getXSize());
-
- assertEquals(0x8b, record.getYSize());
-
- assertEquals((byte) 0x3, record.getType());
-
- assertEquals((byte) 0x1, record.getSpacing());
-
- assertEquals((short) 0x1f, record.getOptions());
- assertTrue(record.isAutoPosition());
- assertTrue(record.isAutoSeries());
- assertTrue(record.isAutoXPositioning());
- assertTrue(record.isAutoYPositioning());
- assertTrue(record.isVertical());
- assertFalse(record.isDataTable());
-
- assertEquals(24, record.getRecordSize());
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- LegendRecord record = new LegendRecord();
-
- record.setXAxisUpperLeft(0xe76);
- record.setYAxisUpperLeft(0x786);
- record.setXSize(0x119);
- record.setYSize(0x8b);
- record.setType((byte) 0x3);
- record.setSpacing((byte) 0x1);
- record.setOptions((short) 0x1f);
- record.setAutoPosition(true);
- record.setAutoSeries(true);
- record.setAutoXPositioning(true);
- record.setAutoYPositioning(true);
- record.setVertical(true);
- record.setDataTable(false);
-
- byte[] recordBytes = record.serialize();
- confirmRecordEncoding(LegendRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java
deleted file mode 100644
index 89fd5e48e4..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the LineFormatRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestLineFormatRecord {
- byte[] data = new byte[] {
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // colour
- (byte)0x00,(byte)0x00, // pattern
- (byte)0x00,(byte)0x00, // weight
- (byte)0x01,(byte)0x00, // format
- (byte)0x4D,(byte)0x00 // index
- };
-
- @Test
- void testLoad() {
- LineFormatRecord record = new LineFormatRecord(TestcaseRecordInputStream.create(0x1007, data));
- assertEquals( 0, record.getLineColor());
- assertEquals( 0, record.getLinePattern());
- assertEquals( 0, record.getWeight());
- assertEquals( 1, record.getFormat());
- assertTrue(record.isAuto());
- assertFalse(record.isDrawTicks());
- assertEquals( 0x4d, record.getColourPaletteIndex());
-
- assertEquals( 16, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- LineFormatRecord record = new LineFormatRecord();
- record.setLineColor( 0 );
- record.setLinePattern( (short)0 );
- record.setWeight( (short)0 );
- record.setAuto( true );
- record.setDrawTicks( false );
- record.setColourPaletteIndex( (short)0x4d );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(LineFormatRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java
deleted file mode 100644
index b21fd2d71d..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.apache.poi.ss.formula.ptg.Area3DPtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the LinkedDataRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestLinkedDataRecord {
-
-/*
- The records below are records that would appear in a simple bar chart
-
- The first record links to the series title (linkType = 0). It's
- reference type is 1 which means that it links directly to data entered
- into the forumula bar. There seems to be no reference to any data
- however. The formulaOfLink field contains two 0 bytes. This probably
- means that there is no particular heading set.
-
-
-============================================
-Offset 0xf9c (3996)
-rectype = 0x1051, recsize = 0x8
--BEGIN DUMP---------------------------------
-00000000 00 01 00 00 00 00 00 00 ........
--END DUMP-----------------------------------
-recordid = 0x1051, size =8
-[AI]
-.linkType = 0x00 (0 )
-.referenceType = 0x01 (1 )
-.options = 0x0000 (0 )
- .customNumberFormat = false
-.indexNumberFmtRecord = 0x0000 (0 )
-.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@95fd19 )
-[/AI]
-
-
- The second record links to the series data (linkType=1). The
- referenceType = 2 which means it's linked to the worksheet.
- It links using a formula. The formula value is
- 0B 00 3B 00 00 00 00 1E 00 01 00 01 00.
-
- 0B 00 11 bytes length
- 3B (tArea3d) Rectangular area
- 00 00 index to REF entry in extern sheet
- 00 00 index to first row
- 1E 00 index to last row
- 01 00 index to first column and relative flags
- 01 00 index to last column and relative flags
-
-============================================
-Offset 0xfa8 (4008)
-rectype = 0x1051, recsize = 0x13
--BEGIN DUMP---------------------------------
-00000000 01 02 00 00 00 00 0B 00 3B 00 00 00 00 1E 00 01 ........;.......
-00000010 00 01 00 ...
--END DUMP-----------------------------------
-recordid = 0x1051, size =19
-[AI]
-.linkType = 0x01 (1 )
-.referenceType = 0x02 (2 )
-.options = 0x0000 (0 )
- .customNumberFormat = false
-.indexNumberFmtRecord = 0x0000 (0 )
-.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@11b9fb1 )
-[/AI]
-
- The third record links to the series categories (linkType=2). The
- reference type of 2 means that it's linked to the worksheet.
- It links using a formula. The formula value is
- 0B 00 3B 00 00 00 00 1E 00 01 00 01 00
-
- 0B 00 11 bytes in length
- 3B (tArea3d) Rectangular area
- 00 00 index to REF entry in extern sheet
- 00 00 index to first row
- 00 1F index to last row
- 00 00 index to first column and relative flags
- 00 00 index to last column and relative flags
-
-
-============================================
-Offset 0xfbf (4031)
-rectype = 0x1051, recsize = 0x13
--BEGIN DUMP---------------------------------
-00000000 02 02 00 00 69 01 0B 00 3B 00 00 00 00 1F 00 00 ....i...;.......
-00000010 00 00 00 ...
--END DUMP-----------------------------------
-recordid = 0x1051, size =19
-[AI]
-.linkType = 0x02 (2 )
-.referenceType = 0x02 (2 )
-.options = 0x0000 (0 )
- .customNumberFormat = false
-.indexNumberFmtRecord = 0x0169 (361 )
-.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@913fe2 )
-[/AI]
-
-This third link type does not seem to be documented and does not appear to
-contain any useful information anyway.
-
-============================================
-Offset 0xfd6 (4054)
-rectype = 0x1051, recsize = 0x8
--BEGIN DUMP---------------------------------
-00000000 03 01 00 00 00 00 00 00 ........
--END DUMP-----------------------------------
-recordid = 0x1051, size =8
-[AI]
-.linkType = 0x03 (3 )
-.referenceType = 0x01 (1 )
-.options = 0x0000 (0 )
- .customNumberFormat = false
-.indexNumberFmtRecord = 0x0000 (0 )
-.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@1f934ad )
-[/AI]
-
-*/
-
- byte[] data = new byte[]{
- (byte)0x01, // link type
- (byte)0x02, // reference type
- (byte)0x00,(byte)0x00, // options
- (byte)0x00,(byte)0x00, // index number format record
- (byte)0x0B,(byte)0x00, // 11 bytes length
- (byte)0x3B, // formula of link
- (byte)0x00,(byte)0x00, // index to ref entry in extern sheet
- (byte)0x00,(byte)0x00, // index to first row
- (byte)0x00,(byte)0x1F, // index to last row
- (byte)0x00,(byte)0x00, // index to first column and relative flags
- (byte)0x00,(byte)0x00, // index to last column and relative flags
- };
-
- @Test
- void testLoad() {
- LinkedDataRecord record = new LinkedDataRecord(TestcaseRecordInputStream.create(0x1051, data));
- assertEquals( LinkedDataRecord.LINK_TYPE_VALUES, record.getLinkType());
- assertEquals( LinkedDataRecord.REFERENCE_TYPE_WORKSHEET, record.getReferenceType());
- assertEquals( 0, record.getOptions());
- assertFalse(record.isCustomNumberFormat());
- assertEquals( 0, record.getIndexNumberFmtRecord());
-
- Area3DPtg ptgExpected = new Area3DPtg(0, 7936, 0, 0,
- false, false, false, false, 0);
-
- Ptg ptgActual = record.getFormulaOfLink()[0];
- assertEquals(ptgExpected.toString(), ptgActual.toString());
-
- assertEquals( data.length + 4, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- LinkedDataRecord record = new LinkedDataRecord();
- record.setLinkType( LinkedDataRecord.LINK_TYPE_VALUES );
- record.setReferenceType( LinkedDataRecord.REFERENCE_TYPE_WORKSHEET );
- record.setOptions( (short)0 );
- record.setCustomNumberFormat( false );
- record.setIndexNumberFmtRecord( (short)0 );
- Area3DPtg ptg = new Area3DPtg(0, 7936, 0, 0,
- false, false, false, false, 0);
- record.setFormulaOfLink(new Ptg[] { ptg, } );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(LinkedDataRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java
deleted file mode 100644
index 12c7cc7342..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the NumberFormatIndexRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestNumberFormatIndexRecord {
- byte[] data = new byte[] {
- 0x05,0x00
- };
-
- @Test
- void testLoad() {
- NumberFormatIndexRecord record = new NumberFormatIndexRecord(TestcaseRecordInputStream.create(0x104e, data));
- assertEquals( 5, record.getFormatIndex());
-
- assertEquals( 6, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- NumberFormatIndexRecord record = new NumberFormatIndexRecord();
- record.setFormatIndex( (short)5 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(NumberFormatIndexRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java
deleted file mode 100644
index cd0b87bbc8..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the ObjectLinkRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestObjectLinkRecord {
- byte[] data = new byte[] {
- (byte)0x03,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00
- };
-
- @Test
- void testLoad() {
- ObjectLinkRecord record = new ObjectLinkRecord(TestcaseRecordInputStream.create(0x1027, data));
-
- assertEquals( (short)3, record.getAnchorId());
- assertEquals( (short)0x00, record.getLink1());
- assertEquals( (short)0x00, record.getLink2());
-
- assertEquals( 10, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- ObjectLinkRecord record = new ObjectLinkRecord();
-
- record.setAnchorId( (short)3 );
- record.setLink1( (short)0x00 );
- record.setLink2( (short)0x00 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(ObjectLinkRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java
deleted file mode 100644
index 2c9d42a8dc..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.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.hssf.record.chart;
-
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the PlotAreaRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestPlotAreaRecord {
- byte[] data = new byte[] {
-
- };
-
- @Test
- void testLoad() {
- PlotAreaRecord record = new PlotAreaRecord(TestcaseRecordInputStream.create(0x1035, data));
-
- assertEquals( 4, record.getRecordSize() );
- }
-
- @Test
- void testStore() {
- PlotAreaRecord record = new PlotAreaRecord();
-
- byte [] recordBytes = record.serialize();
- assertEquals(recordBytes.length - 4, data.length);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java
deleted file mode 100644
index 30435c76b7..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the PlotGrowthRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestPlotGrowthRecord {
- byte[] data = new byte[] {
- (byte)0x00,(byte)0x00,(byte)0x01,(byte)0x00, // horizontal
- (byte)0x00,(byte)0x00,(byte)0x01,(byte)0x00 // vertical
- };
-
- @Test
- void testLoad() {
-
- PlotGrowthRecord record = new PlotGrowthRecord(TestcaseRecordInputStream.create(0x1064, data));
- assertEquals( 65536, record.getHorizontalScale());
- assertEquals( 65536, record.getVerticalScale());
-
- assertEquals( 12, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- PlotGrowthRecord record = new PlotGrowthRecord();
- record.setHorizontalScale( 65536 );
- record.setVerticalScale( 65536 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(PlotGrowthRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java
deleted file mode 100644
index 1c6e886c90..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the SeriesChartGroupIndexRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestSeriesChartGroupIndexRecord {
- byte[] data = new byte[] {
- (byte)0x00,(byte)0x00
- };
-
- @Test
- void testLoad() {
- SeriesChartGroupIndexRecord record = new SeriesChartGroupIndexRecord(TestcaseRecordInputStream.create(0x1045, data));
- assertEquals( 0, record.getChartGroupIndex());
-
- assertEquals( 6, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- SeriesChartGroupIndexRecord record = new SeriesChartGroupIndexRecord();
- record.setChartGroupIndex( (short)0 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(SeriesChartGroupIndexRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java
deleted file mode 100644
index b4bad1d191..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the SeriesIndexRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestSeriesIndexRecord {
- byte[] data = new byte[] {
- (byte)0x03,(byte)0x00
- };
-
- @Test
- void testLoad() {
- SeriesIndexRecord record = new SeriesIndexRecord(TestcaseRecordInputStream.create(0x1065, data));
-
- assertEquals( (short)3, record.getIndex());
- assertEquals( 6, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- SeriesIndexRecord record = new SeriesIndexRecord();
- record.setIndex( (short)3 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(SeriesIndexRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java
deleted file mode 100644
index f20184d3ba..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the SeriesLabelsRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestSeriesLabelsRecord {
- byte[] data = new byte[] {
- (byte)0x03,(byte)0x00
- };
-
- @Test
- void testLoad() {
- SeriesLabelsRecord record = new SeriesLabelsRecord(TestcaseRecordInputStream.create(0x100c, data));
- assertEquals( 3, record.getFormatFlags());
- assertTrue(record.isShowActual());
- assertTrue(record.isShowPercent());
- assertFalse(record.isLabelAsPercentage());
- assertFalse(record.isSmoothedLine());
- assertFalse(record.isShowLabel());
- assertFalse(record.isShowBubbleSizes());
-
- assertEquals( 2+4, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- SeriesLabelsRecord record = new SeriesLabelsRecord();
- record.setShowActual( true );
- record.setShowPercent( true );
- record.setLabelAsPercentage( false );
- record.setSmoothedLine( false );
- record.setShowLabel( false );
- record.setShowBubbleSizes( false );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(SeriesLabelsRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java
deleted file mode 100644
index b75c579147..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the SeriesListRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestSeriesListRecord {
- private static final byte[] data = {
- (byte)0x02,(byte)0x00,(byte)0x01,(byte)0x20,(byte)0xff,(byte)0xf0
- };
-
- @Test
- void testLoad() {
-
- SeriesListRecord record = new SeriesListRecord(TestcaseRecordInputStream.create(0x1016, data));
- assertEquals( (short)0x2001, record.getSeriesNumbers()[0]);
- assertEquals( (short)0xf0ff, record.getSeriesNumbers()[1]);
- assertEquals( 2, record.getSeriesNumbers().length);
-
- assertEquals( 4 + 6, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- SeriesListRecord record = new SeriesListRecord(new short[] { (short)0x2001, (short)0xf0ff } );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(SeriesListRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java
deleted file mode 100644
index 8aac948d0c..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the SeriesRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestSeriesRecord {
- byte[] data = new byte[] {
- (byte)0x01,(byte)0x00, // category data type
- (byte)0x01,(byte)0x00, // values data type
- (byte)0x1B,(byte)0x00, // num categories
- (byte)0x1B,(byte)0x00, // num values
- (byte)0x01,(byte)0x00, // bubble series type
- (byte)0x00,(byte)0x00 // num bubble values
- };
-
- @Test
- void testLoad() {
- SeriesRecord record = new SeriesRecord(TestcaseRecordInputStream.create(0x1003, data));
- assertEquals( SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC, record.getCategoryDataType());
- assertEquals( SeriesRecord.VALUES_DATA_TYPE_NUMERIC, record.getValuesDataType());
- assertEquals( 27, record.getNumCategories());
- assertEquals( 27, record.getNumValues());
- assertEquals( SeriesRecord.BUBBLE_SERIES_TYPE_NUMERIC, record.getBubbleSeriesType());
- assertEquals( 0, record.getNumBubbleValues());
-
-
- assertEquals( 16, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- SeriesRecord record = new SeriesRecord();
- record.setCategoryDataType( SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC );
- record.setValuesDataType( SeriesRecord.VALUES_DATA_TYPE_NUMERIC );
- record.setNumCategories( (short)27 );
- record.setNumValues( (short)27 );
- record.setBubbleSeriesType( SeriesRecord.BUBBLE_SERIES_TYPE_NUMERIC );
- record.setNumBubbleValues( (short)0 );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(SeriesRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java
deleted file mode 100644
index 6e56904996..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.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.hssf.record.chart;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the SeriesTextRecord class
- * works correctly. Test data taken directly from a real Excel file.
- */
-final class TestSeriesTextRecord {
- private static final byte[] SIMPLE_DATA = HexRead
- .readFromString("00 00 0C 00 56 61 6C 75 65 20 4E 75 6D 62 65 72");
-
- @Test
- void testLoad() {
- SeriesTextRecord record = new SeriesTextRecord(TestcaseRecordInputStream.create(0x100d, SIMPLE_DATA));
-
- assertEquals((short) 0, record.getId());
- assertEquals("Value Number", record.getText());
-
- assertEquals(SIMPLE_DATA.length + 4, record.getRecordSize());
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- SeriesTextRecord record = new SeriesTextRecord();
-
- record.setId(0);
- record.setText("Value Number");
-
- byte[] recordBytes = record.serialize();
- confirmRecordEncoding(SeriesTextRecord.sid, SIMPLE_DATA, recordBytes);
- }
-
- @Test
- void testReserializeLongTitle() {
- // Hex dump from bug 45784 attachment 22560 streamOffset=0x0CD1
- byte[] data = HexRead.readFromString(
- "00 00, "
- + "82 "
- + "01 "
- + "50 00 6C 00 61 00 73 00 6D 00 61 00 20 00 4C 00 "
- + "65 00 76 00 65 00 6C 00 73 00 20 00 6F 00 66 00 "
- + "20 00 4C 00 2D 00 30 00 30 00 30 00 31 00 31 00 "
- + "31 00 32 00 32 00 32 00 2D 00 33 00 33 00 33 00 "
- + "58 00 34 00 34 00 34 00 20 00 69 00 6E 00 20 00 "
- + "53 00 44 00 20 00 72 00 61 00 74 00 0A 00 50 00 "
- + "4F 00 20 00 33 00 2E 00 30 00 20 00 6D 00 67 00 "
- + "2F 00 6B 00 67 00 20 00 28 00 35 00 2E 00 30 00 "
- + "20 00 6D 00 4C 00 2F 00 6B 00 67 00 29 00 20 00 "
- + "69 00 6E 00 20 00 4D 00 65 00 74 00 68 00 6F 00 "
- + "63 00 65 00 6C 00 0A 00 49 00 56 00 20 00 30 00 "
- + "2E 00 35 00 20 00 6D 00 67 00 2F 00 6B 00 67 00 "
- + "20 00 28 00 31 00 2E 00 30 00 20 00 6D 00 4C 00 "
- + "2F 00 6B 00 67 00 29 00 20 00 69 00 6E 00 20 00 "
- + "36 00 30 00 25 00 20 00 50 00 45 00 47 00 20 00 "
- + "32 00 30 00 30 00 0A 00 46 00 20 00 3D 00 61 00 "
- + "62 00 63 00");
-
- RecordInputStream in = TestcaseRecordInputStream.create(SeriesTextRecord.sid, data);
- // Identified bug 45784a
- // 'would be' error msg changed at svn r703620
- // "Illegal length - asked for -126 but only 130 left!"
- // "Bad requested string length (-126)"
- SeriesTextRecord str = new SeriesTextRecord(in);
-
- assertTrue(str.getRecordSize() >= 0, "Identified bug 45784b");
- byte[] ser = str.serialize();
- confirmRecordEncoding(SeriesTextRecord.sid, data, ser);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.java
deleted file mode 100644
index 21f03302c6..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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 org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link SheetPropertiesRecord}
- * Test data taken directly from a real Excel file.
- */
-final class TestSheetPropertiesRecord {
- private static final byte[] data = {
- (byte)0x0A,(byte)0x00,
- (byte)0x00,
- (byte)0x00, // not sure where that last byte comes from
- };
-
- @Test
- void testLoad() {
- RecordInputStream in = TestcaseRecordInputStream.create(0x1044, data);
- SheetPropertiesRecord record = new SheetPropertiesRecord(in);
- assertNotEquals(1, in.remaining(), "Identified bug 44693c");
- assertEquals(0, in.remaining());
- assertEquals( 10, record.getFlags());
- assertFalse(record.isChartTypeManuallyFormatted());
- assertTrue(record.isPlotVisibleOnly());
- assertFalse(record.isDoNotSizeWithWindow());
- assertTrue(record.isDefaultPlotDimensions());
- assertFalse(record.isAutoPlotArea());
- assertEquals( 0, record.getEmpty());
-
- assertEquals( 8, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- SheetPropertiesRecord record = new SheetPropertiesRecord();
- record.setChartTypeManuallyFormatted( false );
- record.setPlotVisibleOnly( true );
- record.setDoNotSizeWithWindow( false );
- record.setDefaultPlotDimensions( true );
- record.setAutoPlotArea( false );
- record.setEmpty( (byte)0 );
-
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(SheetPropertiesRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java
deleted file mode 100644
index 7628d9ce4f..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the TextRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestTextRecord {
- byte[] data = new byte[] {
- (byte)0x02, // horiz align
- (byte)0x02, // vert align
- (byte)0x01,(byte)0x00, // display mode
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // rgb color
- (byte)0xD6,(byte)0xFF,(byte)0xFF,(byte)0xFF, // x
- (byte)0xC4,(byte)0xFF,(byte)0xFF,(byte)0xFF, // y
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // width
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // height
- (byte)0xB1,(byte)0x00, // options 1
- (byte)0x4D,(byte)0x00, // index of color value
- (byte)0x50,(byte)0x2B, // options 2 -- strange upper bits supposed to be 0'd
- (byte)0x00,(byte)0x00 // text rotation
- };
-
- @Test
- void testLoad() {
- TextRecord record = new TextRecord(TestcaseRecordInputStream.create(0x1025, data));
- assertEquals( TextRecord.HORIZONTAL_ALIGNMENT_CENTER, record.getHorizontalAlignment());
- assertEquals( TextRecord.VERTICAL_ALIGNMENT_CENTER, record.getVerticalAlignment());
- assertEquals( TextRecord.DISPLAY_MODE_TRANSPARENT, record.getDisplayMode());
- assertEquals( 0, record.getRgbColor());
- assertEquals( -42, record.getX());
- assertEquals( -60, record.getY());
- assertEquals( 0, record.getWidth());
- assertEquals( 0, record.getHeight());
- assertEquals( 177, record.getOptions1());
- assertTrue(record.isAutoColor());
- assertFalse(record.isShowKey());
- assertFalse(record.isShowValue());
- assertFalse(record.isVertical());
- assertTrue(record.isAutoGeneratedText());
- assertTrue(record.isGenerated());
- assertFalse(record.isAutoLabelDeleted());
- assertTrue(record.isAutoBackground());
- assertEquals( TextRecord.ROTATION_NONE, record.getRotation() );
- assertFalse(record.isShowCategoryLabelAsPercentage());
- assertFalse(record.isShowValueAsPercentage());
- assertFalse(record.isShowBubbleSizes());
- assertFalse(record.isShowLabel());
- assertEquals( 77, record.getIndexOfColorValue());
- assertEquals( 11088, record.getOptions2());
- assertEquals( 0, record.getDataLabelPlacement() );
- assertEquals( 0, record.getTextRotation());
-
-
- assertEquals( 36, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- TextRecord record = new TextRecord();
- record.setHorizontalAlignment( TextRecord.HORIZONTAL_ALIGNMENT_CENTER );
- record.setVerticalAlignment( TextRecord.VERTICAL_ALIGNMENT_CENTER );
- record.setDisplayMode( TextRecord.DISPLAY_MODE_TRANSPARENT );
- record.setRgbColor( 0 );
- record.setX( -42 );
- record.setY( -60 );
- record.setWidth( 0 );
- record.setHeight( 0 );
- record.setAutoColor( true );
- record.setShowKey( false );
- record.setShowValue( false );
- record.setVertical( false );
- record.setAutoGeneratedText( true );
- record.setGenerated( true );
- record.setAutoLabelDeleted( false );
- record.setAutoBackground( true );
- record.setRotation( TextRecord.ROTATION_NONE );
- record.setShowCategoryLabelAsPercentage( false );
- record.setShowValueAsPercentage( false );
- record.setShowBubbleSizes( false );
- record.setShowLabel( false );
- record.setIndexOfColorValue( (short)77 );
- record.setOptions2( (short)0x2b50 );
-// record.setDataLabelPlacement( (short)0x2b50 );
- record.setTextRotation( (short)0 );
-
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(TextRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java
deleted file mode 100644
index dc1a0405bd..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the TickRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestTickRecord {
- private static final byte[] data = {
- (byte)0x02, (byte)0x00, (byte)0x03, (byte)0x01,
- (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
- (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
- (byte)0x00, (byte)0x00, (byte)0x00,
- (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
- (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x23, (byte)0x00,
- (byte)0x4D, (byte)0x00, (byte)0x00, (byte)0x00
- };
-
- @Test
- void testLoad() {
- TickRecord record = new TickRecord(TestcaseRecordInputStream.create(0x101e, data));
- assertEquals( (byte)2, record.getMajorTickType());
- assertEquals( (byte)0, record.getMinorTickType());
- assertEquals( (byte)3, record.getLabelPosition());
- assertEquals( (short)1, record.getBackground());
- assertEquals( 0, record.getLabelColorRgb());
- assertEquals( (short)0, record.getZero1());
- assertEquals( (short)0, record.getZero2());
- assertEquals( (short)35, record.getOptions());
- assertTrue(record.isAutoTextColor());
- assertTrue(record.isAutoTextBackground());
- assertEquals( (short)0x0, record.getRotation() );
- assertTrue(record.isAutorotate());
- assertEquals( (short)77, record.getTickColor());
- assertEquals( (short)0x0, record.getZero3());
-
-
- assertEquals( 34, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- TickRecord record = new TickRecord();
- record.setMajorTickType( (byte)2 );
- record.setMinorTickType( (byte)0 );
- record.setLabelPosition( (byte)3 );
- record.setBackground( (byte)1 );
- record.setLabelColorRgb( 0 );
- record.setZero1( (short)0 );
- record.setZero2( (short)0 );
- record.setOptions( (short)35 );
- record.setAutoTextColor( true );
- record.setAutoTextBackground( true );
- record.setRotation( (short)0 );
- record.setAutorotate( true );
- record.setTickColor( (short)77 );
- record.setZero3( (short)0 );
-
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(TickRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java
deleted file mode 100644
index 8d1294fa9b..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.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.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the UnitsRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestUnitsRecord {
- byte[] data = new byte[] {
- (byte)0x00, (byte)0x00
- };
-
- @Test
- void testLoad() {
-
- UnitsRecord record = new UnitsRecord(TestcaseRecordInputStream.create(0x1001, data));
- assertEquals( 0, record.getUnits());
-
- assertEquals( 6, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- UnitsRecord record = new UnitsRecord();
- record.setUnits( (short)0 );
-
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(UnitsRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java
deleted file mode 100644
index 0dc470d417..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.record.chart;
-
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-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.hssf.record.TestcaseRecordInputStream;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the serialization and deserialization of the ValueRangeRecord
- * class works correctly. Test data taken directly from a real
- * Excel file.
- */
-final class TestValueRangeRecord {
- byte[] data = new byte[] {
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // min axis value
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // max axis value
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // major increment
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // minor increment
- (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // cross over
- (byte)0x1F,(byte)0x01 // options
- };
-
- @Test
- void testLoad() {
-
- ValueRangeRecord record = new ValueRangeRecord(TestcaseRecordInputStream.create(0x101f, data));
- assertEquals( 0.0, record.getMinimumAxisValue(), 0.001);
- assertEquals( 0.0, record.getMaximumAxisValue(), 0.001);
- assertEquals( 0.0, record.getMajorIncrement(), 0.001);
- assertEquals( 0.0, record.getMinorIncrement(), 0.001);
- assertEquals( 0.0, record.getCategoryAxisCross(), 0.001);
- assertEquals( 0x011f, record.getOptions());
- assertTrue(record.isAutomaticMinimum());
- assertTrue(record.isAutomaticMaximum());
- assertTrue(record.isAutomaticMajor());
- assertTrue(record.isAutomaticMinor());
- assertTrue(record.isAutomaticCategoryCrossing());
- assertFalse(record.isLogarithmicScale());
- assertFalse(record.isValuesInReverse());
- assertFalse(record.isCrossCategoryAxisAtMaximum());
- assertTrue(record.isReserved());
-
- assertEquals( 42+4, record.getRecordSize() );
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testStore() {
- ValueRangeRecord record = new ValueRangeRecord();
- record.setMinimumAxisValue( 0 );
- record.setMaximumAxisValue( 0 );
- record.setMajorIncrement( 0 );
- record.setMinorIncrement( 0 );
- record.setCategoryAxisCross( 0 );
- record.setAutomaticMinimum( true );
- record.setAutomaticMaximum( true );
- record.setAutomaticMajor( true );
- record.setAutomaticMinor( true );
- record.setAutomaticCategoryCrossing( true );
- record.setLogarithmicScale( false );
- record.setValuesInReverse( false );
- record.setCrossCategoryAxisAtMaximum( false );
- record.setReserved( true );
-
- byte [] recordBytes = record.serialize();
- confirmRecordEncoding(ValueRangeRecord.sid, data, recordBytes);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java b/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java
deleted file mode 100644
index 45151b90ff..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.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.hssf.record.common;
-
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.poi.hssf.record.ContinueRecord;
-import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.hssf.record.SSTRecord;
-import org.apache.poi.hssf.record.cont.ContinuableRecordOutput;
-import org.apache.poi.hssf.usermodel.HSSFOptimiser;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-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.util.LittleEndianByteArrayInputStream;
-import org.apache.poi.util.LittleEndianByteArrayOutputStream;
-import org.apache.poi.util.LittleEndianConsts;
-import org.apache.poi.util.LittleEndianInput;
-import org.apache.poi.util.LittleEndianInputStream;
-import org.apache.poi.util.LittleEndianOutputStream;
-import org.apache.poi.util.StringUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests that {@link UnicodeString} record size calculates correctly. The record size
- * is used when serializing {@link SSTRecord}s.
- *
- * @author Jason Height (jheight at apache.org)
- */
-final class TestUnicodeString {
- private static final int MAX_DATA_SIZE = RecordInputStream.MAX_RECORD_DATA_SIZE;
-
- /** a 4 character string requiring 16 bit encoding */
- private static final String STR_16_BIT = "A\u591A\u8A00\u8A9E";
-
- private static void confirmSize(int expectedSize, UnicodeString s) {
- confirmSize(expectedSize, s, 0);
- }
-
- /**
- * Note - a value of zero for amountUsedInCurrentRecord would only ever occur just
- * after a {@link ContinueRecord} had been started. In the initial {@link SSTRecord} this
- * value starts at 8 (for the first {@link UnicodeString} written). In general, it can be
- * any value between 0 and {@link #MAX_DATA_SIZE}
- */
- private static void confirmSize(int expectedSize, UnicodeString s, int amountUsedInCurrentRecord) {
- ContinuableRecordOutput out = ContinuableRecordOutput.createForCountingOnly();
- out.writeContinue();
- for(int i=amountUsedInCurrentRecord; i>0; i--) {
- out.writeByte(0);
- }
- int size0 = out.getTotalSize();
- s.serialize(out);
- int size1 = out.getTotalSize();
- int actualSize = size1-size0;
- assertEquals(expectedSize, actualSize);
- }
-
- @Test
- void smallStringSize() {
- //Test a basic string
- UnicodeString s = makeUnicodeString("Test");
- confirmSize(7, s);
-
- //Test a small string that is uncompressed
- s = makeUnicodeString(STR_16_BIT);
- s.setOptionFlags((byte)0x01);
- confirmSize(11, s);
-
- //Test a compressed small string that has rich text formatting
- s.setString("Test");
- s.setOptionFlags((byte)0x8);
- FormatRun r = new FormatRun((short)0,(short)1);
- s.addFormatRun(r);
- FormatRun r2 = new FormatRun((short)2,(short)2);
- s.addFormatRun(r2);
- confirmSize(17, s);
-
- //Test a uncompressed small string that has rich text formatting
- s.setString(STR_16_BIT);
- s.setOptionFlags((byte)0x9);
- confirmSize(21, s);
-
- //Test a compressed small string that has rich text and extended text
- s.setString("Test");
- s.setOptionFlags((byte)0xC);
- confirmSize(17, s);
-
- // Extended phonetics data
- // Minimum size is 14
- // Also adds 4 bytes to hold the length
- s.setExtendedRst(
- new ExtRst()
- );
- confirmSize(35, s);
-
- //Test a uncompressed small string that has rich text and extended text
- s.setString(STR_16_BIT);
- s.setOptionFlags((byte)0xD);
- confirmSize(39, s);
-
- s.setExtendedRst(null);
- confirmSize(21, s);
- }
-
- @Test
- void perfectStringSize() {
- //Test a basic string
- UnicodeString s = makeUnicodeString(MAX_DATA_SIZE-2-1);
- confirmSize(MAX_DATA_SIZE, s);
-
- //Test an uncompressed string
- //Note that we can only ever get to a maximim size of 8227 since an uncompressed
- //string is writing double bytes.
- s = makeUnicodeString((MAX_DATA_SIZE-2-1)/2, true);
- s.setOptionFlags((byte)0x1);
- confirmSize(MAX_DATA_SIZE-1, s);
- }
-
- @Test
- void perfectRichStringSize() {
- //Test a rich text string
- UnicodeString s = makeUnicodeString(MAX_DATA_SIZE-2-1-8-2);
- s.addFormatRun(new FormatRun((short)1,(short)0));
- s.addFormatRun(new FormatRun((short)2,(short)1));
- s.setOptionFlags((byte)0x8);
- confirmSize(MAX_DATA_SIZE, s);
-
- //Test an uncompressed rich text string
- //Note that we can only ever get to a maximum size of 8227 since an uncompressed
- //string is writing double bytes.
- s = makeUnicodeString((MAX_DATA_SIZE-2-1-8-2)/2, true);
- s.addFormatRun(new FormatRun((short)1,(short)0));
- s.addFormatRun(new FormatRun((short)2,(short)1));
- s.setOptionFlags((byte)0x9);
- confirmSize(MAX_DATA_SIZE-1, s);
- }
-
- @Test
- void continuedStringSize() {
- //Test a basic string
- UnicodeString s = makeUnicodeString(MAX_DATA_SIZE-2-1+20);
- confirmSize(MAX_DATA_SIZE+4+1+20, s);
- }
-
- /** Tests that a string size calculation that fits neatly in two records, the second being a continue*/
- @Test
- void perfectContinuedStringSize() {
- //Test a basic string
- int strSize = MAX_DATA_SIZE*2;
- //String overhead
- strSize -= 3;
- //Continue Record overhead
- strSize -= 4;
- //Continue Record additional byte overhead
- strSize -= 1;
- UnicodeString s = makeUnicodeString(strSize);
- confirmSize(MAX_DATA_SIZE*2, s);
- }
-
- @Test
- void formatRun() {
- FormatRun fr = new FormatRun((short)4, (short)0x15c);
- assertEquals(4, fr.getCharacterPos());
- assertEquals(0x15c, fr.getFontIndex());
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- LittleEndianOutputStream out = new LittleEndianOutputStream(baos);
-
- fr.serialize(out);
-
- byte[] b = baos.toByteArray();
- assertEquals(4, b.length);
- assertEquals(4, b[0]);
- assertEquals(0, b[1]);
- assertEquals(0x5c, b[2]);
- assertEquals(0x01, b[3]);
-
- LittleEndianInputStream inp = new LittleEndianInputStream(
- new ByteArrayInputStream(b)
- );
- fr = new FormatRun(inp);
- assertEquals(4, fr.getCharacterPos());
- assertEquals(0x15c, fr.getFontIndex());
- }
-
- @Test
- void extRstFromEmpty() {
- ExtRst ext = new ExtRst();
-
- assertEquals(0, ext.getNumberOfRuns());
- assertEquals(0, ext.getFormattingFontIndex());
- assertEquals(0, ext.getFormattingOptions());
- assertEquals("", ext.getPhoneticText());
- assertEquals(0, ext.getPhRuns().length);
- assertEquals(10, ext.getDataSize()); // Excludes 4 byte header
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- LittleEndianOutputStream out = new LittleEndianOutputStream(baos);
- ContinuableRecordOutput cout = new ContinuableRecordOutput(out, 0xffff);
-
- ext.serialize(cout);
- cout.writeContinue();
-
- byte[] b = baos.toByteArray();
- assertEquals(20, b.length);
-
- // First 4 bytes from the outputstream
- assertEquals(-1, b[0]);
- assertEquals(-1, b[1]);
- assertEquals(14, b[2]);
- assertEquals(0, b[3]);
-
- // Reserved
- assertEquals(1, b[4]);
- assertEquals(0, b[5]);
- // Data size
- assertEquals(10, b[6]);
- assertEquals(0, b[7]);
- // Font*2
- assertEquals(0, b[8]);
- assertEquals(0, b[9]);
- assertEquals(0, b[10]);
- assertEquals(0, b[11]);
- // 0 Runs
- assertEquals(0, b[12]);
- assertEquals(0, b[13]);
- // Size=0, *2
- assertEquals(0, b[14]);
- assertEquals(0, b[15]);
- assertEquals(0, b[16]);
- assertEquals(0, b[17]);
-
- // Last 2 bytes from the outputstream
- assertEquals(ContinueRecord.sid, b[18]);
- assertEquals(0, b[19]);
-
-
- // Load in again and re-test
- byte[] data = Arrays.copyOfRange(b, 4, 4+14);
- LittleEndianInputStream inp = new LittleEndianInputStream(new ByteArrayInputStream(data));
- ext = new ExtRst(inp, data.length);
-
- assertEquals(0, ext.getNumberOfRuns());
- assertEquals(0, ext.getFormattingFontIndex());
- assertEquals(0, ext.getFormattingOptions());
- assertEquals("", ext.getPhoneticText());
- assertEquals(0, ext.getPhRuns().length);
- }
-
- @Test
- void extRstFromData() {
- byte[] data = new byte[] {
- 1, 0, 0x0C, 0,
- 0, 0, 0x37, 0,
- 0, 0,
- 0, 0, 0, 0,
- 0, 0 // Cruft at the end, as found from real files
- };
- assertEquals(16, data.length);
-
- LittleEndianInputStream inp = new LittleEndianInputStream(
- new ByteArrayInputStream(data)
- );
- ExtRst ext = new ExtRst(inp, data.length);
- assertEquals(0x0c, ext.getDataSize()); // Excludes 4 byte header
-
- assertEquals(0, ext.getNumberOfRuns());
- assertEquals(0x37, ext.getFormattingOptions());
- assertEquals(0, ext.getFormattingFontIndex());
- assertEquals("", ext.getPhoneticText());
- assertEquals(0, ext.getPhRuns().length);
- }
-
- @Test
- void corruptExtRstDetection() {
- byte[] data = new byte[] {
- 0x79, 0x79, 0x11, 0x11,
- 0x22, 0x22, 0x33, 0x33,
- };
- assertEquals(8, data.length);
-
- LittleEndianInputStream inp = new LittleEndianInputStream(
- new ByteArrayInputStream(data)
- );
- ExtRst ext = new ExtRst(inp, data.length);
-
- // Will be empty
- assertEquals(ext, new ExtRst());
-
- // If written, will be the usual size
- assertEquals(10, ext.getDataSize()); // Excludes 4 byte header
-
- // Is empty
- assertEquals(0, ext.getNumberOfRuns());
- assertEquals(0, ext.getFormattingOptions());
- assertEquals(0, ext.getFormattingFontIndex());
- assertEquals("", ext.getPhoneticText());
- assertEquals(0, ext.getPhRuns().length);
- }
-
- @Test
- void extRstEqualsAndHashCode() {
- byte[] buf = new byte[200];
- LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(buf, 0);
- String str = "\u1d02\u1d12\u1d22";
- bos.writeShort(1);
- bos.writeShort(5*LittleEndianConsts.SHORT_SIZE+str.length()*2+3*LittleEndianConsts.SHORT_SIZE+2); // data size
- bos.writeShort(0x4711);
- bos.writeShort(0x0815);
- bos.writeShort(1);
- bos.writeShort(str.length());
- bos.writeShort(str.length());
- StringUtil.putUnicodeLE(str, bos);
- bos.writeShort(1);
- bos.writeShort(1);
- bos.writeShort(3);
- bos.writeShort(42);
-
- LittleEndianInput in = new LittleEndianByteArrayInputStream(buf, 0, bos.getWriteIndex());
- ExtRst extRst1 = new ExtRst(in, bos.getWriteIndex());
- in = new LittleEndianByteArrayInputStream(buf, 0, bos.getWriteIndex());
- ExtRst extRst2 = new ExtRst(in, bos.getWriteIndex());
-
- assertEquals(extRst1, extRst2);
- assertEquals(extRst1.hashCode(), extRst2.hashCode());
- }
-
- @Test
- void unicodeStringsNullPointer() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
-
- Sheet sheet = wb.createSheet("styles");
- Row row = sheet.createRow(0);
- Cell cell = row.createCell(0);
-
- CellStyle style = wb.createCellStyle();
- style.setFont(wb.createFont());
- cell.setCellStyle(style);
-
- cell.setCellValue("test");
-
- assertDoesNotThrow(() -> HSSFOptimiser.optimiseFonts(wb));
- }
- }
-
- @Test
- void copyExtRst() {
- ExtRst ext = new ExtRst();
-
- assertEquals(0, ext.getNumberOfRuns());
- assertEquals(0, ext.getFormattingFontIndex());
- assertEquals(0, ext.getFormattingOptions());
- assertEquals("", ext.getPhoneticText());
- assertEquals(0, ext.getPhRuns().length);
- assertEquals(10, ext.getDataSize()); // Excludes 4 byte header
-
- ExtRst copied = ext.copy();
-
- assertEquals(0, copied.getNumberOfRuns());
- assertEquals(0, copied.getFormattingFontIndex());
- assertEquals(0, copied.getFormattingOptions());
- assertEquals("", copied.getPhoneticText());
- assertEquals(0, copied.getPhRuns().length);
- assertEquals(10, copied.getDataSize());
- }
-
- @Test
- void copyExtRstFromData() {
- byte[] data = new byte[]{
- 1, 0, 0x0C, 0,
- 0, 0, 0x37, 0,
- 0, 0,
- 0, 0, 0, 0,
- 0, 0 // Cruft at the end, as found from real files
- };
- assertEquals(16, data.length);
-
- LittleEndianInputStream inp = new LittleEndianInputStream(
- new ByteArrayInputStream(data)
- );
- ExtRst ext = new ExtRst(inp, data.length);
- assertEquals(0x0c, ext.getDataSize()); // Excludes 4 byte header
-
- assertEquals(0, ext.getNumberOfRuns());
- assertEquals(0x37, ext.getFormattingOptions());
- assertEquals(0, ext.getFormattingFontIndex());
- assertEquals("", ext.getPhoneticText());
- assertEquals(0, ext.getPhRuns().length);
-
- ExtRst copied = ext.copy();
- assertEquals(10, copied.getDataSize()); // Excludes 4 byte header
-
- assertEquals(0, copied.getNumberOfRuns());
- assertEquals(0x37, copied.getFormattingOptions());
- assertEquals(0, copied.getFormattingFontIndex());
- assertEquals("", copied.getPhoneticText());
- assertEquals(0, copied.getPhRuns().length);
- }
-
- private static UnicodeString makeUnicodeString(String s) {
- UnicodeString st = new UnicodeString(s);
- st.setOptionFlags((byte)0);
- return st;
- }
-
- private static UnicodeString makeUnicodeString(int numChars) {
- return makeUnicodeString(numChars, false);
- }
-
- /**
- * @param is16Bit if true
the created string will have characters > 0x00FF
- * @return a string of the specified number of characters
- */
- private static UnicodeString makeUnicodeString(int numChars, boolean is16Bit) {
- StringBuilder b = new StringBuilder(numChars);
- int charBase = is16Bit ? 0x8A00 : 'A';
- for (int i = 0; i < numChars; i++) {
- char ch = (char) ((i % 16) + charBase);
- b.append(ch);
- }
- return makeUnicodeString(b.toString());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java
deleted file mode 100644
index 3cfe1dc277..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.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.hssf.record.pivot;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.apache.poi.hssf.record.pivottable.ExtendedPivotTableViewFieldsRecord;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link ExtendedPivotTableViewFieldsRecord}
- */
-final class TestExtendedPivotTableViewFieldsRecord {
-
- @Test
- void testSubNameNotPresent_bug46693() {
- // This data came from attachment 23347 of bug 46693 at offset 0xAA43
- byte[] data = HexRead.readFromString(
- "00 01 14 00" + // BIFF header
- "1E 14 00 0A FF FF FF FF 00 00 FF FF 00 00 00 00 00 00 00 00");
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- // bug 46693a - Expected to find a ContinueRecord in order to read remaining 65535 of 65535 chars
- ExtendedPivotTableViewFieldsRecord rec = new ExtendedPivotTableViewFieldsRecord(in);
-
- assertEquals(data.length, rec.getRecordSize());
- }
-
- @SuppressWarnings("squid:S2699")
- @Test
- void testOlderFormat_bug46918() {
- // There are 10 SXVDEX records in the file (not uploaded) that originated bugzilla 46918
- // They all had the following hex encoding:
- byte[] data = HexRead.readFromString("00 01 0A 00 1E 14 00 0A FF FF FF FF 00 00");
-
- RecordInputStream in = TestcaseRecordInputStream.create(data);
- // bug 46918 - Not enough data (0) to read requested (2) bytes
- ExtendedPivotTableViewFieldsRecord rec = new ExtendedPivotTableViewFieldsRecord(in);
-
- byte[] expReserData = HexRead.readFromString("1E 14 00 0A FF FF FF FF 00 00" +
- "FF FF 00 00 00 00 00 00 00 00");
-
- confirmRecordEncoding(ExtendedPivotTableViewFieldsRecord.sid, expReserData, rec.serialize());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java
deleted file mode 100644
index ff6ac5d019..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.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.hssf.record.pivot;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-
-import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.apache.poi.hssf.record.pivottable.PageItemRecord;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link PageItemRecord}
- */
-final class TestPageItemRecord {
- @Test
- void testMoreThanOneInfoItem_bug46917() {
- byte[] data = HexRead.readFromString("01 02 03 04 05 06 07 08 09 0A 0B 0C");
- RecordInputStream in = TestcaseRecordInputStream.create(PageItemRecord.sid, data);
- PageItemRecord rec = new PageItemRecord(in);
- assertNotEquals(6, in.remaining(), "Identified bug 46917");
- assertEquals(0, in.remaining());
-
- assertEquals(4+data.length, rec.getRecordSize());
- }
-
- @Test
- void testSerialize() {
- confirmSerialize("01 02 03 04 05 06");
- confirmSerialize("01 02 03 04 05 06 07 08 09 0A 0B 0C");
- confirmSerialize("01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12");
- }
-
- private static void confirmSerialize(String hexDump) {
- byte[] data = HexRead.readFromString(hexDump);
- RecordInputStream in = TestcaseRecordInputStream.create(PageItemRecord.sid, data);
- PageItemRecord rec = new PageItemRecord(in);
- assertEquals(0, in.remaining());
- assertEquals(4+data.length, rec.getRecordSize());
- byte[] data2 = rec.serialize();
- confirmRecordEncoding(PageItemRecord.sid, data, data2);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java
deleted file mode 100644
index ee05e1a4f4..0000000000
--- a/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.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.hssf.record.pivot;
-
-import static org.apache.poi.hssf.record.TestcaseRecordInputStream.confirmRecordEncoding;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-
-import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.hssf.record.TestcaseRecordInputStream;
-import org.apache.poi.hssf.record.pivottable.ViewFieldsRecord;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link ViewFieldsRecord}
- */
-final class TestViewFieldsRecord {
-
- @Test
- void testUnicodeFlag_bug46693() {
- byte[] data = HexRead.readFromString("01 00 01 00 01 00 04 00 05 00 00 6D 61 72 63 6F");
- RecordInputStream in = TestcaseRecordInputStream.create(ViewFieldsRecord.sid, data);
- ViewFieldsRecord rec = new ViewFieldsRecord(in);
- assertNotEquals(1, in.remaining(), "Identified bug 46693b");
- assertEquals(0, in.remaining());
- assertEquals(4+data.length, rec.getRecordSize());
- }
-
- @Test
- void testSerialize() {
- // This hex data was produced by changing the 'Custom Name' property,
- // available under 'Field Settings' from the 'PivotTable Field List' (Excel 2007)
- confirmSerialize("00 00 01 00 01 00 00 00 FF FF");
- confirmSerialize("01 00 01 00 01 00 04 00 05 00 00 6D 61 72 63 6F");
- confirmSerialize("01 00 01 00 01 00 04 00 0A 00 01 48 00 69 00 73 00 74 00 6F 00 72 00 79 00 2D 00 82 69 81 89");
- }
-
- private static void confirmSerialize(String hexDump) {
- byte[] data = HexRead.readFromString(hexDump);
- RecordInputStream in = TestcaseRecordInputStream.create(ViewFieldsRecord.sid, data);
- ViewFieldsRecord rec = new ViewFieldsRecord(in);
- assertEquals(0, in.remaining());
- assertEquals(4+data.length, rec.getRecordSize());
- byte[] data2 = rec.serialize();
- confirmRecordEncoding(ViewFieldsRecord.sid, data, data2);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/FormulaExtractor.java b/src/testcases/org/apache/poi/hssf/usermodel/FormulaExtractor.java
deleted file mode 100644
index c44b3c0c7b..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/FormulaExtractor.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.hssf.usermodel;
-
-import org.apache.poi.hssf.record.CellValueRecordInterface;
-import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
-import org.apache.poi.ss.formula.ptg.Ptg;
-
-/**
- * Test utility class to get Ptg arrays out of formula cells
- *
- * @author Josh Micich
- */
-public final class FormulaExtractor {
-
- private FormulaExtractor() {
- // no instances of this class
- }
-
- public static Ptg[] getPtgs(HSSFCell cell) {
- CellValueRecordInterface vr = cell.getCellValueRecord();
- if (!(vr instanceof FormulaRecordAggregate)) {
- throw new IllegalArgumentException("Not a formula cell");
- }
- FormulaRecordAggregate fra = (FormulaRecordAggregate) vr;
- return fra.getFormulaRecord().getParsedExpression();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/HSSFEvaluationTestHelper.java b/src/testcases/org/apache/poi/hssf/usermodel/HSSFEvaluationTestHelper.java
deleted file mode 100644
index 96196c146e..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/HSSFEvaluationTestHelper.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import org.apache.poi.ss.formula.EvaluationCell;
-
-/**
- * Raises visibility of some internal functionality for test purposes
- *
- * @author Josh Micich
- */
-public final class HSSFEvaluationTestHelper {
-
- public static EvaluationCell wrapCell(HSSFCell cell) {
- return new HSSFEvaluationCell(cell);
- }
-
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/HSSFTestHelper.java b/src/testcases/org/apache/poi/hssf/usermodel/HSSFTestHelper.java
deleted file mode 100644
index 20a55c32ab..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/HSSFTestHelper.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import org.apache.poi.ddf.*;
-import org.apache.poi.hssf.model.DrawingManager2;
-import org.apache.poi.hssf.model.InternalSheet;
-import org.apache.poi.hssf.model.InternalWorkbook;
-import org.apache.poi.hssf.record.EscherAggregate;
-import org.apache.poi.hssf.record.ObjRecord;
-import org.apache.poi.hssf.record.TextObjectRecord;
-
-/**
- * Helper class for HSSF tests that aren't within the
- * HSSF UserModel package, but need to do internal
- * UserModel things.
- */
-public class HSSFTestHelper {
-
- public static class MockDrawingManager extends DrawingManager2 {
-
- public MockDrawingManager (){
- super(null);
- }
-
- @Override
- public int allocateShapeId(EscherDgRecord dg) {
- return 1025;
- }
-
- @Override
- public EscherDgRecord createDgRecord()
- {
- EscherDgRecord dg = new EscherDgRecord();
- dg.setRecordId( EscherDgRecord.RECORD_ID );
- dg.setOptions( (short) (16) );
- dg.setNumShapes( 1 );
- dg.setLastMSOSPID( 1024 );
- return dg;
- }
- }
- /**
- * Lets non UserModel tests at the low level Workbook
- */
- public static InternalWorkbook getWorkbookForTest(HSSFWorkbook wb) {
- return wb.getWorkbook();
- }
- public static InternalSheet getSheetForTest(HSSFSheet sheet) {
- return sheet.getSheet();
- }
-
- public static HSSFPatriarch createTestPatriarch(HSSFSheet sheet, EscherAggregate agg){
- return new HSSFPatriarch(sheet, agg);
- }
-
- public static EscherAggregate getEscherAggregate(HSSFPatriarch patriarch){
- return patriarch.getBoundAggregate();
- }
-
- public static int allocateNewShapeId(HSSFPatriarch patriarch){
- return patriarch.newShapeId();
- }
-
- public static EscherOptRecord getOptRecord(HSSFShape shape){
- return shape.getOptRecord();
- }
-
- public static void setShapeId(HSSFShape shape, int id){
- shape.setShapeId(id);
- }
-
- public static EscherContainerRecord getEscherContainer(HSSFShape shape){
- return shape.getEscherContainer();
- }
-
- public static TextObjectRecord getTextObjRecord(HSSFSimpleShape shape){
- return shape.getTextObjectRecord();
- }
-
- public static ObjRecord getObjRecord(HSSFShape shape){
- return shape.getObjRecord();
- }
-
- public static EscherRecord getEscherAnchor(HSSFAnchor anchor){
- return anchor.getEscherAnchor();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java b/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java
deleted file mode 100644
index 22d0676d51..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.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.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.List;
-
-import org.apache.poi.hssf.model.InternalSheet;
-import org.apache.poi.hssf.model.InternalWorkbook;
-import org.apache.poi.hssf.record.*;
-import org.apache.poi.hssf.record.aggregates.PageSettingsBlock;
-
-/**
- * Designed to check wither the records written actually make sense.
- */
-public class SanityChecker {
- static class CheckRecord {
- Class extends RecordBase> record;
- char occurance; // 1 = one time, M = 1..many times, * = 0..many, 0 = optional
- private final boolean together;
-
- public CheckRecord(Class extends RecordBase> record, char occurance) {
- this(record, occurance, true);
- }
-
- /**
- * @param record The record type to check
- * @param occurance The occurance 1 = occurs once, M = occurs many times
- * @param together
- */
- public CheckRecord(Class extends RecordBase> record, char occurance, boolean together) {
- this.record = record;
- this.occurance = occurance;
- this.together = together;
- }
-
- public Class extends RecordBase> getRecord() {
- return record;
- }
-
- public boolean isRequired() {
- return occurance == '1' || occurance == 'M';
- }
-
- public boolean isOptional() {
- return occurance == '0' || occurance == '*';
- }
-
- public boolean isMany() {
- return occurance == '*' || occurance == 'M';
- }
-
- public int match(List extends RecordBase> records, int recordIdx) {
- int firstRecord = findFirstRecord(records, getRecord(), recordIdx);
- if (isRequired()) {
- return matchRequired(firstRecord, records, recordIdx);
- }
- return matchOptional(firstRecord, records, recordIdx);
- }
-
- private int matchOptional(int firstRecord, List extends RecordBase> records, int recordIdx) {
- if (firstRecord == -1) {
- return recordIdx;
- }
-
- return matchOneOrMany(records, firstRecord);
- }
-
- private int matchRequired(int firstRecord, List extends RecordBase> records, int recordIdx) {
- assertNotEquals(-1, firstRecord, "Manditory record missing or out of order: " + record);
-
- return matchOneOrMany(records, firstRecord);
- }
-
- private int matchOneOrMany(List extends RecordBase> records, int recordIdx) {
- if (isZeroOrOne()) {
- // check no other records
- assertEquals(-1, findFirstRecord(records, getRecord(), recordIdx + 1),
- "More than one record matched for " + getRecord().getName());
- } else if (isZeroToMany()) {
- if (together) {
- int nextIdx = findFirstRecord(records, record, recordIdx + 1);
- while (nextIdx != -1) {
- assertEquals(recordIdx+1, nextIdx, "Records are not together " + record.getName());
- recordIdx = nextIdx;
- nextIdx = findFirstRecord(records, record, recordIdx + 1);
- }
- }
- }
- return recordIdx + 1;
- }
-
- private boolean isZeroToMany() {
- return occurance == '*' || occurance == 'M';
- }
-
- private boolean isZeroOrOne() {
- return occurance == '0' || occurance == '1';
- }
- }
-
- CheckRecord[] workbookRecords = {
- new CheckRecord(BOFRecord.class, '1'),
- new CheckRecord(InterfaceHdrRecord.class, '1'),
- new CheckRecord(MMSRecord.class, '1'),
- new CheckRecord(InterfaceEndRecord.class, '1'),
- new CheckRecord(WriteAccessRecord.class, '1'),
- new CheckRecord(CodepageRecord.class, '1'),
- new CheckRecord(DSFRecord.class, '1'),
- new CheckRecord(TabIdRecord.class, '1'),
- new CheckRecord(FnGroupCountRecord.class, '1'),
- new CheckRecord(WindowProtectRecord.class, '1'),
- new CheckRecord(ProtectRecord.class, '1'),
- new CheckRecord(PasswordRev4Record.class, '1'),
- new CheckRecord(WindowOneRecord.class, '1'),
- new CheckRecord(BackupRecord.class, '1'),
- new CheckRecord(HideObjRecord.class, '1'),
- new CheckRecord(DateWindow1904Record.class, '1'),
- new CheckRecord(PrecisionRecord.class, '1'),
- new CheckRecord(RefreshAllRecord.class, '1'),
- new CheckRecord(BookBoolRecord.class, '1'),
- new CheckRecord(FontRecord.class, 'M'),
- new CheckRecord(FormatRecord.class, 'M'),
- new CheckRecord(ExtendedFormatRecord.class, 'M'),
- new CheckRecord(StyleRecord.class, 'M'),
- new CheckRecord(UseSelFSRecord.class, '1'),
- new CheckRecord(BoundSheetRecord.class, 'M'),
- new CheckRecord(CountryRecord.class, '1'),
- new CheckRecord(SupBookRecord.class, '0'),
- new CheckRecord(ExternSheetRecord.class, '0'),
- new CheckRecord(NameRecord.class, '*'),
- new CheckRecord(SSTRecord.class, '1'),
- new CheckRecord(ExtSSTRecord.class, '1'),
- new CheckRecord(EOFRecord.class, '1'),
- };
-
- CheckRecord[] sheetRecords = {
- new CheckRecord(BOFRecord.class, '1'),
- new CheckRecord(CalcModeRecord.class, '1'),
- new CheckRecord(RefModeRecord.class, '1'),
- new CheckRecord(IterationRecord.class, '1'),
- new CheckRecord(DeltaRecord.class, '1'),
- new CheckRecord(SaveRecalcRecord.class, '1'),
- new CheckRecord(PrintHeadersRecord.class, '1'),
- new CheckRecord(PrintGridlinesRecord.class, '1'),
- new CheckRecord(GridsetRecord.class, '1'),
- new CheckRecord(GutsRecord.class, '1'),
- new CheckRecord(DefaultRowHeightRecord.class, '1'),
- new CheckRecord(WSBoolRecord.class, '1'),
- new CheckRecord(PageSettingsBlock.class, '1'),
- new CheckRecord(DefaultColWidthRecord.class, '1'),
- new CheckRecord(DimensionsRecord.class, '1'),
- new CheckRecord(WindowTwoRecord.class, '1'),
- new CheckRecord(SelectionRecord.class, '1'),
- new CheckRecord(EOFRecord.class, '1')
- };
-
- private void checkWorkbookRecords(InternalWorkbook workbook) {
- List records = workbook.getRecords();
- assertTrue(records.get(0) instanceof BOFRecord);
- assertTrue(records.get(records.size() - 1) instanceof EOFRecord);
-
- checkRecordOrder(records, workbookRecords);
- }
-
- private void checkSheetRecords(InternalSheet sheet) {
- List records = sheet.getRecords();
- assertTrue(records.get(0) instanceof BOFRecord);
- assertTrue(records.get(records.size() - 1) instanceof EOFRecord);
-
- checkRecordOrder(records, sheetRecords);
- }
-
- void checkHSSFWorkbook(HSSFWorkbook wb) {
- checkWorkbookRecords(wb.getWorkbook());
- for (int i = 0; i < wb.getNumberOfSheets(); i++)
- checkSheetRecords(wb.getSheetAt(i).getSheet());
-
- }
-
- static int findFirstRecord(List extends RecordBase> records, Class extends RecordBase> record, int startIndex) {
- for (int i = startIndex; i < records.size(); i++) {
- if (record.getName().equals(records.get(i).getClass().getName()))
- return i;
- }
- return -1;
- }
-
- void checkRecordOrder(List extends RecordBase> records, CheckRecord[] check) {
- int recordIdx = 0;
- for (CheckRecord element : check) {
- recordIdx = element.match(records, recordIdx);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/StreamUtility.java b/src/testcases/org/apache/poi/hssf/usermodel/StreamUtility.java
deleted file mode 100644
index d467333ffc..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/StreamUtility.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Utility class to help test code verify that generated files do not differ from proof copies in
- * any significant detail. Normally this task would be simple except for the presence of artifacts
- * in the file that change every time it is generated. Usually these volatile artifacts are
- * time-stamps, user names, or other machine dependent parameters.
- *
- * @author Josh Micich
- */
-public final class StreamUtility {
-
- /**
- * Compares two streams with expected differences in specified regions. The streams are
- * expected to be of equal length and comparison is always byte for byte. That is -
- * differences can only involve exchanging each individual byte for another single byte.
- * Both input streams are closed.
- *
- * @param allowableDifferenceRegions array of integer pairs: (offset, length).
- * Any differences encountered in these regions of the streams will be ignored
- * @return null
if streams are identical, else the
- * byte indexes of differing data. If streams were different lengths,
- * the returned indexes will be -1 and the length of the shorter stream
- */
- public static int[] diffStreams(InputStream isA, InputStream isB, int[] allowableDifferenceRegions) {
-
- if((allowableDifferenceRegions.length % 2) != 0) {
- throw new RuntimeException("allowableDifferenceRegions length is odd");
- }
- boolean success = false;
- int[] result;
- try {
- result = diffInternal(isA, isB, allowableDifferenceRegions);
- success = true;
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
- close(isA, success);
- close(isB, success);
- }
- return result;
- }
-
- /**
- * @param success false
if the outer method is throwing an exception.
- */
- private static void close(InputStream is, boolean success) {
- try {
- is.close();
- } catch (IOException e) {
- if(success) {
- // this is a new error. ok to throw
- throw new RuntimeException(e);
- }
- // else don't subvert original exception. just print stack trace for this one
- e.printStackTrace();
- }
- }
-
- private static int[] diffInternal(InputStream isA, InputStream isB, int[] allowableDifferenceRegions)
- throws IOException {
- int offset = 0;
- List temp = new ArrayList<>();
- while (true) {
- int b = isA.read();
- int b2 = isB.read();
- if (b == -1) {
- // EOF
- if (b2 == -1) {
- return toPrimitiveIntArray(temp);
- }
- return new int[] { -1, offset, };
- }
- if (b2 == -1) {
- return new int[] { -1, offset, };
- }
- if (b != b2 && !isIgnoredRegion(allowableDifferenceRegions, offset)) {
- temp.add(Integer.valueOf(offset));
- }
- offset++;
- }
- }
-
- private static boolean isIgnoredRegion(int[] allowableDifferenceRegions, int offset) {
- for (int i = 0; i < allowableDifferenceRegions.length; i+=2) {
- int start = allowableDifferenceRegions[i];
- int end = start + allowableDifferenceRegions[i+1];
- if(start <= offset && offset < end) {
- return true;
- }
- }
- return false;
- }
-
- private static int[] toPrimitiveIntArray(List temp) {
- int nItems = temp.size();
- if(nItems < 1) {
- return null;
- }
- Integer[] boxInts = new Integer[nItems];
- temp.toArray(boxInts);
-
- int[] result = new int[nItems];
- for (int i = 0; i < result.length; i++) {
- result[i] = boxInts[i].intValue();
- }
- return result;
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java b/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java
deleted file mode 100644
index 8a3008cb45..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import java.util.Iterator;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.FormulaRecord;
-import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
-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.Row;
-import org.apache.poi.ss.util.CellReference;
-import org.junit.jupiter.api.Test;
-
-/**
- *
- */
-final class TestBug42464 {
-
- @Test
- void testOKFile() throws Exception {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-ok.xls");
- process(wb);
- wb.close();
- }
-
- @Test
- void testExpSharedBadFile() throws Exception {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-bad.xls");
- process(wb);
- wb.close();
- }
-
- private static void process(HSSFWorkbook wb) {
- HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb);
- for(int i=0; i it = s.rowIterator();
- while(it.hasNext()) {
- HSSFRow r = (HSSFRow)it.next();
- process(r, eval);
- }
- }
- }
-
- private static void process(HSSFRow row, HSSFFormulaEvaluator eval) {
- Iterator it = row.cellIterator();
- while(it.hasNext()) {
- HSSFCell cell = (HSSFCell)it.next();
- if(cell.getCellType() != CellType.FORMULA) {
- continue;
- }
- FormulaRecordAggregate record = (FormulaRecordAggregate) cell.getCellValueRecord();
- FormulaRecord r = record.getFormulaRecord();
- /*Ptg[] ptgs =*/ r.getParsedExpression();
-
- /*String cellRef =*/ new CellReference(row.getRowNum(), cell.getColumnIndex(), false, false).formatAsString();
-// if(false && cellRef.equals("BP24")) { // TODO - replace System.out.println()s with asserts
-// System.out.print(cellRef);
-// System.out.println(" - has " + ptgs.length + " ptgs:");
-// for(int i=0; i " + cell.getCellFormula());
-// }
-
- CellValue evalResult = eval.evaluate(cell);
- assertNotNull(evalResult);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java
deleted file mode 100644
index b30f9f71ec..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java
+++ /dev/null
@@ -1,2607 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.apache.poi.POITestCase.assertContains;
-import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook;
-import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack;
-import static org.junit.jupiter.api.Assertions.*;
-
-import java.awt.image.BufferedImage;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-import java.util.TimeZone;
-import java.util.function.Consumer;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
-import javax.imageio.ImageIO;
-
-import org.apache.poi.hpsf.PropertySet;
-import org.apache.poi.hpsf.SummaryInformation;
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.extractor.ExcelExtractor;
-import org.apache.poi.hssf.model.InternalSheet;
-import org.apache.poi.hssf.model.InternalWorkbook;
-import org.apache.poi.hssf.record.CellValueRecordInterface;
-import org.apache.poi.hssf.record.CommonObjectDataSubRecord;
-import org.apache.poi.hssf.record.EmbeddedObjectRefSubRecord;
-import org.apache.poi.hssf.record.NameRecord;
-import org.apache.poi.hssf.record.TabIdRecord;
-import org.apache.poi.hssf.record.UnknownRecord;
-import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
-import org.apache.poi.hssf.record.aggregates.PageSettingsBlock;
-import org.apache.poi.hssf.record.common.UnicodeString;
-import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
-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.ss.formula.ptg.Area3DPtg;
-import org.apache.poi.ss.formula.ptg.DeletedArea3DPtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues;
-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.CellType;
-import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
-import org.apache.poi.ss.usermodel.ComparisonOperator;
-import org.apache.poi.ss.usermodel.DataFormatter;
-import org.apache.poi.ss.usermodel.FormulaError;
-import org.apache.poi.ss.usermodel.FormulaEvaluator;
-import org.apache.poi.ss.usermodel.Name;
-import org.apache.poi.ss.usermodel.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.SheetVisibility;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.Assumptions;
-import org.junit.jupiter.api.BeforeAll;
-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;
-
-/**
- * Testcases for bugs entered in bugzilla
- * the Test name contains the bugzilla bug id
- *
- * YK: If a bug can be tested in terms of common ss interfaces,
- * define the test in the base class {@link BaseTestBugzillaIssues}
- */
-final class TestBugs extends BaseTestBugzillaIssues {
-
- public TestBugs() {
- super(HSSFITestDataProvider.instance);
- }
-
- private static final Map SIMPLE_REFS = new LinkedHashMap<>();
-
- // References used for the simpleTest convenience method
- @BeforeAll
- public static void initSimpleRefs() {
- String[] refs = {
- "Calculations",
- "/Documents and Settings/crawformk.EUU/Local Settings/Temporary Internet Files/OLK64/Daily Status Report Generation Files/DST - Daily Data Transfer Sheet - 2002.xls",
- "Sheet1",
- "/Documents and Settings/donnag/Local Settings/Temporary Internet Files/OLK7/0231324V1-1.xls",
- "Sheet1",
- "refs/airport.xls",
- "Sheet1",
- "9http://www.principlesofeconometrics.com/excel/airline.xls",
- "Sheet1",
- "C:Documents and Settings/Yegor/My Documents/csco.xls",
- };
-
- for (int i=0; i assertNotNull(wb.getSheetAt(0).getRow(45)));
- }
-
- @Test
- void bug24215() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("24215.xls")) {
-
- for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
- HSSFSheet sheet = wb.getSheetAt(sheetIndex);
- assertNotNull(sheet);
- int rows = sheet.getLastRowNum();
-
- for (int rowIndex = 0; rowIndex < rows; rowIndex++) {
- HSSFRow row = sheet.getRow(rowIndex);
- assertNotNull(row);
- int cells = row.getLastCellNum();
-
- for (int cellIndex = 0; cellIndex < cells; cellIndex++) {
- row.getCell(cellIndex);
- }
- }
- }
- }
- }
-
- /**
- * Tests read and write of Unicode strings in formula results
- * bug and testcase submitted by Sompop Kumnoonsate
- * The file contains THAI unicode characters.
- */
- @Test
- void bugUnicodeStringFormulaRead() throws Exception {
-
- try (HSSFWorkbook w = openSampleWorkbook("25695.xls")) {
-
- HSSFCell a1 = w.getSheetAt(0).getRow(0).getCell(0);
- HSSFCell a2 = w.getSheetAt(0).getRow(0).getCell(1);
- HSSFCell b1 = w.getSheetAt(0).getRow(1).getCell(0);
- HSSFCell b2 = w.getSheetAt(0).getRow(1).getCell(1);
- HSSFCell c1 = w.getSheetAt(0).getRow(2).getCell(0);
- HSSFCell c2 = w.getSheetAt(0).getRow(2).getCell(1);
- HSSFCell d1 = w.getSheetAt(0).getRow(3).getCell(0);
- HSSFCell d2 = w.getSheetAt(0).getRow(3).getCell(1);
-
- /*
- // THAI code page
- System.out.println("a1="+unicodeString(a1));
- System.out.println("a2="+unicodeString(a2));
- // US code page
- System.out.println("b1="+unicodeString(b1));
- System.out.println("b2="+unicodeString(b2));
- // THAI+US
- System.out.println("c1="+unicodeString(c1));
- System.out.println("c2="+unicodeString(c2));
- // US+THAI
- System.out.println("d1="+unicodeString(d1));
- System.out.println("d2="+unicodeString(d2));
- */
-
- confirmSameCellText(a1, a2);
- confirmSameCellText(b1, b2);
- confirmSameCellText(c1, c2);
- confirmSameCellText(d1, d2);
-
- try (HSSFWorkbook rw = writeOutAndReadBack(w)) {
-
- HSSFCell ra1 = rw.getSheetAt(0).getRow(0).getCell(0);
- HSSFCell ra2 = rw.getSheetAt(0).getRow(0).getCell(1);
- HSSFCell rb1 = rw.getSheetAt(0).getRow(1).getCell(0);
- HSSFCell rb2 = rw.getSheetAt(0).getRow(1).getCell(1);
- HSSFCell rc1 = rw.getSheetAt(0).getRow(2).getCell(0);
- HSSFCell rc2 = rw.getSheetAt(0).getRow(2).getCell(1);
- HSSFCell rd1 = rw.getSheetAt(0).getRow(3).getCell(0);
- HSSFCell rd2 = rw.getSheetAt(0).getRow(3).getCell(1);
-
- confirmSameCellText(a1, ra1);
- confirmSameCellText(b1, rb1);
- confirmSameCellText(c1, rc1);
- confirmSameCellText(d1, rd1);
-
- confirmSameCellText(a1, ra2);
- confirmSameCellText(b1, rb2);
- confirmSameCellText(c1, rc2);
- confirmSameCellText(d1, rd2);
- }
- }
- }
-
- private static void confirmSameCellText(HSSFCell a, HSSFCell b) {
- assertEquals(a.getRichStringCellValue().getString(), b.getRichStringCellValue().getString());
- }
-
- /**
- * names and macros
- */
- @Test
- void bug27852() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("27852.xls")) {
- for (HSSFName name : wb.getAllNames()) {
- assertNotNull(name.getNameName());
- if (!name.isFunctionName()) {
- assertNotNull(name.getRefersToFormula());
- }
- }
- }
- }
-
- /**
- * Bug 29206: NPE on HSSFSheet.getRow for blank rows
- */
- @Test
- void bug29206() throws Exception {
- //the first check with blank workbook
- try (HSSFWorkbook wb = openSampleWorkbook("Simple.xls")) {
- HSSFSheet sheet = wb.createSheet();
- for (int i = 1; i < 400; i++) {
- HSSFRow row = sheet.getRow(i);
- assertNull(row);
- }
- }
- }
-
- /**
- * Bug 29942: Importing Excel files that have been created by Open Office on Linux
- */
- @Test
- void bug29942() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("29942.xls")) {
-
- HSSFSheet sheet = wb.getSheetAt(0);
- int count = 0;
- for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
- HSSFRow row = sheet.getRow(i);
- if (row != null) {
- HSSFCell cell = row.getCell(0);
- assertEquals(CellType.STRING, cell.getCellType());
- count++;
- }
- }
- assertEquals(85, count); //should read 85 rows
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) {
- assertNotNull(wb2.getSheetAt(0));
- }
- }
- }
-
- /**
- * Bug 30540: HSSFSheet.setRowBreak throws NullPointerException
- */
- @Test
- void bug30540() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("30540.xls")) {
-
- HSSFSheet s1 = wb.getSheetAt(0);
- s1.setRowBreak(1);
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) {
- HSSFSheet s2 = wb2.getSheetAt(0);
- int[] act = s2.getRowBreaks();
- int[] exp = { 1 };
- assertArrayEquals(exp, act);
- }
- }
- }
-
- /**
- * Bug 35564: HSSFCell.java: NullPtrExc in isGridsPrinted() and getProtect()
- * when HSSFWorkbook is created from file
- */
- @Test
- void bug35564() throws Exception {
- simpleTest("35564.xls", wb -> {
- HSSFSheet sheet = wb.getSheetAt(0);
- assertFalse(sheet.isGridsPrinted());
- assertFalse(sheet.getProtect());
- });
- }
-
- /**
- * Bug 35565: HSSFCell.java: NullPtrExc in getColumnBreaks() when HSSFWorkbook is created from file
- */
- @Test
- void bug35565() throws Exception {
- simpleTest("35565.xls", wb -> assertNotNull(wb.getSheetAt(0)));
- }
-
- /**
- * Bug 40285: CellIterator Skips First Column
- */
- @Test
- void bug40285() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("40285.xls")) {
-
- HSSFSheet sheet = wb.getSheetAt(0);
- int rownum = 0;
- for (Iterator it = sheet.rowIterator(); it.hasNext(); rownum++) {
- Row row = it.next();
- assertEquals(rownum, row.getRowNum());
- int cellNum = 0;
- for (Iterator it2 = row.cellIterator(); it2.hasNext(); cellNum++) {
- Cell cell = it2.next();
- assertEquals(cellNum, cell.getColumnIndex());
- }
- }
- }
- }
-
- /**
- * Test bug 38266: NPE when adding a row break
- *
- * User's diagnosis:
- * 1. Manually (i.e., not using POI) create an Excel Workbook, making sure it
- * contains a sheet that doesn't have any row breaks
- * 2. Using POI, create a new HSSFWorkbook from the template in step #1
- * 3. Try adding a row break (via sheet.setRowBreak()) to the sheet mentioned in step #1
- * 4. Get a NullPointerException
- */
- @Test
- void bug38266() throws Exception {
- String[] files = {"Simple.xls", "SimpleMultiCell.xls", "duprich1.xls"};
- for (String file : files) {
- try (HSSFWorkbook wb = openSampleWorkbook(file)) {
-
- HSSFSheet sheet = wb.getSheetAt(0);
- int[] breaks = sheet.getRowBreaks();
- assertEquals(0, breaks.length);
-
- //add 3 row breaks
- for (int j = 1; j <= 3; j++) {
- sheet.setRowBreak(j * 20);
- }
- }
- }
- }
-
- /**
- * Bug 44200: Sheet not cloneable when Note added to excel cell
- */
- @Test
- void bug44200() throws Exception {
- simpleTest("44200.xls", wb -> assertDoesNotThrow(() -> wb.cloneSheet(0)));
- }
-
- /**
- * Bug 41546: Constructing HSSFWorkbook is failed,
- * Unknown Ptg in Formula: 0x1a (26)
- */
- @Test
- void bug41546() throws Exception {
- simpleTest("41546.xls", wb -> assertEquals(1, wb.getNumberOfSheets()));
- }
-
- /**
- * Bug 42618: RecordFormatException reading a file containing
- * =CHOOSE(2,A2,A3,A4)
- */
- @Test
- void bug42618() throws Exception {
- try (HSSFWorkbook wb1 = openSampleWorkbook("SimpleWithChoose.xls");
- HSSFWorkbook wb2 = writeOutAndReadBack(wb1)){
- // Check we detect the string properly too
- HSSFSheet s = wb2.getSheetAt(0);
-
- // Textual value
- HSSFRow r1 = s.getRow(0);
- HSSFCell c1 = r1.getCell(1);
- assertEquals("=CHOOSE(2,A2,A3,A4)", c1.getRichStringCellValue().toString());
-
- // Formula Value
- HSSFRow r2 = s.getRow(1);
- HSSFCell c2 = r2.getCell(1);
- assertEquals(25, (int) c2.getNumericCellValue());
-
- try {
- assertEquals("CHOOSE(2,A2,A3,A4)", c2.getCellFormula());
- } catch (IllegalStateException e) {
- if (e.getMessage().startsWith("Too few arguments")
- && e.getMessage().indexOf("ConcatPtg") > 0) {
- fail("identified bug 44306");
- }
- }
- }
- }
-
- /**
- * Something up with the FileSharingRecord
- */
- @Test
- void bug43251() throws Exception {
- // Used to blow up with an IllegalArgumentException when creating a FileSharingRecord
- simpleTest("43251.xls", wb -> assertEquals(1, wb.getNumberOfSheets()));
- }
-
- /**
- * Crystal reports generates files with short
- * StyleRecords, which is against the spec
- */
- @Test
- void bug44471() throws Exception {
- // Used to blow up with an ArrayIndexOutOfBounds when creating a StyleRecord
- simpleTest("OddStyleRecord.xls", wb -> assertEquals(1, wb.getNumberOfSheets()));
- }
-
- /**
- * Files with "read only recommended" were giving
- * grief on the FileSharingRecord
- */
- @Test
- void bug44536() throws Exception {
- // Used to blow up with an IllegalArgumentException when creating a FileSharingRecord
- simpleTest("ReadOnlyRecommended.xls", wb -> {
- // Check read only advised
- assertEquals(3, wb.getNumberOfSheets());
- assertTrue(wb.isWriteProtected());
- });
-
-
- // But also check that another wb isn't
- simpleTest("SimpleWithChoose.xls", wb -> assertFalse(wb.isWriteProtected()));
- }
-
- /**
- * Some files were having problems with the DVRecord,
- * probably due to dropdowns
- */
- @Test
- void bug44593() throws Exception {
- // Used to blow up with an IllegalArgumentException when creating a DVRecord
- // Now won't, but no idea if this means we have rubbish in the DVRecord or not...
- simpleTest("44593.xls", wb -> assertEquals(2, wb.getNumberOfSheets()));
- }
-
- /**
- * Used to give problems due to trying to read a zero
- * length string, but that's now properly handled
- */
- @Test
- void bug44643() throws Exception {
- // Used to blow up with an IllegalArgumentException
- simpleTest("44643.xls", wb -> assertEquals(1, wb.getNumberOfSheets()));
- }
-
- /**
- * User reported the wrong number of rows from the
- * iterator, but we can't replicate that
- */
- @Test
- void bug44693() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("44693.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
-
- // Rows are 1 to 713
- assertEquals(0, s.getFirstRowNum());
- assertEquals(712, s.getLastRowNum());
- assertEquals(713, s.getPhysicalNumberOfRows());
-
- // Now check the iterator
- int rowsSeen = 0;
- for (Iterator i = s.rowIterator(); i.hasNext(); ) {
- Row r = i.next();
- assertNotNull(r);
- rowsSeen++;
- }
- assertEquals(713, rowsSeen);
- }
- }
-
- /**
- * Problems with extracting check boxes from
- * HSSFObjectData
- */
- @Test
- void bug44840() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("WithCheckBoxes.xls")) {
-
- // Take a look at the embedded objects
- List objects = wb.getAllEmbeddedObjects();
- assertEquals(1, objects.size());
-
- HSSFObjectData obj = objects.get(0);
- assertNotNull(obj);
-
- // Peek inside the underlying record
- EmbeddedObjectRefSubRecord rec = obj.findObjectRecord();
- assertNotNull(rec);
-
- // assertEquals(32, rec.field_1_stream_id_offset);
- assertEquals(0, rec.getStreamId().intValue()); // WRONG!
- assertEquals("Forms.CheckBox.1", rec.getOLEClassName());
- assertEquals(12, rec.getObjectData().length);
-
- // Doesn't have a directory
- assertFalse(obj.hasDirectoryEntry());
- assertNotNull(obj.getObjectData());
- assertEquals(12, obj.getObjectData().length);
- assertEquals("Forms.CheckBox.1", obj.getOLE2ClassName());
-
- assertThrows(IllegalArgumentException.class, obj::getDirectory);
- }
- }
-
- /**
- * Test that we can delete sheets without
- * breaking the build in named ranges
- * used for printing stuff.
- */
- @Test
- void bug30978() throws Exception {
- try (HSSFWorkbook wb1 = openSampleWorkbook("30978-alt.xls")) {
- assertEquals(1, wb1.getNumberOfNames());
- assertEquals(3, wb1.getNumberOfSheets());
-
- // Check all names fit within range, and use
- // DeletedArea3DPtg
- InternalWorkbook w = wb1.getWorkbook();
- assertNames(wb1, w);
-
- // Delete the 2nd sheet
- wb1.removeSheetAt(1);
-
- // Re-check
- assertEquals(1, wb1.getNumberOfNames());
- assertEquals(2, wb1.getNumberOfSheets());
- assertNames(wb1, w);
-
- // Save and re-load
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- w = wb2.getWorkbook();
-
- assertEquals(1, wb2.getNumberOfNames());
- assertEquals(2, wb2.getNumberOfSheets());
-
- assertNames(wb2, w);
- }
- }
- }
-
- private void assertNames(HSSFWorkbook wb1, InternalWorkbook w) {
- for (int i = 0; i < w.getNumNames(); i++) {
- NameRecord r = w.getNameRecord(i);
- assertTrue(r.getSheetNumber() <= wb1.getNumberOfSheets());
-
- Ptg[] nd = r.getNameDefinition();
- assertEquals(1, nd.length);
- assertTrue(nd[0] instanceof DeletedArea3DPtg);
- }
- }
-
- /**
- * Test that fonts get added properly
- */
- @Test
- void bug45338() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- assertEquals(4, wb.getNumberOfFonts());
-
- HSSFSheet s = wb.createSheet();
- s.createRow(0);
- s.createRow(1);
- s.getRow(0).createCell(0);
- s.getRow(1).createCell(0);
-
- assertEquals(4, wb.getNumberOfFonts());
-
- HSSFFont 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));
- assertEquals(wb.getFontAt(2), wb.getFontAt(2));
- assertNotSame(wb.getFontAt(0), wb.getFontAt(2));
-
- // Look for a new font we have yet to add
- assertNull(wb.findFont(false, (short) 123, (short) 22, "Thingy", false, true, (short) 2, (byte) 2));
-
- HSSFFont nf = wb.createFont();
- assertEquals(5, wb.getNumberOfFonts());
-
- assertEquals(5, nf.getIndex());
- assertEquals(nf, wb.getFontAt(5));
-
- nf.setBold(false);
- nf.setColor((short) 123);
- nf.setFontHeight((short) 22);
- nf.setFontName("Thingy");
- nf.setItalic(false);
- nf.setStrikeout(true);
- nf.setTypeOffset((short) 2);
- nf.setUnderline((byte) 2);
-
- assertEquals(5, wb.getNumberOfFonts());
- assertEquals(nf, wb.getFontAt(5));
-
- // Find it now
- assertNotNull(wb.findFont(false, (short) 123, (short) 22, "Thingy", false, true, (short) 2, (byte) 2));
- HSSFFont font = wb.findFont(false, (short) 123, (short) 22, "Thingy", false, true, (short) 2, (byte) 2);
- assertNotNull(font);
- assertEquals(5, font.getIndex());
- assertEquals(nf, wb.findFont(false, (short) 123, (short) 22, "Thingy", false, true, (short) 2, (byte) 2));
- }
- }
-
- /**
- * From the mailing list - ensure we can handle a formula
- * containing a zip code, eg ="70164"
- */
- @Test
- void bugZipCodeFormulas() throws Exception {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
- s.createRow(0);
- HSSFCell c1 = s.getRow(0).createCell(0);
- HSSFCell c2 = s.getRow(0).createCell(1);
- HSSFCell c3 = s.getRow(0).createCell(2);
-
- // As number and string
- c1.setCellFormula("70164");
- c2.setCellFormula("\"70164\"");
- c3.setCellFormula("\"90210\"");
-
- // Check the formulas
- assertEquals("70164", c1.getCellFormula());
- assertEquals("\"70164\"", c2.getCellFormula());
-
- // And check the values - blank
- confirmCachedValue(0.0, c1);
- confirmCachedValue(0.0, c2);
- confirmCachedValue(0.0, c3);
-
- // Try changing the cached value on one of the string
- // formula cells, so we can see it updates properly
- c3.setCellValue(new HSSFRichTextString("test"));
- confirmCachedValue("test", c3);
- IllegalStateException e = assertThrows(IllegalStateException.class, c3::getNumericCellValue);
- assertEquals("Cannot get a NUMERIC value from a STRING formula cell", e.getMessage());
-
- // Now evaluate, they should all be changed
- HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb1);
- eval.evaluateFormulaCell(c1);
- eval.evaluateFormulaCell(c2);
- eval.evaluateFormulaCell(c3);
-
- // Check that the cells now contain
- // the correct values
- confirmCachedValue(70164.0, c1);
- confirmCachedValue("70164", c2);
- confirmCachedValue("90210", c3);
-
-
- // Write and read
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- HSSFSheet ns = wb2.getSheetAt(0);
- HSSFCell nc1 = ns.getRow(0).getCell(0);
- HSSFCell nc2 = ns.getRow(0).getCell(1);
- HSSFCell nc3 = ns.getRow(0).getCell(2);
-
- // Re-check
- confirmCachedValue(70164.0, nc1);
- confirmCachedValue("70164", nc2);
- confirmCachedValue("90210", nc3);
-
- int i = 0;
- for (Iterator it = ns.getSheet().getCellValueIterator(); it.hasNext(); i++) {
- CellValueRecordInterface cvr = it.next();
- if (cvr instanceof FormulaRecordAggregate) {
- FormulaRecordAggregate fr = (FormulaRecordAggregate) cvr;
-
- if (i == 0) {
- assertEquals(70164.0, fr.getFormulaRecord().getValue(), 0.0001);
- assertNull(fr.getStringRecord());
- } else if (i == 1) {
- assertEquals(0.0, fr.getFormulaRecord().getValue(), 0.0001);
- assertNotNull(fr.getStringRecord());
- assertEquals("70164", fr.getStringRecord().getString());
- } else {
- assertEquals(0.0, fr.getFormulaRecord().getValue(), 0.0001);
- assertNotNull(fr.getStringRecord());
- assertEquals("90210", fr.getStringRecord().getString());
- }
- }
- }
- assertEquals(3, i);
- }
- }
- }
-
- private static void confirmCachedValue(double expectedValue, HSSFCell cell) {
- assertEquals(CellType.FORMULA, cell.getCellType());
- assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType());
- assertEquals(expectedValue, cell.getNumericCellValue(), 0.0);
- }
-
- private static void confirmCachedValue(String expectedValue, HSSFCell cell) {
- assertEquals(CellType.FORMULA, cell.getCellType());
- assertEquals(CellType.STRING, cell.getCachedFormulaResultType());
- assertEquals(expectedValue, cell.getRichStringCellValue().getString());
- }
-
- /**
- * Problem with "Vector Rows", eg a whole
- * column which is set to the result of
- * {=sin(B1:B9)}(9,1), so that each cell is
- * shown to have the contents
- * {=sin(B1:B9){9,1)[rownum][0]
- * In this sample file, the vector column
- * is C, and the data column is B.
- *
- * Expected ExpPtg to be converted from Shared to Non-Shared...
- */
- @Disabled("For now, blows up with an exception from ExtPtg")
- @Test
- void test43623() throws Exception {
- try (HSSFWorkbook wb1 = openSampleWorkbook("43623.xls")) {
- assertEquals(1, wb1.getNumberOfSheets());
-
- HSSFSheet s1 = wb1.getSheetAt(0);
-
- HSSFCell c1 = s1.getRow(0).getCell(2);
- HSSFCell c2 = s1.getRow(1).getCell(2);
- HSSFCell c3 = s1.getRow(2).getCell(2);
-
- // These formula contents are a guess...
- assertEquals("{=sin(B1:B9){9,1)[0][0]", c1.getCellFormula());
- assertEquals("{=sin(B1:B9){9,1)[1][0]", c2.getCellFormula());
- assertEquals("{=sin(B1:B9){9,1)[2][0]", c3.getCellFormula());
-
- // Save and re-open, ensure it still works
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- HSSFSheet ns1 = wb2.getSheetAt(0);
- HSSFCell nc1 = ns1.getRow(0).getCell(2);
- HSSFCell nc2 = ns1.getRow(1).getCell(2);
- HSSFCell nc3 = ns1.getRow(2).getCell(2);
-
- assertEquals("{=sin(B1:B9){9,1)[0][0]", nc1.getCellFormula());
- assertEquals("{=sin(B1:B9){9,1)[1][0]", nc2.getCellFormula());
- assertEquals("{=sin(B1:B9){9,1)[2][0]", nc3.getCellFormula());
- }
- }
- }
-
- /**
- * People are all getting confused about the last
- * row and cell number
- */
- @Test
- void bug30635() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
-
- // No rows, first/last return -1
- assertEquals(-1, s.getFirstRowNum());
- assertEquals(-1, s.getLastRowNum());
- assertEquals(0, s.getPhysicalNumberOfRows());
-
- // One row, most things are 0, physical is 1
- s.createRow(0);
- assertEquals(0, s.getFirstRowNum());
- assertEquals(0, s.getLastRowNum());
- assertEquals(1, s.getPhysicalNumberOfRows());
-
- // And another, things change
- s.createRow(4);
- assertEquals(0, s.getFirstRowNum());
- assertEquals(4, s.getLastRowNum());
- assertEquals(2, s.getPhysicalNumberOfRows());
-
-
- // Now start on cells
- HSSFRow r = s.getRow(0);
- assertEquals(-1, r.getFirstCellNum());
- assertEquals(-1, r.getLastCellNum());
- assertEquals(0, r.getPhysicalNumberOfCells());
-
- // Add a cell, things move off -1
- r.createCell(0);
- assertEquals(0, r.getFirstCellNum());
- assertEquals(1, r.getLastCellNum()); // last cell # + 1
- assertEquals(1, r.getPhysicalNumberOfCells());
-
- r.createCell(1);
- assertEquals(0, r.getFirstCellNum());
- assertEquals(2, r.getLastCellNum()); // last cell # + 1
- assertEquals(2, r.getPhysicalNumberOfCells());
-
- r.createCell(4);
- assertEquals(0, r.getFirstCellNum());
- assertEquals(5, r.getLastCellNum()); // last cell # + 1
- assertEquals(3, r.getPhysicalNumberOfCells());
-
- }
- }
-
- /**
- * Data Tables - ptg 0x2
- */
- @Test
- void bug44958() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("44958.xls")) {
- HSSFSheet s;
- HSSFRow r;
- HSSFCell c;
-
- // Check the contents of the formulas
-
- // E4 to G9 of sheet 4 make up the table
- s = wb.getSheet("OneVariable Table Completed");
- r = s.getRow(3);
- c = r.getCell(4);
- assertEquals(CellType.FORMULA, c.getCellType());
-
- // TODO - check the formula once tables and
- // arrays are properly supported
-
-
- // E4 to H9 of sheet 5 make up the table
- s = wb.getSheet("TwoVariable Table Example");
- r = s.getRow(3);
- c = r.getCell(4);
- assertEquals(CellType.FORMULA, c.getCellType());
-
- // TODO - check the formula once tables and
- // arrays are properly supported
- }
- }
-
- /**
- * 45322: HSSFSheet.autoSizeColumn fails when style.getDataFormat() returns -1
- */
- @Test
- void bug45322() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("44958.xls")) {
- HSSFSheet sh = wb.getSheetAt(0);
- for (short i = 0; i < 30; i++) {
- sh.autoSizeColumn(i);
- assertNotEquals(0, sh.getColumnWidth(i));
- }
- }
- }
-
- /**
- * We used to add too many UncalcRecords to sheets
- * with diagrams on. Don't any more
- */
- @Test
- void bug45414() throws Exception {
- try (HSSFWorkbook wb1 = openSampleWorkbook("WithThreeCharts.xls")) {
- wb1.getSheetAt(0).setForceFormulaRecalculation(true);
- wb1.getSheetAt(1).setForceFormulaRecalculation(false);
- wb1.getSheetAt(2).setForceFormulaRecalculation(true);
-
- // Write out and back in again
- // This used to break
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
-
- // Check now set as it should be
- assertTrue(wb2.getSheetAt(0).getForceFormulaRecalculation());
- assertFalse(wb2.getSheetAt(1).getForceFormulaRecalculation());
- assertTrue(wb2.getSheetAt(2).getForceFormulaRecalculation());
- }
- }
- }
-
- /**
- * Very hidden sheets not displaying as such
- */
- @Test
- void bug45761() throws Exception {
- try (HSSFWorkbook wb1 = openSampleWorkbook("45761.xls")) {
- assertEquals(3, wb1.getNumberOfSheets());
-
- assertFalse(wb1.isSheetHidden(0));
- assertFalse(wb1.isSheetVeryHidden(0));
- assertTrue(wb1.isSheetHidden(1));
- assertFalse(wb1.isSheetVeryHidden(1));
- assertFalse(wb1.isSheetHidden(2));
- assertTrue(wb1.isSheetVeryHidden(2));
-
- // Change sheet 0 to be very hidden, and re-load
- wb1.setSheetVisibility(0, SheetVisibility.VERY_HIDDEN);
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- assertFalse(wb2.isSheetHidden(0));
- assertTrue(wb2.isSheetVeryHidden(0));
- assertTrue(wb2.isSheetHidden(1));
- assertFalse(wb2.isSheetVeryHidden(1));
- assertFalse(wb2.isSheetHidden(2));
- assertTrue(wb2.isSheetVeryHidden(2));
- }
- }
- }
-
- /**
- * The resolution for bug 45777 assumed that the maximum text length in a header / footer
- * record was 256 bytes. This assumption appears to be wrong. Since the fix for bug 47244,
- * POI now supports header / footer text lengths beyond 256 bytes.
- */
- @Test
- void bug45777() throws Exception {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
-
- char[] cc248 = new char[248];
- Arrays.fill(cc248, 'x');
- String s248 = new String(cc248);
-
- String s249 = s248 + "1";
- String s250 = s248 + "12";
- String s251 = s248 + "123";
- assertEquals(248, s248.length());
- assertEquals(249, s249.length());
- assertEquals(250, s250.length());
- assertEquals(251, s251.length());
-
-
- // Try on headers
- s.getHeader().setCenter(s248);
- assertEquals(254, s.getHeader().getRawText().length());
- writeOutAndReadBack(wb).close();
-
- s.getHeader().setCenter(s251);
- assertEquals(257, s.getHeader().getRawText().length());
- writeOutAndReadBack(wb).close();
-
- // header can be more than 256 bytes
- s.getHeader().setCenter(s250); // 256 bytes required
- s.getHeader().setCenter(s251); // 257 bytes required
-
- // Now try on footers
- s.getFooter().setCenter(s248);
- assertEquals(254, s.getFooter().getRawText().length());
- writeOutAndReadBack(wb).close();
-
- s.getFooter().setCenter(s251);
- assertEquals(257, s.getFooter().getRawText().length());
- writeOutAndReadBack(wb).close();
-
- // footer can be more than 256 bytes
- s.getFooter().setCenter(s250); // 256 bytes required
- s.getFooter().setCenter(s251); // 257 bytes required
-
- }
- }
-
- /**
- * Charts with long titles
- */
- @Test
- void bug45784() throws Exception {
- simpleTest("45784.xls", wb -> assertEquals(1, wb.getNumberOfSheets()));
- }
-
- /**
- * Cell background colours
- */
- @Test
- void bug45492() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("45492.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
- HSSFRow r = s.getRow(0);
- HSSFPalette p = wb.getCustomPalette();
-
- HSSFCell auto = r.getCell(0);
- HSSFCell grey = r.getCell(1);
- HSSFCell red = r.getCell(2);
- HSSFCell blue = r.getCell(3);
- HSSFCell green = r.getCell(4);
-
- assertEquals(64, auto.getCellStyle().getFillForegroundColor());
- assertEquals(64, auto.getCellStyle().getFillBackgroundColor());
- assertEquals("0:0:0", p.getColor(64).getHexString());
-
- assertEquals(22, grey.getCellStyle().getFillForegroundColor());
- assertEquals(64, grey.getCellStyle().getFillBackgroundColor());
- assertEquals("C0C0:C0C0:C0C0", p.getColor(22).getHexString());
-
- assertEquals(10, red.getCellStyle().getFillForegroundColor());
- assertEquals(64, red.getCellStyle().getFillBackgroundColor());
- assertEquals("FFFF:0:0", p.getColor(10).getHexString());
-
- assertEquals(12, blue.getCellStyle().getFillForegroundColor());
- assertEquals(64, blue.getCellStyle().getFillBackgroundColor());
- assertEquals("0:0:FFFF", p.getColor(12).getHexString());
-
- assertEquals(11, green.getCellStyle().getFillForegroundColor());
- assertEquals(64, green.getCellStyle().getFillBackgroundColor());
- assertEquals("0:FFFF:0", p.getColor(11).getHexString());
- }
- }
-
- /**
- * ContinueRecord after EOF
- */
- @Test
- void bug46137() throws Exception {
- simpleTest("46137.xls", wb -> assertEquals(7, wb.getNumberOfSheets()));
- }
-
- /**
- * Odd POIFS blocks issue:
- * block[ 44 ] already removed from org.apache.poi.poifs.storage.BlockListImpl.remove
- */
- @Test
- void bug45290() throws Exception {
- simpleTest("45290.xls", wb -> assertEquals(1, wb.getNumberOfSheets()));
- }
-
- /**
- * In POI-2.5 user reported exception when parsing a name with a custom VBA function:
- * =MY_VBA_FUNCTION("lskdjflsk")
- */
- @Test
- void bug30070() throws Exception {
- //contains custom VBA function 'Commission'
- try (HSSFWorkbook wb = openSampleWorkbook("30070.xls")) {
- HSSFSheet sh = wb.getSheetAt(0);
- HSSFCell cell = sh.getRow(0).getCell(1);
-
- //B1 uses VBA in the formula
- assertEquals("Commission(A1)", cell.getCellFormula());
-
- //name sales_1 refers to Commission(Sheet0!$A$1)
- int idx = wb.getNameIndex("sales_1");
- assertTrue(idx != -1);
-
- HSSFName name = wb.getNameAt(idx);
- assertEquals("Commission(Sheet0!$A$1)", name.getRefersToFormula());
- }
- }
-
- /**
- * The link formulas which is referring to other books cannot be taken (the bug existed prior to POI-3.2)
- * Expected:
- *
- * [link_sub.xls]Sheet1!$A$1
- * [link_sub.xls]Sheet1!$A$2
- * [link_sub.xls]Sheet1!$A$3
- *
- * POI-3.1 output:
- *
- * Sheet1!$A$1
- * Sheet1!$A$2
- * Sheet1!$A$3
- */
- @Test
- void bug27364() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("27364.xls")) {
- HSSFSheet sheet = wb.getSheetAt(0);
-
- assertEquals("[link_sub.xls]Sheet1!$A$1", sheet.getRow(0).getCell(0).getCellFormula());
- assertEquals("[link_sub.xls]Sheet1!$A$2", sheet.getRow(1).getCell(0).getCellFormula());
- assertEquals("[link_sub.xls]Sheet1!$A$3", sheet.getRow(2).getCell(0).getCellFormula());
- }
- }
-
- /**
- * Similar to bug#27364:
- * HSSFCell.getCellFormula() fails with references to external workbooks
- */
- @Test
- void bug31661() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("31661.xls")) {
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFCell cell = sheet.getRow(11).getCell(10); //K11
- assertEquals("+'[GM Budget.xls]8085.4450'!$B$2", cell.getCellFormula());
- }
- }
-
- /**
- * Incorrect handling of non-ISO 8859-1 characters in Windows ANSII Code Page 1252
- */
- @Test
- void bug27394() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("27394.xls")) {
- assertEquals("\u0161\u017E", wb.getSheetName(0));
- assertEquals("\u0161\u017E\u010D\u0148\u0159", wb.getSheetName(1));
- HSSFSheet sheet = wb.getSheetAt(0);
-
- assertEquals("\u0161\u017E", sheet.getRow(0).getCell(0).getStringCellValue());
- assertEquals("\u0161\u017E\u010D\u0148\u0159", sheet.getRow(1).getCell(0).getStringCellValue());
- }
- }
-
- /**
- * Multiple calls of HSSFWorkbook.write result in corrupted xls
- */
- @Test
- void bug32191() throws IOException {
- try (HSSFWorkbook wb = openSampleWorkbook("27394.xls");
- ByteArrayOutputStream out1 = new ByteArrayOutputStream();
- ByteArrayOutputStream out2 = new ByteArrayOutputStream();
- ByteArrayOutputStream out3 = new ByteArrayOutputStream()) {
- wb.write(out1);
- wb.write(out2);
- wb.write(out3);
- assertArrayEquals(out1.toByteArray(), out2.toByteArray());
- assertArrayEquals(out2.toByteArray(), out3.toByteArray());
- }
- }
-
- /**
- * java.lang.NegativeArraySizeException reading long
- * non-unicode data for a name record
- */
- @Test
- void bug47034() throws Exception {
- simpleTest("47034.xls", wb -> {
- assertEquals(893, wb.getNumberOfNames());
- assertEquals("Matthew\\Matthew11_1\\Matthew2331_1\\Matthew2351_1\\Matthew2361_1___lab", wb.getNameName(300));
- });
- }
-
- /**
- * HSSFRichTextString.length() returns negative for really long strings.
- * The test file was created in OpenOffice 3.0 as Excel does not allow cell text longer than 32,767 characters
- */
- @Test
- void bug46368() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("46368.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
- HSSFCell cell1 = s.getRow(0).getCell(0);
- assertEquals(32770, cell1.getStringCellValue().length());
-
- HSSFCell cell2 = s.getRow(2).getCell(0);
- assertEquals(32766, cell2.getStringCellValue().length());
- }
- }
-
- /**
- * Short records on certain sheets with charts in them
- */
- @Test
- void bug48180() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("48180.xls")) {
-
- HSSFSheet s = wb.getSheetAt(0);
- HSSFCell cell1 = s.getRow(0).getCell(0);
- assertEquals("test ", cell1.getStringCellValue());
-
- HSSFCell cell2 = s.getRow(0).getCell(1);
- assertEquals(1.0, cell2.getNumericCellValue(), 0.0);
- }
- }
-
- /**
- * Round trip a file with an unusual UnicodeString/ExtRst record parts
- */
- @Test
- void bug47847() throws Exception {
- try (HSSFWorkbook wb1 = openSampleWorkbook("47847.xls")) {
- assertEquals(3, wb1.getNumberOfSheets());
-
- // Find the SST record
- UnicodeString withExt = wb1.getWorkbook().getSSTString(0);
- UnicodeString withoutExt = wb1.getWorkbook().getSSTString(31);
-
- assertEquals("O:Alloc:Qty", withExt.getString());
- assertEquals(0x0004, (withExt.getOptionFlags() & 0x0004));
-
- assertEquals("RT", withoutExt.getString());
- assertEquals(0x0000, (withoutExt.getOptionFlags() & 0x0004));
-
- // Something about continues...
-
-
- // Write out and re-read
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- assertEquals(3, wb2.getNumberOfSheets());
-
- // Check it's the same now
- withExt = wb2.getWorkbook().getSSTString(0);
- withoutExt = wb2.getWorkbook().getSSTString(31);
-
- assertEquals("O:Alloc:Qty", withExt.getString());
- assertEquals(0x0004, (withExt.getOptionFlags() & 0x0004));
-
- assertEquals("RT", withoutExt.getString());
- assertEquals(0x0000, (withoutExt.getOptionFlags() & 0x0004));
- }
- }
- }
-
- /**
- * Problem with cloning a sheet with a chart
- * contained in it.
- */
- @Test
- void bug49096() throws Exception {
- try (HSSFWorkbook wb1 = openSampleWorkbook("49096.xls")) {
- assertEquals(1, wb1.getNumberOfSheets());
-
- assertNotNull(wb1.getSheetAt(0));
- wb1.cloneSheet(0);
- assertEquals(2, wb1.getNumberOfSheets());
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- assertEquals(2, wb2.getNumberOfSheets());
- }
- }
- }
-
- /**
- * Newly created sheets need to get a
- * proper TabID, otherwise print setup
- * gets confused on them.
- * Also ensure that print setup refs are
- * by reference not value
- */
- @Test
- void bug46664() throws Exception {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet sheet = wb1.createSheet("new_sheet");
- HSSFRow row = sheet.createRow((short) 0);
- row.createCell(0).setCellValue(new HSSFRichTextString("Column A"));
- row.createCell(1).setCellValue(new HSSFRichTextString("Column B"));
- row.createCell(2).setCellValue(new HSSFRichTextString("Column C"));
- row.createCell(3).setCellValue(new HSSFRichTextString("Column D"));
- row.createCell(4).setCellValue(new HSSFRichTextString("Column E"));
- row.createCell(5).setCellValue(new HSSFRichTextString("Column F"));
-
- //set print area from column a to column c (on first row)
- wb1.setPrintArea(
- 0, //sheet index
- 0, //start column
- 2, //end column
- 0, //start row
- 0 //end row
- );
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- // Ensure the tab index
- TabIdRecord tr = null;
- for (org.apache.poi.hssf.record.Record r : wb2.getWorkbook().getRecords()) {
- if (r instanceof TabIdRecord) {
- tr = (TabIdRecord) r;
- }
- }
- assertNotNull(tr);
- assertEquals(1, tr.getTabIdSize());
- assertEquals(0, tr.getTabIdAt(0));
-
- // Ensure the print setup
- assertEquals("new_sheet!$A$1:$C$1", wb2.getPrintArea(0));
- HSSFName printArea = wb2.getName("Print_Area");
- assertNotNull(printArea);
- assertEquals("new_sheet!$A$1:$C$1", printArea.getRefersToFormula());
-
- // Needs reference not value
- NameRecord nr = wb2.getWorkbook().getNameRecord(
- wb2.getNameIndex("Print_Area")
- );
- assertEquals("Print_Area", nr.getNameText());
- assertEquals(1, nr.getNameDefinition().length);
- assertEquals(
- "new_sheet!$A$1:$C$1",
- ((Area3DPtg) nr.getNameDefinition()[0]).toFormulaString(HSSFEvaluationWorkbook.create(wb2))
- );
- assertEquals('R', nr.getNameDefinition()[0].getRVAType());
- }
- }
- }
-
- /**
- * Problems with formula references to
- * sheets via URLs
- */
- @Test
- void bug45970() throws Exception {
- try (HSSFWorkbook wb1 = openSampleWorkbook("FormulaRefs.xls")) {
- assertEquals(3, wb1.getNumberOfSheets());
-
- HSSFSheet s = wb1.getSheetAt(0);
- HSSFRow row;
-
- row = s.getRow(0);
- assertEquals(CellType.NUMERIC, row.getCell(1).getCellType());
- assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0);
-
- row = s.getRow(1);
- assertEquals(CellType.FORMULA, row.getCell(1).getCellType());
- assertEquals("B1", row.getCell(1).getCellFormula());
- assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0);
-
- row = s.getRow(2);
- assertEquals(CellType.FORMULA, row.getCell(1).getCellType());
- assertEquals("Sheet1!B1", row.getCell(1).getCellFormula());
- assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0);
-
- row = s.getRow(3);
- assertEquals(CellType.FORMULA, row.getCell(1).getCellType());
- assertEquals("[Formulas2.xls]Sheet1!B2", row.getCell(1).getCellFormula());
- assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0);
-
- row = s.getRow(4);
- assertEquals(CellType.FORMULA, row.getCell(1).getCellType());
- assertEquals("'[$http://gagravarr.org/FormulaRefs.xls]Sheet1'!B1", row.getCell(1).getCellFormula());
- assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0);
-
- // Link our new workbook
- Workbook externalWb1 = new HSSFWorkbook();
- externalWb1.createSheet("Sheet1");
- assertEquals(4, wb1.linkExternalWorkbook("$http://gagravarr.org/FormulaRefs2.xls", externalWb1));
-
- // Change 4
- row.getCell(1).setCellFormula("'[$http://gagravarr.org/FormulaRefs2.xls]Sheet1'!B2");
- row.getCell(1).setCellValue(123.0);
-
- // Link our new workbook
- Workbook externalWb2 = new HSSFWorkbook();
- externalWb2.createSheet("Sheet1");
- assertEquals(5, wb1.linkExternalWorkbook("$http://example.com/FormulaRefs.xls", externalWb2));
-
- // Add 5
- row = s.createRow(5);
- row.createCell(1, CellType.FORMULA);
- row.getCell(1).setCellFormula("'[$http://example.com/FormulaRefs.xls]Sheet1'!B1");
- row.getCell(1).setCellValue(234.0);
-
- // Re-test
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- s = wb2.getSheetAt(0);
-
- row = s.getRow(0);
- assertEquals(CellType.NUMERIC, row.getCell(1).getCellType());
- assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0);
-
- row = s.getRow(1);
- assertEquals(CellType.FORMULA, row.getCell(1).getCellType());
- assertEquals("B1", row.getCell(1).getCellFormula());
- assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0);
-
- row = s.getRow(2);
- assertEquals(CellType.FORMULA, row.getCell(1).getCellType());
- assertEquals("Sheet1!B1", row.getCell(1).getCellFormula());
- assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0);
-
- row = s.getRow(3);
- assertEquals(CellType.FORMULA, row.getCell(1).getCellType());
- assertEquals("[Formulas2.xls]Sheet1!B2", row.getCell(1).getCellFormula());
- assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0);
-
- row = s.getRow(4);
- assertEquals(CellType.FORMULA, row.getCell(1).getCellType());
- assertEquals("'[$http://gagravarr.org/FormulaRefs2.xls]Sheet1'!B2", row.getCell(1).getCellFormula());
- assertEquals(123.0, row.getCell(1).getNumericCellValue(), 0);
-
- row = s.getRow(5);
- assertEquals(CellType.FORMULA, row.getCell(1).getCellType());
- assertEquals("'[$http://example.com/FormulaRefs.xls]Sheet1'!B1", row.getCell(1).getCellFormula());
- assertEquals(234.0, row.getCell(1).getNumericCellValue(), 0);
-
- }
- }
- }
-
- /**
- * Test for a file with NameRecord with NameCommentRecord comments
- */
- @Test
- void bug49185() throws Exception {
- try (HSSFWorkbook wb1 = openSampleWorkbook("49185.xls")) {
- Name name = wb1.getName("foobarName");
- assertNotNull(name);
- assertEquals("This is a comment", name.getComment());
-
- // Rename the name, comment comes with it
- name.setNameName("ChangedName");
- assertEquals("This is a comment", name.getComment());
-
- // Save and re-check
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- name = wb2.getName("ChangedName");
- assertNotNull(name);
- assertEquals("This is a comment", name.getComment());
-
- // Now try to change it
- name.setComment("Changed Comment");
- assertEquals("Changed Comment", name.getComment());
-
- // Save and re-check
- try (HSSFWorkbook wb3 = writeOutAndReadBack(wb2)) {
- name = wb3.getName("ChangedName");
- assertNotNull(name);
- assertEquals("Changed Comment", name.getComment());
- }
- }
- }
- }
-
- /** Vertically aligned text */
- @Test
- void bug49524() throws Exception {
- try (HSSFWorkbook wb1 = openSampleWorkbook("49524.xls")) {
- Sheet s = wb1.getSheetAt(0);
- Row r = s.getRow(0);
- Cell rotated = r.getCell(0);
- Cell normal = r.getCell(1);
-
- // Check the current ones
- assertEquals(0, normal.getCellStyle().getRotation());
- assertEquals(0xff, rotated.getCellStyle().getRotation());
-
- // Add a new style, also rotated
- CellStyle cs = wb1.createCellStyle();
- cs.setRotation((short) 0xff);
- Cell nc = r.createCell(2);
- nc.setCellValue("New Rotated Text");
- nc.setCellStyle(cs);
- assertEquals(0xff, nc.getCellStyle().getRotation());
-
- // Write out and read back
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- // Re-check
- s = wb2.getSheetAt(0);
- r = s.getRow(0);
- rotated = r.getCell(0);
- normal = r.getCell(1);
- nc = r.getCell(2);
-
- assertEquals(0, normal.getCellStyle().getRotation());
- assertEquals(0xff, rotated.getCellStyle().getRotation());
- assertEquals(0xff, nc.getCellStyle().getRotation());
- }
- }
- }
-
- /**
- * Setting the user style name on custom styles
- */
- @Test
- void bug49689() throws Exception {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet("Test");
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(0);
-
- HSSFCellStyle cs1 = wb1.createCellStyle();
- HSSFCellStyle cs2 = wb1.createCellStyle();
- HSSFCellStyle cs3 = wb1.createCellStyle();
-
- assertEquals(21, cs1.getIndex());
- cs1.setUserStyleName("Testing");
-
- assertEquals(22, cs2.getIndex());
- cs2.setUserStyleName("Testing 2");
-
- assertEquals(23, cs3.getIndex());
- cs3.setUserStyleName("Testing 3");
-
- // Set one
- c.setCellStyle(cs1);
-
- // Write out and read back
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- // Re-check
- assertEquals("Testing", wb2.getCellStyleAt((short) 21).getUserStyleName());
- assertEquals("Testing 2", wb2.getCellStyleAt((short) 22).getUserStyleName());
- assertEquals("Testing 3", wb2.getCellStyleAt((short) 23).getUserStyleName());
- }
- }
- }
-
- @Test
- void bug49751() throws Exception {
- Set exp = new HashSet<>(Arrays.asList(
- "20% - Accent1", "20% - Accent2", "20% - Accent3", "20% - Accent4", "20% - Accent5",
- "20% - Accent6", "40% - Accent1", "40% - Accent2", "40% - Accent3", "40% - Accent4",
- "40% - Accent5", "40% - Accent6", "60% - Accent1", "60% - Accent2", "60% - Accent3",
- "60% - Accent4", "60% - Accent5", "60% - Accent6", "Accent1", "Accent2", "Accent3",
- "Accent4", "Accent5", "Accent6", "Bad", "Calculation", "Check Cell", "Explanatory Text",
- "Good", "Heading 1", "Heading 2", "Heading 3", "Heading 4", "Input", "Linked Cell",
- "Neutral", "Note", "Output", "Title", "Total", "Warning Text"));
-
- try (HSSFWorkbook wb = openSampleWorkbook("49751.xls")) {
- Set act = IntStream
- .range(0, wb.getNumCellStyles())
- .mapToObj(wb::getCellStyleAt)
- .map(HSSFCellStyle::getUserStyleName)
- .filter(Objects::nonNull)
- .collect(Collectors.toSet());
- assertEquals(exp, act);
- }
- }
-
- /**
- * Regression with the PageSettingsBlock
- */
- @Test
- void bug49931() throws Exception {
- simpleTest("49931.xls", wb -> {
- assertEquals(1, wb.getNumberOfSheets());
- assertEquals("Foo", wb.getSheetAt(0).getRow(0).getCell(0).getRichStringCellValue().toString());
- });
- }
-
- /**
- * Missing left/right/centre options on a footer
- */
- @Test
- void bug48325() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("48325.xls")) {
- HSSFSheet sh = wb.getSheetAt(0);
- HSSFFooter f = sh.getFooter();
-
- // Will show as the center, as that is what excel does
- // with an invalid footer lacking left/right/center details
- assertEquals("", f.getLeft(), "Left text should be empty");
- assertEquals("", f.getRight(), "Right text should be empty");
- assertEquals("BlahBlah blah blah ", f.getCenter(),
- "Center text should contain the illegal value");
- }
- }
-
- /**
- * Last row number when shifting rows
- */
- @Test
- void bug50416LastRowNumber() throws IOException {
- // Create the workbook with 1 sheet which contains 3 rows
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- Sheet sheet = wb.createSheet("Bug50416");
- Row row1 = sheet.createRow(0);
- Cell cellA_1 = row1.createCell(0, CellType.STRING);
- cellA_1.setCellValue("Cell A,1");
- Row row2 = sheet.createRow(1);
- Cell cellA_2 = row2.createCell(0, CellType.STRING);
- cellA_2.setCellValue("Cell A,2");
- Row row3 = sheet.createRow(2);
- Cell cellA_3 = row3.createCell(0, CellType.STRING);
- cellA_3.setCellValue("Cell A,3");
-
- // Test the last Row number it currently correct
- assertEquals(2, sheet.getLastRowNum());
-
- // Shift the first row to the end
- sheet.shiftRows(0, 0, 3);
- assertEquals(3, sheet.getLastRowNum());
- assertEquals(-1, sheet.getRow(0).getLastCellNum());
- assertEquals("Cell A,2", sheet.getRow(1).getCell(0).getStringCellValue());
- assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue());
- assertEquals("Cell A,1", sheet.getRow(3).getCell(0).getStringCellValue());
-
- // Shift the 2nd row up to the first one
- sheet.shiftRows(1, 1, -1);
- assertEquals(3, sheet.getLastRowNum());
- assertEquals("Cell A,2", sheet.getRow(0).getCell(0).getStringCellValue());
- assertEquals(-1, sheet.getRow(1).getLastCellNum());
- assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue());
- assertEquals("Cell A,1", sheet.getRow(3).getCell(0).getStringCellValue());
-
- // Shift the 4th row up into the gap in the 3rd row
- sheet.shiftRows(3, 3, -2);
- assertEquals(2, sheet.getLastRowNum());
- assertEquals("Cell A,2", sheet.getRow(0).getCell(0).getStringCellValue());
- assertEquals("Cell A,1", sheet.getRow(1).getCell(0).getStringCellValue());
- assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue());
- assertEquals(-1, sheet.getRow(3).getLastCellNum());
-
- // Now zap the empty 4th row - won't do anything
- sheet.removeRow(sheet.getRow(3));
-
- // Test again the last row number which should be 2
- assertEquals(2, sheet.getLastRowNum());
- assertEquals("Cell A,2", sheet.getRow(0).getCell(0).getStringCellValue());
- assertEquals("Cell A,1", sheet.getRow(1).getCell(0).getStringCellValue());
- assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue());
-
- }
- }
-
- /**
- * If you send a file between Excel and OpenOffice enough, something
- * will turn the "General" format into "GENERAL"
- */
- @Test
- void bug50756() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("50756.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
- HSSFRow r17 = s.getRow(16);
- HSSFRow r18 = s.getRow(17);
- HSSFDataFormatter df = new HSSFDataFormatter();
-
- assertEquals(10.0, r17.getCell(1).getNumericCellValue(), 0);
- assertEquals(20.0, r17.getCell(2).getNumericCellValue(), 0);
- assertEquals(20.0, r17.getCell(3).getNumericCellValue(), 0);
- assertEquals("GENERAL", r17.getCell(1).getCellStyle().getDataFormatString());
- assertEquals("GENERAL", r17.getCell(2).getCellStyle().getDataFormatString());
- assertEquals("GENERAL", r17.getCell(3).getCellStyle().getDataFormatString());
- assertEquals("10", df.formatCellValue(r17.getCell(1)));
- assertEquals("20", df.formatCellValue(r17.getCell(2)));
- assertEquals("20", df.formatCellValue(r17.getCell(3)));
-
- assertEquals(16.0, r18.getCell(1).getNumericCellValue(), 0);
- assertEquals(35.0, r18.getCell(2).getNumericCellValue(), 0);
- assertEquals(123.0, r18.getCell(3).getNumericCellValue(), 0);
- assertEquals("GENERAL", r18.getCell(1).getCellStyle().getDataFormatString());
- assertEquals("GENERAL", r18.getCell(2).getCellStyle().getDataFormatString());
- assertEquals("GENERAL", r18.getCell(3).getCellStyle().getDataFormatString());
- assertEquals("16", df.formatCellValue(r18.getCell(1)));
- assertEquals("35", df.formatCellValue(r18.getCell(2)));
- assertEquals("123", df.formatCellValue(r18.getCell(3)));
- }
- }
-
- /**
- * A protected sheet with comments, when written out by
- * POI, ends up upsetting excel.
- * TODO Identify the cause and add extra asserts for
- * the bit excel cares about
- */
- @Test
- void bug50833() throws Exception {
- HSSFWorkbook wb1 = openSampleWorkbook("50833.xls");
- HSSFSheet s = wb1.getSheetAt(0);
- assertEquals("Sheet1", s.getSheetName());
- assertFalse(s.getProtect());
-
- HSSFCell c = s.getRow(0).getCell(0);
- assertEquals("test cell value", c.getRichStringCellValue().getString());
-
- HSSFComment cmt = c.getCellComment();
- assertNotNull(cmt);
- assertEquals("Robert Lawrence", cmt.getAuthor());
- assertEquals("Robert Lawrence:\ntest comment", cmt.getString().getString());
-
- // Reload
- HSSFWorkbook wb2 = writeOutAndReadBack(wb1);
- wb1.close();
- s = wb2.getSheetAt(0);
- c = s.getRow(0).getCell(0);
-
- // Re-check the comment
- cmt = c.getCellComment();
- assertNotNull(cmt);
- assertEquals("Robert Lawrence", cmt.getAuthor());
- assertEquals("Robert Lawrence:\ntest comment", cmt.getString().getString());
-
- // TODO Identify what excel doesn't like, and check for that
- wb2.close();
- }
-
- /**
- * The spec says that ChartEndObjectRecord has 6 reserved
- * bytes on the end, but we sometimes find files without...
- */
- @Test
- void bug50939() throws Exception {
- simpleTest("50939.xls", wb -> assertEquals(2, wb.getNumberOfSheets()));
- }
-
- @Test
- void bug49219() throws Exception {
- simpleTest("49219.xls", wb -> {
- assertEquals(1, wb.getNumberOfSheets());
- assertEquals("DGATE", wb.getSheetAt(0).getRow(1).getCell(0).getStringCellValue());
- });
- }
-
- @Test
- void bug48968() throws Exception {
- TimeZone userTimeZone = LocaleUtil.getUserTimeZone();
- LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET"));
- try {
- HSSFWorkbook wb = openSampleWorkbook("48968.xls");
- assertEquals(1, wb.getNumberOfSheets());
-
- DataFormatter fmt = new DataFormatter();
-
- // Check the dates
- HSSFSheet s = wb.getSheetAt(0);
- Cell cell_d20110325 = s.getRow(0).getCell(0);
- Cell cell_d19000102 = s.getRow(11).getCell(0);
- Cell cell_d19000100 = s.getRow(21).getCell(0);
- assertEquals(s.getRow(0).getCell(3).getStringCellValue(), fmt.formatCellValue(cell_d20110325));
- assertEquals(s.getRow(11).getCell(3).getStringCellValue(), fmt.formatCellValue(cell_d19000102));
- // There is no such thing as 00/01/1900...
- assertEquals("00/01/1900 06:14:24", s.getRow(21).getCell(3).getStringCellValue());
- assertEquals("31/12/1899 06:14:24", fmt.formatCellValue(cell_d19000100));
-
- // Check the cached values
- assertEquals("HOUR(A1)", s.getRow(5).getCell(0).getCellFormula());
- assertEquals(11.0, s.getRow(5).getCell(0).getNumericCellValue(), 0);
- assertEquals("MINUTE(A1)", s.getRow(6).getCell(0).getCellFormula());
- assertEquals(39.0, s.getRow(6).getCell(0).getNumericCellValue(), 0);
- assertEquals("SECOND(A1)", s.getRow(7).getCell(0).getCellFormula());
- assertEquals(54.0, s.getRow(7).getCell(0).getNumericCellValue(), 0);
-
- // Re-evaluate and check
- HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
- assertEquals("HOUR(A1)", s.getRow(5).getCell(0).getCellFormula());
- assertEquals(11.0, s.getRow(5).getCell(0).getNumericCellValue(), 0);
- assertEquals("MINUTE(A1)", s.getRow(6).getCell(0).getCellFormula());
- assertEquals(39.0, s.getRow(6).getCell(0).getNumericCellValue(), 0);
- assertEquals("SECOND(A1)", s.getRow(7).getCell(0).getCellFormula());
- assertEquals(54.0, s.getRow(7).getCell(0).getNumericCellValue(), 0);
-
- // Push the time forward a bit and check
- double date = s.getRow(0).getCell(0).getNumericCellValue();
- s.getRow(0).getCell(0).setCellValue(date + 1.26);
-
- HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
- assertEquals("HOUR(A1)", s.getRow(5).getCell(0).getCellFormula());
- assertEquals(11.0 + 6.0, s.getRow(5).getCell(0).getNumericCellValue(), 0);
- assertEquals("MINUTE(A1)", s.getRow(6).getCell(0).getCellFormula());
- assertEquals(39.0 + 14.0 + 1, s.getRow(6).getCell(0).getNumericCellValue(), 0);
- assertEquals("SECOND(A1)", s.getRow(7).getCell(0).getCellFormula());
- assertEquals(54.0 + 24.0 - 60, s.getRow(7).getCell(0).getNumericCellValue(), 0);
-
- wb.close();
- } finally {
- LocaleUtil.setUserTimeZone(userTimeZone);
- }
- }
-
-
- /**
- * Mixture of Ascii and Unicode strings in a
- * NameComment record
- */
- @Test
- void bug51143() throws Exception {
- simpleTest("51143.xls", wb -> assertEquals(1, wb.getNumberOfSheets()));
- }
-
- /**
- * File with exactly 256 data blocks (+header block)
- * shouldn't break on POIFS loading
- */
- @Test
- void bug51461() throws Exception {
- byte[] data = HSSFITestDataProvider.instance.getTestDataFileContent("51461.xls");
-
- HSSFWorkbook wbPOIFS = new HSSFWorkbook(new POIFSFileSystem(
- new ByteArrayInputStream(data)).getRoot(), false);
- HSSFWorkbook wbPOIFS2 = new HSSFWorkbook(new POIFSFileSystem(
- new ByteArrayInputStream(data)).getRoot(), false);
-
- assertEquals(2, wbPOIFS.getNumberOfSheets());
- assertEquals(2, wbPOIFS2.getNumberOfSheets());
- }
-
- @Test
- void bug51535() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("51535.xls")) {
- assertEquals(3, wb.getNumberOfSheets());
-
- // Check directly
- HSSFSheet s = wb.getSheetAt(0);
- assertEquals("Top Left Cell", s.getRow(0).getCell(0).getStringCellValue());
- assertEquals("Top Right Cell", s.getRow(0).getCell(255).getStringCellValue());
- assertEquals("Bottom Left Cell", s.getRow(65535).getCell(0).getStringCellValue());
- assertEquals("Bottom Right Cell", s.getRow(65535).getCell(255).getStringCellValue());
-
- // Extract and check
- try (ExcelExtractor ex = new ExcelExtractor(wb)) {
- String text = ex.getText();
- assertContains(text, "Top Left Cell");
- assertContains(text, "Top Right Cell");
- assertContains(text, "Bottom Left Cell");
- assertContains(text, "Bottom Right Cell");
- }
- }
- }
-
- /**
- * Sum across multiple workbooks
- * eg =SUM($Sheet2.A1:$Sheet3.A1)
- */
- @Test
- void test48703() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("48703.xls")) {
- assertEquals(3, wb.getNumberOfSheets());
-
- // Check reading the formula
- Sheet sheet = wb.getSheetAt(0);
- Row r = sheet.getRow(0);
- Cell c = r.getCell(0);
-
- assertEquals("SUM(Sheet2:Sheet3!A1)", c.getCellFormula());
- assertEquals(4.0, c.getNumericCellValue(), 0);
-
- // Check the evaluated result
- HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb);
- eval.evaluateFormulaCell(c);
- assertEquals(4.0, c.getNumericCellValue(), 0);
- }
- }
-
- @Test
- void bug49896() throws Exception {
- String exp = "VLOOKUP(A2,'[C:Documents and Settings/Yegor/My Documents/csco.xls]Sheet1'!$A$2:$B$3,2,FALSE)"
- .replace("/", File.separator);
- simpleTest("49896.xls", wb -> assertEquals(exp, wb.getSheetAt(0).getRow(1).getCell(1).getCellFormula()));
- }
-
- @Test
- void bug49529() throws Exception {
- // user code reported in Bugzilla #49529
- simpleTest("49529.xls", wb -> {
- wb.getSheetAt(0).createDrawingPatriarch();
- // prior to the fix the line below failed with
- // java.lang.IllegalStateException: EOF - next record not available
- wb.cloneSheet(0);
- });
- }
-
- @Test
- void bug49612_part() throws IOException {
- try (HSSFWorkbook wb = openSampleWorkbook("49612.xls")) {
- HSSFSheet sh = wb.getSheetAt(0);
- HSSFRow row = sh.getRow(0);
- HSSFCell c1 = row.getCell(2);
- HSSFCell d1 = row.getCell(3);
- HSSFCell e1 = row.getCell(2);
-
- assertEquals("SUM(BOB+JIM)", c1.getCellFormula());
-
- // Problem 1: See TestUnfixedBugs#test49612()
- // Problem 2: TestUnfixedBugs#test49612()
-
- // Problem 3: These used to fail, now pass
- HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb);
- assertEquals(30.0, eval.evaluate(c1).getNumberValue(), 0.001, "evaluating c1");
- assertEquals(30.0, eval.evaluate(d1).getNumberValue(), 0.001, "evaluating d1");
- assertEquals(30.0, eval.evaluate(e1).getNumberValue(), 0.001, "evaluating e1");
- }
- }
-
- @Test
- void bug51675() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("51675.xls")) {
- HSSFSheet sh = wb.getSheetAt(0);
- InternalSheet ish = HSSFTestHelper.getSheetForTest(sh);
- PageSettingsBlock psb = (PageSettingsBlock) ish.getRecords().get(13);
- List list = new ArrayList<>();
- psb.visitContainedRecords(r -> list.add(r.getSid()));
- assertEquals(UnknownRecord.BITMAP_00E9, list.get(list.size() - 1).intValue());
- assertEquals(UnknownRecord.HEADER_FOOTER_089C, list.get(list.size() - 2).intValue());
- }
- }
-
- @Test
- void bug52272() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sh = wb.createSheet();
- HSSFPatriarch p = sh.createDrawingPatriarch();
-
- HSSFSimpleShape s = p.createSimpleShape(new HSSFClientAnchor());
- s.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
-
- HSSFSheet sh2 = wb.cloneSheet(0);
- assertNotNull(sh2.getDrawingPatriarch());
- }
- }
-
- @Test
- void bug53432() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- wb1.addPicture(new byte[]{123, 22}, Workbook.PICTURE_TYPE_JPEG);
- assertEquals(wb1.getAllPictures().size(), 1);
- }
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- assertEquals(wb2.getAllPictures().size(), 0);
- wb2.addPicture(new byte[]{123, 22}, Workbook.PICTURE_TYPE_JPEG);
- assertEquals(wb2.getAllPictures().size(), 1);
-
- try (HSSFWorkbook wb3 = writeOutAndReadBack(wb2)) {
- assertEquals(wb3.getAllPictures().size(), 1);
- }
- }
- }
- }
-
- @Test
- void bug46250() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("46250.xls")) {
- Sheet sh = wb.getSheet("Template");
- Sheet cSh = wb.cloneSheet(wb.getSheetIndex(sh));
- int sIdx = wb.getSheetIndex(cSh);
-
- HSSFPatriarch patriarch = (HSSFPatriarch) cSh.createDrawingPatriarch();
- HSSFTextbox tb = (HSSFTextbox) patriarch.getChildren().get(2);
-
- tb.setString(new HSSFRichTextString("POI test"));
- tb.setAnchor(new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 0, (short) 10, 10));
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) {
- HSSFSheet sh2 = wb2.getSheetAt(sIdx);
- assertNotNull(sh2);
- assertNotNull(sh2.getDrawingPatriarch());
- }
- }
- }
-
- @Test
- void bug53404() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("53404.xls")) {
- Sheet sheet = wb.getSheet("test-sheet");
- int rowCount = sheet.getLastRowNum() + 1;
- int newRows = 5;
- Calendar cal = LocaleUtil.getLocaleCalendar();
- for (int r = rowCount; r < rowCount + newRows; r++) {
- Row row = sheet.createRow((short) r);
- row.createCell(0).setCellValue(1.03 * (r + 7));
- row.createCell(1).setCellValue(cal.getTime());
- row.createCell(2).setCellValue(cal);
- row.createCell(3).setCellValue(String.format(Locale.ROOT, "row:%d/col:%d", r, 3));
- row.createCell(4).setCellValue(true);
- row.createCell(5).setCellErrorValue(FormulaError.NUM.getCode());
- row.createCell(6).setCellValue("added cells.");
- }
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) {
- Sheet sheet2 = wb2.getSheet("test-sheet");
- Row row2 = sheet2.getRow(5);
- assertNotNull(row2);
- assertEquals(cal.getTime(),row2.getCell(2).getDateCellValue());
- }
- }
- }
-
- /**
- * Row style information is 12 not 16 bits
- */
- @Test
- void bug49237() throws Exception {
- try (Workbook wb = openSampleWorkbook("49237.xls")) {
- Sheet sheet = wb.getSheetAt(0);
- Row row = sheet.getRow(0);
- CellStyle rstyle = row.getRowStyle();
- assertNotNull(rstyle);
- assertEquals(BorderStyle.DOUBLE, rstyle.getBorderBottom());
- }
- }
-
- /**
- * POI does now support the RC4 CryptoAPI encryption header structure
- */
- @ParameterizedTest
- @CsvSource({
- "xor-encryption-abc.xls, abc",
- "35897-type4.xls, freedom"
- })
- void bug35897(String file, String pass) throws Exception {
- Biff8EncryptionKey.setCurrentUserPassword(pass);
- try {
- simpleTest(file, null);
- } finally {
- Biff8EncryptionKey.setCurrentUserPassword(null);
- }
- }
-
- @Test
- void bug56450() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("56450.xls")) {
- HSSFSheet sheet = wb.getSheetAt(0);
- int comments = 0;
- for (Row r : sheet) {
- for (Cell c : r) {
- if (c.getCellComment() != null) {
- assertNotNull(c.getCellComment().getString().getString());
- comments++;
- }
- }
- }
- assertEquals(0, comments);
- }
- }
-
- /**
- * Files initially created with Excel 2010 can have >3 CF rules
- */
- @Test
- void bug56482() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("56482.xls")) {
- assertEquals(1, wb.getNumberOfSheets());
-
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFSheetConditionalFormatting cf = sheet.getSheetConditionalFormatting();
-
- assertEquals(5, cf.getNumConditionalFormattings());
- }
- }
-
- @Test
- void bug56325() throws IOException {
- try (HSSFWorkbook wb1 = openSampleWorkbook("56325.xls")) {
- assertEquals(3, wb1.getNumberOfSheets());
- wb1.removeSheetAt(0);
- assertEquals(2, wb1.getNumberOfSheets());
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- assertEquals(2, wb2.getNumberOfSheets());
- wb2.removeSheetAt(0);
- assertEquals(1, wb2.getNumberOfSheets());
- wb2.removeSheetAt(0);
- assertEquals(0, wb2.getNumberOfSheets());
-
- try (HSSFWorkbook wb3 = writeOutAndReadBack(wb2)) {
- assertEquals(0, wb3.getNumberOfSheets());
- }
- }
- }
- }
-
- @Test
- void bug56325a() throws IOException {
- try (HSSFWorkbook wb1 = openSampleWorkbook("56325a.xls")) {
-
- HSSFSheet sheet = wb1.cloneSheet(2);
- wb1.setSheetName(3, "Clone 1");
- sheet.setRepeatingRows(CellRangeAddress.valueOf("2:3"));
- wb1.setPrintArea(3, "$A$4:$C$10");
-
- sheet = wb1.cloneSheet(2);
- wb1.setSheetName(4, "Clone 2");
- sheet.setRepeatingRows(CellRangeAddress.valueOf("2:3"));
- wb1.setPrintArea(4, "$A$4:$C$10");
-
- wb1.removeSheetAt(2);
-
- try (Workbook wb2 = writeOutAndReadBack(wb1)) {
- assertEquals(4, wb2.getNumberOfSheets());
- }
- }
- }
-
- /**
- * Formulas which reference named ranges, either in other
- * sheets, or workbook scoped but in other workbooks.
- * Used to fail with
- * java.lang.RuntimeException: Unexpected eval class (org.apache.poi.ss.formula.eval.NameXEval)
- */
- @Test
- void bug56737() throws IOException {
- try (Workbook wb = openSampleWorkbook("56737.xls")) {
-
- // 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());
-
- // TODO Correct this, so that the filename is shown too, see bug #56742
- // This is what Excel itself shows
- //assertEquals("'56737.xls'!NR_Global_B2", cRefWName.getCellFormula());
- // TODO This isn't right, but it's what we currently generate....
- assertEquals("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();
- }
- }
-
- /**
- * ClassCastException in HSSFOptimiser - StyleRecord cannot be cast to
- * ExtendedFormatRecord when removing un-used styles
- */
- @Test
- void bug54443() throws Exception {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- HSSFCellStyle style = workbook.createCellStyle();
- HSSFCellStyle newStyle = workbook.createCellStyle();
-
- HSSFSheet mySheet = workbook.createSheet();
- HSSFRow row = mySheet.createRow(0);
- HSSFCell cell = row.createCell(0);
-
- // Use style
- cell.setCellStyle(style);
- // Switch to newStyle, style is now un-used
- cell.setCellStyle(newStyle);
-
- // Optimize
- int nbrOfCellStyles = workbook.getNumCellStyles();
- HSSFOptimiser.optimiseCellStyles(workbook);
- assertEquals(nbrOfCellStyles-1, workbook.getNumCellStyles());
- }
- }
-
- /**
- * Intersection formula ranges, eg =(C2:D3 D3:E4)
- */
- @Test
- void bug52111() throws Exception {
- try (Workbook wb = openSampleWorkbook("Intersection-52111.xls")) {
- 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!$A11:$IV11", "5.0");
- assertFormula(wb, s.getRow(8).getCell(0), "Tabelle2!E:F Tabelle2!$A11:$IV12", null);
- }
- }
-
- @Test
- void bug42016() throws Exception {
- try (Workbook wb = openSampleWorkbook("42016.xls")) {
- Sheet s = wb.getSheetAt(0);
- for (int row = 0; row < 7; row++) {
- assertEquals("A$1+B$1", s.getRow(row).getCell(2).getCellFormula());
- }
- }
- }
-
- /**
- * Unexpected record type (org.apache.poi.hssf.record.ColumnInfoRecord)
- */
- @Test
- void bug53984() throws Exception {
- try (Workbook wb = openSampleWorkbook("53984.xls")) {
- Sheet s = wb.getSheetAt(0);
- assertEquals("International Communication Services SA", s.getRow(2).getCell(0).getStringCellValue());
- assertEquals("Saudi Arabia-Riyadh", s.getRow(210).getCell(0).getStringCellValue());
- }
- }
-
- /**
- * Read, write, read for formulas point to cells in other files.
- * See {@link #bug46670()} for the main test, this just
- * covers reading an existing file and checking it.
- *
- * See base-test-class for some related tests that still fail
- */
- @Test
- void bug46670_existing() throws Exception {
- // Expected values
- String refLocal = "'[refs" + File.separator + "airport.xls]Sheet1'!$A$2";
- String refHttp = "'[9http://www.principlesofeconometrics.com/excel/airline.xls]Sheet1'!$A$2";
-
- // Check we can read them correctly
- simpleTest("46670_local.xls",
- wb -> assertEquals(refLocal, wb.getSheetAt(0).getRow(0).getCell(0).getCellFormula()));
-
- simpleTest("46670_http.xls",
- wb -> assertEquals(refHttp, wb.getSheetAt(0).getRow(0).getCell(0).getCellFormula()));
-
- // Now try to set them to the same values, and ensure that
- // they end up as they did before, even with a save and re-load
- try (HSSFWorkbook wb3 = openSampleWorkbook("46670_local.xls")) {
- Sheet s = wb3.getSheetAt(0);
- Cell c = s.getRow(0).getCell(0);
- c.setCellFormula(refLocal);
- assertEquals(refLocal, c.getCellFormula());
-
- try (HSSFWorkbook wb4 = writeOutAndReadBack(wb3)) {
- s = wb4.getSheetAt(0);
- assertEquals(refLocal, s.getRow(0).getCell(0).getCellFormula());
- }
- }
-
- try (HSSFWorkbook wb5 = openSampleWorkbook("46670_http.xls")) {
- Sheet s = wb5.getSheetAt(0);
- Cell c = s.getRow(0).getCell(0);
- c.setCellFormula(refHttp);
- assertEquals(refHttp, c.getCellFormula());
-
- try (Workbook wb6 = writeOutAndReadBack(wb5)) {
- s = wb6.getSheetAt(0);
- assertEquals(refHttp, s.getRow(0).getCell(0).getCellFormula());
- }
- }
- }
-
- @Test
- void test57163() throws IOException {
- simpleTest("57163.xls", wb -> {
- while (wb.getNumberOfSheets() > 1) {
- wb.removeSheetAt(1);
- }
- });
- }
-
- @Test
- void test48043() throws IOException {
- try (HSSFWorkbook wb = openSampleWorkbook("56325a.xls")) {
-
- wb.removeSheetAt(2);
- wb.removeSheetAt(1);
-
- //Sheet s = wb.createSheet("sheetname");
- Sheet s = wb.getSheetAt(0);
- Row row = s.createRow(0);
- Cell cell = row.createCell(0);
-
- cell.setCellFormula(
- "IF(AND(ISBLANK(A10)," +
- "ISBLANK(B10)),\"\"," +
- "CONCATENATE(A10,\"-\",B10))");
-
- FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator();
-
- eval.evaluateAll();
- try (Workbook wbBack = writeOutAndReadBack(wb)) {
- assertNotNull(wbBack);
- }
- }
- }
-
- @Test
- void test57925() throws IOException {
- try (Workbook wb = openSampleWorkbook("57925.xls")) {
- wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
- DataFormatter df = new DataFormatter();
- for (Sheet sheet : wb) {
- for (Row row : sheet) {
- for (Cell cell : row) {
- assertNotNull(df.formatCellValue(cell));
- }
- }
- }
- }
- }
-
- @Test
- void test46515() throws IOException {
- try (Workbook wb = openSampleWorkbook("46515.xls")) {
-
- // Get structure from webservice
- String urlString = "https://poi.apache.org/components/spreadsheet/images/calendar.jpg";
- URL structURL = new URL(urlString);
- BufferedImage bimage;
- try {
- bimage = ImageIO.read(structURL);
- } catch (IOException e) {
- Assumptions.assumeFalse(true, "Downloading a jpg from poi.apache.org should work");
- return;
- }
-
- // Convert BufferedImage to byte[]
- ByteArrayOutputStream imageBAOS = new ByteArrayOutputStream();
- ImageIO.write(bimage, "jpeg", imageBAOS);
- imageBAOS.flush();
- byte[] imageBytes = imageBAOS.toByteArray();
- imageBAOS.close();
-
- // Pop structure into Structure HSSFSheet
- int pict = wb.addPicture(imageBytes, HSSFWorkbook.PICTURE_TYPE_JPEG);
- Sheet sheet = wb.getSheet("Structure");
- assertNotNull(sheet, "Did not find sheet");
- HSSFPatriarch patriarch = (HSSFPatriarch) sheet.createDrawingPatriarch();
- HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 10, 22);
- anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE);
- patriarch.createPicture(anchor, pict);
- }
- }
-
- @Test
- void test55668() throws IOException {
- try (Workbook wb = openSampleWorkbook("55668.xls")) {
-
- Sheet sheet = wb.getSheetAt(0);
- Row row = sheet.getRow(0);
- Cell cell = row.getCell(0);
- assertEquals(CellType.FORMULA, cell.getCellType());
- assertEquals("IF(TRUE,\"\",\"\")", cell.getCellFormula());
- assertEquals("", cell.getStringCellValue());
- //noinspection deprecation
- cell.setCellType(CellType.STRING);
-
- assertEquals(CellType.BLANK, cell.getCellType());
- assertEquals("", cell.getStringCellValue());
-
- assertThrows(IllegalStateException.class, cell::getCellFormula);
- }
- }
-
- @Test
- void test55982() throws IOException {
- simpleTest("55982.xls", wb -> assertNotNull(wb.cloneSheet(1)));
- }
-
- /**
- * Test generator of ids for the CommonObjectDataSubRecord record.
- */
- @Test
- void test51332() {
- HSSFClientAnchor anchor = new HSSFClientAnchor();
- HSSFSimpleShape shape;
- CommonObjectDataSubRecord cmo;
-
- shape = new HSSFTextbox(null, anchor);
- shape.setShapeId(1025);
- cmo = (CommonObjectDataSubRecord) shape.getObjRecord().getSubRecords().get(0);
- assertEquals(1, cmo.getObjectId());
-
- shape = new HSSFPicture(null, anchor);
- shape.setShapeId(1026);
- cmo = (CommonObjectDataSubRecord) shape.getObjRecord().getSubRecords().get(0);
- assertEquals(2, cmo.getObjectId());
-
- shape = new HSSFComment(null, anchor);
- shape.setShapeId(1027);
- cmo = (CommonObjectDataSubRecord) shape.getObjRecord().getSubRecords().get(0);
- assertEquals(1027, cmo.getObjectId());
- }
-
- // As of POI 3.15 beta 2, LibreOffice does not display the diagonal border while it does display the bottom border
- // I have not checked Excel to know if this is a LibreOffice or a POI problem.
- @Test
- void test53564() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet("Page 1");
- final short BLUE = 30;
-
- HSSFSheetConditionalFormatting scf = sheet.getSheetConditionalFormatting();
- HSSFConditionalFormattingRule rule = scf.createConditionalFormattingRule(ComparisonOperator.GT, "10");
-
- HSSFBorderFormatting bord = rule.createBorderFormatting();
- bord.setBorderDiagonal(BorderStyle.THICK);
- assertEquals(BorderStyle.THICK, bord.getBorderDiagonal());
-
- bord.setBackwardDiagonalOn(true);
- assertTrue(bord.isBackwardDiagonalOn());
-
- bord.setForwardDiagonalOn(true);
- assertTrue(bord.isForwardDiagonalOn());
-
- bord.setDiagonalBorderColor(BLUE);
- assertEquals(BLUE, bord.getDiagonalBorderColor());
-
- // Create the bottom border style so we know what a border is supposed to look like
- bord.setBorderBottom(BorderStyle.THICK);
- assertEquals(BorderStyle.THICK, bord.getBorderBottom());
- bord.setBottomBorderColor(BLUE);
- assertEquals(BLUE, bord.getBottomBorderColor());
-
- CellRangeAddress[] A2_D4 = {new CellRangeAddress(1, 3, 0, 3)};
- scf.addConditionalFormatting(A2_D4, rule);
-
- // Set a cell value within the conditional formatting range whose rule would resolve to True.
- Cell C3 = sheet.createRow(2).createCell(2);
- C3.setCellValue(30.0);
- }
- }
-
- @Test
- void test61287() throws IOException {
- try (HSSFWorkbook wb = openSampleWorkbook("61287.xls");
- ExcelExtractor ex = new ExcelExtractor(wb)) {
- String text = ex.getText();
- assertContains(text, "\u8D44\u4EA7\u8D1F\u503A\u8868");
- }
- }
-
- @Test
- void test61300() throws Exception {
- try (POIFSFileSystem poifs = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("61300.xls"))) {
-
- DocumentEntry entry =
- (DocumentEntry) poifs.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
-
- RuntimeException ex = assertThrows(
- RuntimeException.class,
- () -> new PropertySet(new DocumentInputStream(entry))
- );
- assertEquals("Can't read negative number of bytes", ex.getMessage());
- }
- }
-
- @Test
- void test51262() throws IOException {
- try (HSSFWorkbook wb = openSampleWorkbook("51262.xls")) {
- Sheet sheet = wb.getSheetAt(0);
- Row row = sheet.getRow(2);
-
- Cell cell = row.getCell(1);
- CellStyle style = cell.getCellStyle();
- assertEquals(26, style.getFontIndex());
-
- row = sheet.getRow(3);
- cell = row.getCell(1);
- style = cell.getCellStyle();
- assertEquals(28, style.getFontIndex());
-
- // check the two fonts
- HSSFFont font = wb.getFontAt(26);
- assertTrue(font.getBold());
- assertEquals(10, font.getFontHeightInPoints());
- assertEquals("\uFF2D\uFF33 \uFF30\u30B4\u30B7\u30C3\u30AF", font.getFontName());
-
- font = wb.getFontAt(28);
- assertTrue(font.getBold());
- assertEquals(10, font.getFontHeightInPoints());
- assertEquals("\uFF2D\uFF33 \uFF30\u30B4\u30B7\u30C3\u30AF", font.getFontName());
- }
- }
-
- @Test
- void test60460() throws IOException {
- try (final Workbook wb = openSampleWorkbook("60460.xls")) {
- assertEquals(2, wb.getAllNames().size());
-
- Name rangedName = wb.getAllNames().get(0);
- assertFalse(rangedName.isFunctionName());
- assertEquals("'[\\\\HEPPC3\\gt$\\Teaching\\Syn\\physyn.xls]#REF'!$AK$70:$AL$70",
- // replace '/' to make test work equally on Windows and Linux
- rangedName.getRefersToFormula().replace("/", "\\"));
-
- rangedName = wb.getAllNames().get(1);
- assertFalse(rangedName.isFunctionName());
- assertEquals("Questionnaire!$A$1:$L$65", rangedName.getRefersToFormula());
- }
- }
-
- @Test
- void test63819() throws IOException {
- LocaleUtil.setUserLocale(Locale.UK);
- try {
- simpleTest("63819.xls", null);
- } finally {
- LocaleUtil.resetUserLocale();
- }
- }
-
- /**
- * Test that VALUE behaves properly as array function and its result is handled by aggregate function
- */
- @Test
- void testValueAsArrayFunction() throws IOException {
- try (final Workbook wb = openSampleWorkbook("TestValueAsArrayFunction.xls")) {
- wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
- Sheet sheet = wb.getSheetAt(0);
- Row row = sheet.getRow(0);
- Cell cell = row.getCell(0);
- assertEquals(6.0, cell.getNumericCellValue(), 0.0);
- }
- }
-
- // a simple test which rewrites the file once and evaluates its formulas
- @ParameterizedTest
- @CsvSource({
- "15228.xls", "13796.xls", "14460.xls", "14330-1.xls", "14330-2.xls", "22742.xls", "12561-1.xls", "12561-2.xls",
- "12843-1.xls", "12843-2.xls", "13224.xls", "19599-1.xls", "19599-2.xls", "32822.xls", "15573.xls",
- "33082.xls", "34775.xls", "37630.xls", "25183.xls", "26100.xls", "27933.xls", "29675.xls", "29982.xls",
- "31749.xls", "37376.xls", "SimpleWithAutofilter.xls", "44201.xls", "37684-1.xls", "37684-2.xls",
- "41139.xls", "ex42564-21435.xls", "ex42564-21503.xls", "28774.xls", "44891.xls", "44235.xls", "36947.xls",
- "39634.xls", "47701.xls", "48026.xls", "47251.xls", "47251_1.xls", "50020.xls", "50426.xls", "50779_1.xls",
- "50779_2.xls", "51670.xls", "54016.xls", "57456.xls", "53109.xls", "com.aida-tour.www_SPO_files_maldives%20august%20october.xls",
- "named-cell-in-formula-test.xls", "named-cell-test.xls", "bug55505.xls", "SUBSTITUTE.xls", "64261.xls"
- })
- void simpleTest(String fileName) throws IOException {
- simpleTest(fileName, null);
- }
-
- @SuppressWarnings("unchecked")
- @ParameterizedTest
- @CsvSource({
- "46904.xls, org.apache.poi.hssf.OldExcelFormatException, The supplied spreadsheet seems to be Excel",
- "51832.xls, org.apache.poi.EncryptedDocumentException, Default password is invalid for salt/verifier/verifierHash"
- })
- void simpleTest(String fileName, String exClazz, String exMessage) throws IOException, ClassNotFoundException {
- Class extends Exception> ex = (Class extends Exception>)Class.forName(exClazz);
- Exception e = assertThrows(ex, () -> simpleTest(fileName, null));
- assertTrue(e.getMessage().startsWith(exMessage));
- }
-
- private void simpleTest(String fileName, Consumer addTest) throws IOException {
- try (HSSFWorkbook wb1 = openSampleWorkbook(fileName)) {
- if (addTest != null) {
- addTest.accept(wb1);
- }
-
- HSSFSheet s = wb1.getSheetAt(0);
- HSSFRow r = s.createRow(10_000);
- HSSFCell c = r.createCell(0);
- c.setCellValue(10);
-
- HSSFSheet tmpSheet = wb1.createSheet("POITESTSHEET");
- tmpSheet.createRow(10).createCell(10).setCellValue("Test");
- wb1.removeSheetAt(wb1.getSheetIndex(tmpSheet));
-
- simpleTestHelper(wb1, fileName);
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- if (addTest != null) {
- addTest.accept(wb2);
- }
-
- double act = wb2.getSheetAt(0).getRow(10_000).getCell(0).getNumericCellValue();
- assertEquals(10, act, 0);
- simpleTestHelper(wb2, fileName);
- }
- }
- }
-
- private void simpleTestHelper(HSSFWorkbook wb, String fileName) {
- List files = new ArrayList<>();
- files.add(fileName);
- files.addAll(SIMPLE_REFS.keySet());
- List evals = new ArrayList<>();
- evals.add(wb.getCreationHelper().createFormulaEvaluator());
- evals.addAll(SIMPLE_REFS.values());
-
- try {
- HSSFFormulaEvaluator.setupEnvironment(files.toArray(new String[0]), evals.toArray(new HSSFFormulaEvaluator[0]));
- evals.get(0).evaluateAll();
- } catch (RuntimeException e) {
- throw new RuntimeException("While handling files " + files + " and evals " + evals, e);
- }
- }
-
-
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java
deleted file mode 100644
index d80f000368..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java
+++ /dev/null
@@ -1,504 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.apache.poi.ss.usermodel.BorderStyle.*;
-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.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNotSame;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Random;
-import java.util.stream.Stream;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-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.CellType;
-import org.apache.poi.ss.usermodel.DateUtil;
-import org.apache.poi.ss.usermodel.FillPatternType;
-import org.apache.poi.ss.usermodel.Font;
-import org.apache.poi.ss.usermodel.HorizontalAlignment;
-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.util.TempFile;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test cell styling functionality
- */
-
-final class TestCellStyle {
-
- private static HSSFWorkbook openSample(String sampleFileName) {
- return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
- }
-
-
- /**
- * TEST NAME: Test Write Sheet Font
- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with fonts.
- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects
- * Last row, first row is tested against the correct values (99,0).
- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good.
- * HSSFSheet last row or first row is incorrect.
- *
- */
- @Test
- void testWriteSheetFont() throws IOException{
- File file = TempFile.createTempFile("testWriteSheetFont", ".xls");
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- HSSFFont fnt = wb.createFont();
- HSSFCellStyle cs = wb.createCellStyle();
-
- fnt.setColor(HSSFFont.COLOR_RED);
- fnt.setBold(true);
- cs.setFont(fnt);
- for (int rownum = 0; rownum < 100; rownum++) {
- HSSFRow r = s.createRow(rownum);
-
- for (int cellnum = 0; cellnum < 50; cellnum += 2) {
- HSSFCell c = r.createCell(cellnum);
- c.setCellValue(rownum * 10000 + cellnum
- + (((double) rownum / 1000)
- + ((double) cellnum / 10000)));
- c = r.createCell(cellnum + 1);
- c.setCellValue("TEST");
- c.setCellStyle(cs);
- }
- }
- try (FileOutputStream out = new FileOutputStream(file)) {
- wb.write(out);
- }
-
- SanityChecker sanityChecker = new SanityChecker();
- sanityChecker.checkHSSFWorkbook(wb);
- assertEquals(99, s.getLastRowNum(), "LAST ROW == 99");
- assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0");
- }
-
- // assert((s.getLastRowNum() == 99));
- }
-
- /**
- * Tests that is creating a file with a date or an calendar works correctly.
- */
- @Test
- void testDataStyle() throws IOException {
- File file = TempFile.createTempFile("testWriteSheetStyleDate", ".xls");
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- HSSFCellStyle cs = wb.createCellStyle();
- HSSFRow row = s.createRow(0);
-
- // with Date:
- HSSFCell cell = row.createCell(1);
- cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
- cell.setCellStyle(cs);
- cell.setCellValue(new Date());
-
- // with Calendar:
- cell = row.createCell(2);
- cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
- cell.setCellStyle(cs);
- Calendar cal = LocaleUtil.getLocaleCalendar();
- cell.setCellValue(cal);
-
- try (FileOutputStream out = new FileOutputStream(file)) {
- wb.write(out);
- }
- SanityChecker sanityChecker = new SanityChecker();
- sanityChecker.checkHSSFWorkbook(wb);
-
- assertEquals(0, s.getLastRowNum(), "LAST ROW");
- assertEquals(0, s.getFirstRowNum(), "FIRST ROW");
- }
- }
-
- @Test
- void testHashEquals() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- HSSFCellStyle cs1 = wb.createCellStyle();
- HSSFCellStyle cs2 = wb.createCellStyle();
- HSSFRow row = s.createRow(0);
- HSSFCell cell1 = row.createCell(1);
- HSSFCell cell2 = row.createCell(2);
-
- cs1.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
- cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/dd/yy"));
-
- cell1.setCellStyle(cs1);
- cell1.setCellValue(new Date());
-
- cell2.setCellStyle(cs2);
- cell2.setCellValue(new Date());
-
- assertEquals(cs1.hashCode(), cs1.hashCode());
- assertEquals(cs2.hashCode(), cs2.hashCode());
- assertEquals(cs1, cs1);
- assertEquals(cs2, cs2);
-
- // Change cs1, hash will alter
- int hash1 = cs1.hashCode();
- cs1.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/dd/yy"));
- assertNotEquals(hash1, cs1.hashCode());
- }
- }
-
- /**
- * TEST NAME: Test Write Sheet Style
- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with colors
- * and borders.
- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects
- * Last row, first row is tested against the correct values (99,0).
- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good.
- * HSSFSheet last row or first row is incorrect.
- *
- */
- @Test
- void testWriteSheetStyle() throws IOException {
- File file = TempFile.createTempFile("testWriteSheetStyle", ".xls");
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- HSSFFont fnt = wb.createFont();
- HSSFCellStyle cs = wb.createCellStyle();
- HSSFCellStyle cs2 = wb.createCellStyle();
-
- cs.setBorderBottom(THIN);
- cs.setBorderLeft(THIN);
- cs.setBorderRight(THIN);
- cs.setBorderTop(THIN);
- cs.setFillForegroundColor((short) 0xA);
- cs.setFillPattern(FillPatternType.DIAMONDS);
- fnt.setColor((short) 0xf);
- fnt.setItalic(true);
- cs2.setFillForegroundColor((short) 0x0);
- cs2.setFillPattern(FillPatternType.DIAMONDS);
- cs2.setFont(fnt);
- for (int rownum = 0; rownum < 100; rownum++) {
- HSSFRow r = s.createRow(rownum);
-
- for (int cellnum = 0; cellnum < 50; cellnum += 2) {
- HSSFCell c = r.createCell(cellnum);
- c.setCellValue(rownum * 10000 + cellnum
- + (((double) rownum / 1000)
- + ((double) cellnum / 10000)));
- c.setCellStyle(cs);
- c = r.createCell(cellnum + 1);
- c.setCellValue("TEST");
- c.setCellStyle(cs2);
- }
- }
- try (FileOutputStream out = new FileOutputStream(file)) {
- wb.write(out);
- }
- SanityChecker sanityChecker = new SanityChecker();
- sanityChecker.checkHSSFWorkbook(wb);
- assertEquals(99, s.getLastRowNum(), "LAST ROW == 99");
- assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0");
- }
- }
-
- /**
- * Cloning one HSSFCellStyle onto Another, same
- * HSSFWorkbook
- */
- @Test
- void testCloneStyleSameWB() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFFont fnt = wb.createFont();
- fnt.setFontName("TestingFont");
- assertEquals(5, wb.getNumberOfFonts());
-
- HSSFCellStyle orig = wb.createCellStyle();
- orig.setAlignment(HorizontalAlignment.JUSTIFY);
- orig.setFont(fnt);
- orig.setDataFormat((short) 18);
-
- assertEquals(HorizontalAlignment.JUSTIFY, orig.getAlignment());
- assertEquals(fnt, orig.getFont(wb));
- assertEquals(18, orig.getDataFormat());
-
- HSSFCellStyle clone = wb.createCellStyle();
- assertNotSame(HorizontalAlignment.RIGHT, clone.getAlignment());
- assertNotSame(fnt, clone.getFont(wb));
- assertNotEquals(18, clone.getDataFormat());
-
- clone.cloneStyleFrom(orig);
- assertEquals(HorizontalAlignment.JUSTIFY, clone.getAlignment());
- assertEquals(fnt, clone.getFont(wb));
- assertEquals(18, clone.getDataFormat());
- assertEquals(5, wb.getNumberOfFonts());
- }
- }
-
- /**
- * Cloning one HSSFCellStyle onto Another, across
- * two different HSSFWorkbooks
- */
- @Test
- void testCloneStyleDiffWB() throws IOException {
- try (HSSFWorkbook wbOrig = new HSSFWorkbook()) {
-
- HSSFFont fnt = wbOrig.createFont();
- fnt.setFontName("TestingFont");
- assertEquals(5, wbOrig.getNumberOfFonts());
-
- HSSFDataFormat fmt = wbOrig.createDataFormat();
- fmt.getFormat("MadeUpOne");
- fmt.getFormat("MadeUpTwo");
-
- HSSFCellStyle orig = wbOrig.createCellStyle();
- orig.setAlignment(HorizontalAlignment.RIGHT);
- orig.setFont(fnt);
- orig.setDataFormat(fmt.getFormat("Test##"));
-
- assertEquals(HorizontalAlignment.RIGHT, orig.getAlignment());
- assertEquals(fnt, orig.getFont(wbOrig));
- assertEquals(fmt.getFormat("Test##"), orig.getDataFormat());
-
- // Now a style on another workbook
- try (HSSFWorkbook wbClone = new HSSFWorkbook()) {
- assertEquals(4, wbClone.getNumberOfFonts());
- HSSFDataFormat fmtClone = wbClone.createDataFormat();
-
- HSSFCellStyle clone = wbClone.createCellStyle();
- assertEquals(4, wbClone.getNumberOfFonts());
-
- assertNotSame(HorizontalAlignment.RIGHT, clone.getAlignment());
- assertNotSame("TestingFont", clone.getFont(wbClone).getFontName());
-
- clone.cloneStyleFrom(orig);
- assertEquals(HorizontalAlignment.RIGHT, clone.getAlignment());
- assertEquals("TestingFont", clone.getFont(wbClone).getFontName());
- assertEquals(fmtClone.getFormat("Test##"), clone.getDataFormat());
- assertNotEquals(fmtClone.getFormat("Test##"), fmt.getFormat("Test##"));
- assertEquals(5, wbClone.getNumberOfFonts());
- }
- }
- }
-
- @Test
- void testStyleNames() throws IOException {
- try (HSSFWorkbook wb = openSample("WithExtendedStyles.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
- HSSFCell c1 = s.getRow(0).getCell(0);
- HSSFCell c2 = s.getRow(1).getCell(0);
- HSSFCell c3 = s.getRow(2).getCell(0);
-
- HSSFCellStyle cs1 = c1.getCellStyle();
- HSSFCellStyle cs2 = c2.getCellStyle();
- HSSFCellStyle cs3 = c3.getCellStyle();
-
- assertNotNull(cs1);
- assertNotNull(cs2);
- assertNotNull(cs3);
-
- // Check we got the styles we'd expect
- assertEquals(10, cs1.getFont(wb).getFontHeightInPoints());
- assertEquals(9, cs2.getFont(wb).getFontHeightInPoints());
- assertEquals(12, cs3.getFont(wb).getFontHeightInPoints());
-
- assertEquals(15, cs1.getIndex());
- assertEquals(23, cs2.getIndex());
- assertEquals(24, cs3.getIndex());
-
- assertNull(cs1.getParentStyle());
- assertNotNull(cs2.getParentStyle());
- assertNotNull(cs3.getParentStyle());
-
- assertEquals(21, cs2.getParentStyle().getIndex());
- assertEquals(22, cs3.getParentStyle().getIndex());
-
- // Now check we can get style records for the parent ones
- assertNull(wb.getWorkbook().getStyleRecord(15));
- assertNull(wb.getWorkbook().getStyleRecord(23));
- assertNull(wb.getWorkbook().getStyleRecord(24));
-
- assertNotNull(wb.getWorkbook().getStyleRecord(21));
- assertNotNull(wb.getWorkbook().getStyleRecord(22));
-
- // Now check the style names
- assertNull(cs1.getUserStyleName());
- assertNull(cs2.getUserStyleName());
- assertNull(cs3.getUserStyleName());
- assertEquals("style1", cs2.getParentStyle().getUserStyleName());
- assertEquals("style2", cs3.getParentStyle().getUserStyleName());
-
- // now apply a named style to a new cell
- HSSFCell c4 = s.getRow(0).createCell(1);
- c4.setCellStyle(cs2);
- assertEquals("style1", c4.getCellStyle().getParentStyle().getUserStyleName());
- }
- }
-
- @Test
- void testGetSetBorderHair() throws IOException {
- BorderStyle[] bs = {
- HAIR, DOTTED, DASH_DOT_DOT, DASHED, THIN, MEDIUM_DASH_DOT_DOT, SLANTED_DASH_DOT,
- MEDIUM_DASH_DOT, MEDIUM_DASHED, MEDIUM, THICK, DOUBLE
- };
-
- try (HSSFWorkbook wb = openSample("55341_CellStyleBorder.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
- for (int i = 0; i assertDoesNotThrow(() -> {
- Random rand = new Random();
- for(int i=0; i<10; i++) {
- Thread.sleep(rand.nextInt(300));
- try (Workbook wb = openSample(fileName)) {
- for (Row row : wb.getSheetAt(0)) {
- for (Cell cell : row) {
- cell.getCellStyle().getDataFormatString();
- if (cell.getCellType() == CellType.NUMERIC) {
- boolean isDate = DateUtil.isCellDateFormatted(cell);
- int cid = cell.getColumnIndex();
- assertFalse(cid > 0 && isDate, "cell " + cid + " is not a date.");
- }
- }
- }
- }
- }
- }));
- }
-
- @Test
- void test56959() throws IOException {
- try (Workbook wb = new HSSFWorkbook()) {
- Sheet sheet = wb.createSheet("somesheet");
-
- Row row = sheet.createRow(0);
-
- // Create a new font and alter it.
- Font font = wb.createFont();
- font.setFontHeightInPoints((short) 24);
- font.setFontName("Courier New");
- font.setItalic(true);
- font.setStrikeout(true);
- font.setColor(Font.COLOR_RED);
-
- CellStyle style = wb.createCellStyle();
- style.setBorderBottom(DOTTED);
- style.setFont(font);
-
- Cell cell = row.createCell(0);
- cell.setCellStyle(style);
- cell.setCellValue("testtext");
-
- Cell newCell = row.createCell(1);
-
- newCell.setCellStyle(style);
- newCell.setCellValue("2testtext2");
-
- CellStyle newStyle = newCell.getCellStyle();
- assertEquals(DOTTED, newStyle.getBorderBottom());
- assertEquals(Font.COLOR_RED, ((HSSFCellStyle) newStyle).getFont(wb).getColor());
- }
- }
-
-
- @Test
- void test58043() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFCellStyle cellStyle = wb.createCellStyle();
-
- assertEquals(0, cellStyle.getRotation());
-
- cellStyle.setRotation((short) 89);
- assertEquals(89, cellStyle.getRotation());
-
- cellStyle.setRotation((short) 90);
- assertEquals(90, cellStyle.getRotation());
-
- cellStyle.setRotation((short) -1);
- assertEquals(-1, cellStyle.getRotation());
-
- cellStyle.setRotation((short) -89);
- assertEquals(-89, cellStyle.getRotation());
-
- cellStyle.setRotation((short) -90);
- assertEquals(-90, cellStyle.getRotation());
-
- cellStyle.setRotation((short) -89);
- assertEquals(-89, cellStyle.getRotation());
-
- // values above 90 are mapped to the correct values for compatibility between HSSF and XSSF
- cellStyle.setRotation((short) 179);
- assertEquals(-89, cellStyle.getRotation());
-
- cellStyle.setRotation((short) 180);
- assertEquals(-90, cellStyle.getRotation());
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java
deleted file mode 100644
index cb3d92d113..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.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.hssf.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.assertNull;
-
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.poi.ddf.EscherDgRecord;
-import org.apache.poi.ddf.EscherSpRecord;
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.record.CommonObjectDataSubRecord;
-import org.apache.poi.hssf.record.EscherAggregate;
-import org.apache.poi.ss.usermodel.BaseTestCloneSheet;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test the ability to clone a sheet.
- * If adding new records that belong to a sheet (as opposed to a book)
- * add that record to the sheet in the testCloneSheetBasic method.
- * @author avik
- */
-final class TestCloneSheet extends BaseTestCloneSheet {
- public TestCloneSheet() {
- super(HSSFITestDataProvider.instance);
- }
-
- @Test
- void testCloneSheetWithoutDrawings(){
- HSSFWorkbook b = new HSSFWorkbook();
- HSSFSheet s = b.createSheet("Test");
- HSSFSheet s2 = s.cloneSheet(b);
-
- assertNull(s.getDrawingPatriarch());
- assertNull(s2.getDrawingPatriarch());
- assertEquals(HSSFTestHelper.getSheetForTest(s).getRecords().size(), HSSFTestHelper.getSheetForTest(s2).getRecords().size());
- }
-
- @Test
- void testCloneSheetWithEmptyDrawingAggregate(){
- HSSFWorkbook b = new HSSFWorkbook();
- HSSFSheet s = b.createSheet("Test");
- HSSFPatriarch patriarch = s.createDrawingPatriarch();
-
- EscherAggregate agg1 = patriarch.getBoundAggregate();
-
- HSSFSheet s2 = s.cloneSheet(b);
-
- patriarch = s2.getDrawingPatriarch();
-
- EscherAggregate agg2 = patriarch.getBoundAggregate();
-
- EscherSpRecord sp1 = (EscherSpRecord) agg1.getEscherContainer().getChild(1).getChild(0).getChild(1);
- EscherSpRecord sp2 = (EscherSpRecord) agg2.getEscherContainer().getChild(1).getChild(0).getChild(1);
-
- assertEquals(sp1.getShapeId(), 1024);
- assertEquals(sp2.getShapeId(), 2048);
-
- EscherDgRecord dg = (EscherDgRecord) agg2.getEscherContainer().getChild(0);
-
- assertEquals(dg.getLastMSOSPID(), 2048);
- assertEquals(dg.getInstance(), 0x2);
-
- //everything except id and DgRecord.lastMSOSPID and DgRecord.Instance must be the same
-
- sp2.setShapeId(1024);
- dg.setLastMSOSPID(1024);
- dg.setInstance((short) 0x1);
-
- assertEquals(agg1.serialize().length, agg2.serialize().length);
- assertEquals(agg1.toXml(""), agg2.toXml(""));
- assertArrayEquals(agg1.serialize(), agg2.serialize());
- }
-
- @Test
- void testCloneComment() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
- HSSFPatriarch p = sh.createDrawingPatriarch();
- HSSFComment c = p.createComment(new HSSFClientAnchor(0,0,100,100, (short) 0,0,(short)5,5));
- c.setColumn(1);
- c.setRow(2);
- c.setString(new HSSFRichTextString("qwertyuio"));
-
- HSSFSheet sh2 = wb.cloneSheet(0);
- HSSFPatriarch p2 = sh2.getDrawingPatriarch();
- HSSFComment c2 = (HSSFComment) p2.getChildren().get(0);
-
- assertEquals(c.getString(), c2.getString());
- assertEquals(c.getRow(), c2.getRow());
- assertEquals(c.getColumn(), c2.getColumn());
-
- // The ShapeId is not equal?
- // assertEquals(c.getNoteRecord().getShapeId(), c2.getNoteRecord().getShapeId());
-
- assertArrayEquals(c2.getTextObjectRecord().serialize(), c.getTextObjectRecord().serialize());
-
- // ShapeId is different
- CommonObjectDataSubRecord subRecord = (CommonObjectDataSubRecord) c2.getObjRecord().getSubRecords().get(0);
- subRecord.setObjectId(1025);
-
- assertArrayEquals(c2.getObjRecord().serialize(), c.getObjRecord().serialize());
-
- // ShapeId is different
- c2.getNoteRecord().setShapeId(1025);
- assertArrayEquals(c2.getNoteRecord().serialize(), c.getNoteRecord().serialize());
-
- //everything except spRecord.shapeId must be the same
- assertFalse(Arrays.equals(c2.getEscherContainer().serialize(), c.getEscherContainer().serialize()));
- EscherSpRecord sp = (EscherSpRecord) c2.getEscherContainer().getChild(0);
- sp.setShapeId(1025);
- assertArrayEquals(c2.getEscherContainer().serialize(), c.getEscherContainer().serialize());
-
- wb.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java
deleted file mode 100644
index 0f7d5788fe..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.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.hssf.usermodel;
-
-import static org.apache.poi.POITestCase.assertContains;
-
-import java.io.IOException;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.extractor.ExcelExtractor;
-import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
-import org.junit.jupiter.api.Test;
-
-class TestCryptoAPI {
- final HSSFITestDataProvider ssTests = HSSFITestDataProvider.instance;
-
- @Test
- void bug59857() throws IOException {
- // XOR-Obfuscation
- // TODO: XOR-Obfuscation is currently flawed - although the de-/obfuscation initially works,
- // it suddenly differs from the result of encrypted files via Office ...
- // and only very small files can be opened without file validation errors
- validateContent("xor-encryption-abc.xls", "abc", "Sheet1\n1\n2\n3\n");
-
- // BinaryRC4
- validateContent("password.xls", "password", "A ZIP bomb is a variant of mail-bombing. After most commercial mail servers began checking mail with anti-virus software and filtering certain malicious file types, trojan horse viruses tried to send themselves compressed into archives, such as ZIP, RAR or 7-Zip. Mail server software was then configured to unpack archives and check their contents as well. That gave black hats the idea to compose a \"bomb\" consisting of an enormous text file, containing, for example, only the letter z repeated millions of times. Such a file compresses into a relatively small archive, but its unpacking (especially by early versions of mail servers) would use a high amount of processing power, RAM and swap space, which could result in denial of service. Modern mail server computers usually have sufficient intelligence to recognize such attacks as well as sufficient processing power and memory space to process malicious attachments without interruption of service, though some are still susceptible to this technique if the ZIP bomb is mass-mailed.");
-
- // CryptoAPI
- validateContent("35897-type4.xls", "freedom", "Sheet1\nhello there!\n");
- }
-
- private void validateContent(String wbFile, String password, String textExpected) throws IOException {
- Biff8EncryptionKey.setCurrentUserPassword(password);
- try (HSSFWorkbook wb = ssTests.openSampleWorkbook(wbFile);
- ExcelExtractor ee1 = new ExcelExtractor(wb)
- ) {
- Biff8EncryptionKey.setCurrentUserPassword("bla");
- try (HSSFWorkbook wbBla = ssTests.writeOutAndReadBack(wb);
- ExcelExtractor ee2 = new ExcelExtractor(wbBla)) {
- assertContains(ee1.getText(), textExpected);
- assertContains(ee2.getText(), textExpected);
- }
- } finally {
- Biff8EncryptionKey.setCurrentUserPassword(null);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java b/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java
deleted file mode 100644
index 4a120b2ac6..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java
+++ /dev/null
@@ -1,434 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.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.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.util.List;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.DVRecord;
-import org.apache.poi.ss.usermodel.BaseTestDataValidation;
-import org.apache.poi.ss.usermodel.DataValidation;
-import org.apache.poi.ss.usermodel.DataValidation.ErrorStyle;
-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.DateUtil;
-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.CellRangeAddressList;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class for testing Excel's data validation mechanism
- *
- * @author Dragos Buleandra ( dragos.buleandra@trade2b.ro )
- */
-final class TestDataValidation extends BaseTestDataValidation {
-
- public TestDataValidation(){
- super(HSSFITestDataProvider.instance);
- }
-
-
- void assertDataValidation(Workbook wb) {
-
- byte[] generatedContent;
- try (ByteArrayOutputStream baos = new ByteArrayOutputStream(22000)) {
- wb.write(baos);
- generatedContent = baos.toByteArray();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- boolean isSame;
-// if (false) {
-// // TODO - add proof spreadsheet and compare
-// InputStream proofStream = HSSFTestDataSamples.openSampleFileStream("TestDataValidation.xls");
-// isSame = compareStreams(proofStream, generatedContent);
-// }
- isSame = true;
-
- if (isSame) {
- return;
- }
- File tempDir = new File(System.getProperty("java.io.tmpdir"));
- File generatedFile = new File(tempDir, "GeneratedTestDataValidation.xls");
- try (FileOutputStream fileOut = new FileOutputStream(generatedFile)) {
- fileOut.write(generatedContent);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- PrintStream ps = System.out;
-
- ps.println("This test case has failed because the generated file differs from proof copy '"
- ); // TODO+ proofFile.getAbsolutePath() + "'.");
- ps.println("The cause is usually a change to this test, or some common spreadsheet generation code. "
- + "The developer has to decide whether the changes were wanted or unwanted.");
- ps.println("If the changes to the generated version were unwanted, "
- + "make the fix elsewhere (do not modify this test or the proof spreadsheet to get the test working).");
- ps.println("If the changes were wanted, make sure to open the newly generated file in Excel "
- + "and verify it manually. The new proof file should be submitted after it is verified to be correct.");
- ps.println();
- ps.println("One other possible (but less likely) cause of a failed test is a problem in the "
- + "comparison logic used here. Perhaps some extra file regions need to be ignored.");
- ps.println("The generated file has been saved to '" + generatedFile.getAbsolutePath() + "' for manual inspection.");
-
- fail("Generated file differs from proof copy. See sysout comments for details on how to fix.");
-
- }
-
- /* package */ static void setCellValue(HSSFCell cell, String text) {
- cell.setCellValue(new HSSFRichTextString(text));
-
- }
-
- @Test
- void testAddToExistingSheet() throws Exception {
-
- // dvEmpty.xls is a simple one sheet workbook. With a DataValidations header record but no
- // DataValidations. It's important that the example has one SHEETPROTECTION record.
- // Such a workbook can be created in Excel (2007) by adding datavalidation for one cell
- // and then deleting the row that contains the cell.
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("dvEmpty.xls")) {
- int dvRow = 0;
- Sheet sheet = wb.getSheetAt(0);
- DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
- DataValidationConstraint dc = dataValidationHelper.createIntegerConstraint(OperatorType.EQUAL, "42", null);
- DataValidation dv = dataValidationHelper.createValidation(dc, new CellRangeAddressList(dvRow, dvRow, 0, 0));
-
- dv.setEmptyCellAllowed(false);
- dv.setErrorStyle(ErrorStyle.STOP);
- dv.setShowPromptBox(true);
- dv.createErrorBox("Xxx", "Yyy");
- dv.setSuppressDropDownArrow(true);
-
- sheet.addValidationData(dv);
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- wb.write(baos);
-
- byte[] wbData = baos.toByteArray();
-
-// if (false) { // TODO (Jul 2008) fix EventRecordFactory to process unknown records, (and DV records for that matter)
-//
-// ERFListener erfListener = null; // new MyERFListener();
-// EventRecordFactory erf = new EventRecordFactory(erfListener, null);
-// try {
-// POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(baos.toByteArray()));
-// erf.processRecords(fs.createDocumentInputStream("Workbook"));
-// } catch (RecordFormatException e) {
-// throw new RuntimeException(e);
-// } catch (IOException e) {
-// throw new RuntimeException(e);
-// }
-// }
- // else verify record ordering by navigating the raw bytes
-
- byte[] dvHeaderRecStart = {(byte) 0xB2, 0x01, 0x12, 0x00,};
- int dvHeaderOffset = findIndex(wbData, dvHeaderRecStart);
- assertTrue(dvHeaderOffset > 0);
- int nextRecIndex = dvHeaderOffset + 22;
- int nextSid
- = ((wbData[nextRecIndex + 0] << 0) & 0x00FF)
- + ((wbData[nextRecIndex + 1] << 8) & 0xFF00);
- // nextSid should be for a DVRecord. If anything comes between the DV header record
- // and the DV records, Excel will not be able to open the workbook without error.
-
- assertNotEquals(0x0867, nextSid, "Identified bug 45519");
- assertEquals(DVRecord.sid, nextSid);
- }
- }
-
- private int findIndex(byte[] largeData, byte[] searchPattern) {
- byte firstByte = searchPattern[0];
- for (int i = 0; i < largeData.length; i++) {
- if(largeData[i] != firstByte) {
- continue;
- }
- boolean match = true;
- for (int j = 1; j < searchPattern.length; j++) {
- if(searchPattern[j] != largeData[i+j]) {
- match = false;
- break;
- }
- }
- if (match) {
- return i;
- }
- }
- return -1;
- }
-
- @Test
- void testGetDataValidationsAny() throws Exception {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- List list = sheet.getDataValidations();
- assertEquals(0, list.size());
-
- DataValidationHelper dvh = sheet.getDataValidationHelper();
- DataValidationConstraint constraint = dvh.createNumericConstraint(ValidationType.ANY, OperatorType.IGNORED, null, null);
- CellRangeAddressList addressList = new CellRangeAddressList(1, 2, 3, 4);
- DataValidation validation = dvh.createValidation(constraint, addressList);
- validation.setEmptyCellAllowed(true);
- validation.createErrorBox("error-title", "error-text");
- validation.createPromptBox("prompt-title", "prompt-text");
- sheet.addValidationData(validation);
-
- list = sheet.getDataValidations(); // <-- works
- assertEquals(1, list.size());
-
- HSSFDataValidation dv = list.get(0);
- {
- CellRangeAddressList regions = dv.getRegions();
- assertEquals(1, regions.countRanges());
-
- CellRangeAddress address = regions.getCellRangeAddress(0);
- assertEquals(1, address.getFirstRow());
- assertEquals(2, address.getLastRow());
- assertEquals(3, address.getFirstColumn());
- assertEquals(4, address.getLastColumn());
- }
- assertTrue(dv.getEmptyCellAllowed());
- assertFalse(dv.getSuppressDropDownArrow());
- assertTrue(dv.getShowErrorBox());
- assertEquals("error-title", dv.getErrorBoxTitle());
- assertEquals("error-text", dv.getErrorBoxText());
- assertTrue(dv.getShowPromptBox());
- assertEquals("prompt-title", dv.getPromptBoxTitle());
- assertEquals("prompt-text", dv.getPromptBoxText());
-
- DataValidationConstraint c = dv.getValidationConstraint();
- assertEquals(ValidationType.ANY, c.getValidationType());
- assertEquals(OperatorType.IGNORED, c.getOperator());
- }
- }
-
- @Test
- void testGetDataValidationsIntegerFormula() throws Exception {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- List list = sheet.getDataValidations();
- assertEquals(0, list.size());
-
- DataValidationHelper dvh = sheet.getDataValidationHelper();
- DataValidationConstraint constraint = dvh.createIntegerConstraint(OperatorType.BETWEEN, "=A2", "=A3");
- CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
- DataValidation validation = dvh.createValidation(constraint, addressList);
- sheet.addValidationData(validation);
-
- list = sheet.getDataValidations(); // <-- works
- assertEquals(1, list.size());
-
- HSSFDataValidation dv = list.get(0);
- DVConstraint c = dv.getConstraint();
- assertEquals(ValidationType.INTEGER, c.getValidationType());
- assertEquals(OperatorType.BETWEEN, c.getOperator());
- assertEquals("A2", c.getFormula1());
- assertEquals("A3", c.getFormula2());
- assertNull(c.getValue1());
- assertNull(c.getValue2());
- }
- }
-
- @Test
- void testGetDataValidationsIntegerValue() throws Exception {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- List list = sheet.getDataValidations();
- assertEquals(0, list.size());
-
- DataValidationHelper dvh = sheet.getDataValidationHelper();
- DataValidationConstraint constraint = dvh.createIntegerConstraint(OperatorType.BETWEEN, "100", "200");
- CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
- DataValidation validation = dvh.createValidation(constraint, addressList);
- sheet.addValidationData(validation);
-
- list = sheet.getDataValidations(); // <-- works
- assertEquals(1, list.size());
-
- HSSFDataValidation dv = list.get(0);
- DVConstraint c = dv.getConstraint();
- assertEquals(ValidationType.INTEGER, c.getValidationType());
- assertEquals(OperatorType.BETWEEN, c.getOperator());
- assertNull(c.getFormula1());
- assertNull(c.getFormula2());
- assertEquals(100d, c.getValue1(), 0);
- assertEquals(200d, c.getValue2(), 0);
- }
- }
-
- @Test
- void testGetDataValidationsDecimal() throws Exception {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- List list = sheet.getDataValidations();
- assertEquals(0, list.size());
-
- DataValidationHelper dvh = sheet.getDataValidationHelper();
- DataValidationConstraint constraint = dvh.createDecimalConstraint(OperatorType.BETWEEN, "=A2", "200");
- CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
- DataValidation validation = dvh.createValidation(constraint, addressList);
- sheet.addValidationData(validation);
-
- list = sheet.getDataValidations(); // <-- works
- assertEquals(1, list.size());
-
- HSSFDataValidation dv = list.get(0);
- DVConstraint c = dv.getConstraint();
- assertEquals(ValidationType.DECIMAL, c.getValidationType());
- assertEquals(OperatorType.BETWEEN, c.getOperator());
- assertEquals("A2", c.getFormula1());
- assertNull(c.getFormula2());
- assertNull(c.getValue1());
- assertEquals(200, c.getValue2(), 0);
- }
- }
-
- @Test
- void testGetDataValidationsDate() throws Exception {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- List list = sheet.getDataValidations();
- assertEquals(0, list.size());
-
- DataValidationHelper dvh = sheet.getDataValidationHelper();
- DataValidationConstraint constraint = dvh.createDateConstraint(OperatorType.EQUAL, "2014/10/25", null, null);
- CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
- DataValidation validation = dvh.createValidation(constraint, addressList);
- sheet.addValidationData(validation);
-
- list = sheet.getDataValidations(); // <-- works
- assertEquals(1, list.size());
-
- HSSFDataValidation dv = list.get(0);
- DVConstraint c = dv.getConstraint();
- assertEquals(ValidationType.DATE, c.getValidationType());
- assertEquals(OperatorType.EQUAL, c.getOperator());
- assertNull(c.getFormula1());
- assertNull(c.getFormula2());
- assertEquals(DateUtil.getExcelDate(DateUtil.parseYYYYMMDDDate("2014/10/25")), c.getValue1(), 0);
- assertNull(c.getValue2());
- }
- }
-
- @Test
- void testGetDataValidationsListExplicit() throws Exception {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- List list = sheet.getDataValidations();
- assertEquals(0, list.size());
-
- DataValidationHelper dvh = sheet.getDataValidationHelper();
- DataValidationConstraint constraint = dvh.createExplicitListConstraint(new String[]{"aaa", "bbb", "ccc"});
- CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
- DataValidation validation = dvh.createValidation(constraint, addressList);
- validation.setSuppressDropDownArrow(true);
- sheet.addValidationData(validation);
-
- list = sheet.getDataValidations(); // <-- works
- assertEquals(1, list.size());
-
- HSSFDataValidation dv = list.get(0);
- assertTrue(dv.getSuppressDropDownArrow());
-
- DVConstraint c = dv.getConstraint();
- assertEquals(ValidationType.LIST, c.getValidationType());
- assertNull(c.getFormula1());
- assertNull(c.getFormula2());
- assertNull(c.getValue1());
- assertNull(c.getValue2());
- String[] values = c.getExplicitListValues();
- assertEquals(3, values.length);
- assertEquals("aaa", values[0]);
- assertEquals("bbb", values[1]);
- assertEquals("ccc", values[2]);
- }
- }
-
- @Test
- void testGetDataValidationsListFormula() throws Exception {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- List list = sheet.getDataValidations();
- assertEquals(0, list.size());
-
- DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
- DataValidationConstraint constraint = dataValidationHelper.createFormulaListConstraint("A2");
- CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
- DataValidation validation = dataValidationHelper.createValidation(constraint, addressList);
- validation.setSuppressDropDownArrow(true);
- sheet.addValidationData(validation);
-
- list = sheet.getDataValidations(); // <-- works
- assertEquals(1, list.size());
-
- HSSFDataValidation dv = list.get(0);
- assertTrue(dv.getSuppressDropDownArrow());
-
- DVConstraint c = dv.getConstraint();
- assertEquals(ValidationType.LIST, c.getValidationType());
- assertEquals("A2", c.getFormula1());
- assertNull(c.getFormula2());
- assertNull(c.getValue1());
- assertNull(c.getValue2());
- }
- }
-
- @Test
- void testGetDataValidationsFormula() throws Exception {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- List list = sheet.getDataValidations();
- assertEquals(0, list.size());
-
- DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
- DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("A2:A3");
- CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
- DataValidation validation = dataValidationHelper.createValidation(constraint, addressList);
- sheet.addValidationData(validation);
-
- list = sheet.getDataValidations(); // <-- works
- assertEquals(1, list.size());
-
- HSSFDataValidation dv = list.get(0);
- DVConstraint c = dv.getConstraint();
- assertEquals(ValidationType.FORMULA, c.getValidationType());
- assertEquals("A2:A3", c.getFormula1());
- assertNull(c.getFormula2());
- assertNull(c.getValue1());
- assertNull(c.getValue2());
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java
deleted file mode 100644
index 1617bd65ad..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.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.hssf.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.hssf.HSSFTestDataSamples;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for the embedded object fetching support in HSSF
- */
-class TestEmbeddedObjects {
- @Test
- void testReadExistingObject() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls")) {
- List list = wb.getAllEmbeddedObjects();
- assertEquals(list.size(), 1);
- HSSFObjectData obj = list.get(0);
- assertNotNull(obj.getObjectData());
- assertNotNull(obj.getDirectory());
- assertNotNull(obj.getOLE2ClassName());
- }
- }
-
- /**
- * Need to recurse into the shapes to find this one
- * See https://github.com/apache/poi/pull/2
- */
- @Test
- void testReadNestedObject() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithCheckBoxes.xls")) {
- List list = wb.getAllEmbeddedObjects();
- assertEquals(list.size(), 1);
- HSSFObjectData obj = list.get(0);
- assertNotNull(obj.getObjectData());
- assertNotNull(obj.getOLE2ClassName());
- }
- }
-
- /**
- * One with large numbers of recursivly embedded resources
- * See https://github.com/apache/poi/pull/2
- */
- @Test
- void testReadManyNestedObjects() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("45538_form_Header.xls")) {
- List list = wb.getAllEmbeddedObjects();
- assertEquals(list.size(), 40);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java
deleted file mode 100644
index 3ddac1b794..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java
+++ /dev/null
@@ -1,307 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-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.awt.Color;
-import java.awt.Font;
-import java.awt.FontMetrics;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the capabilities of the EscherGraphics class.
- *
- * All tests have two escher groups available to them,
- * one anchored at 0,0,1022,255 and another anchored
- * at 20,30,500,200
- */
-final class TestEscherGraphics {
- private HSSFWorkbook workbook;
- private HSSFPatriarch patriarch;
- private HSSFShapeGroup escherGroupA;
- private EscherGraphics graphics;
-
- @BeforeEach
- void setUp() throws IOException {
- workbook = new HSSFWorkbook();
-
- HSSFSheet sheet = workbook.createSheet("test");
- patriarch = sheet.createDrawingPatriarch();
- escherGroupA = patriarch.createGroup(new HSSFClientAnchor(0,0,1022,255,(short)0,0,(short) 0,0));
- patriarch.createGroup(new HSSFClientAnchor(20,30,500,200,(short)0,0,(short) 0,0));
- graphics = new EscherGraphics(escherGroupA, workbook, Color.black, 1.0f);
- }
-
- @AfterEach
- void closeResources() throws IOException {
- workbook.close();
- }
-
- @Test
- void testGetFont() {
- Font f = graphics.getFont();
- if (! f.toString().contains("dialog") && ! f.toString().contains("Dialog")) {
- assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", f.toString());
- }
- }
-
- @Test
- void testGetFontMetrics() {
- Font f = graphics.getFont();
- if (f.toString().contains("dialog") || f.toString().contains("Dialog")) {
- return;
- }
- FontMetrics fontMetrics = graphics.getFontMetrics(graphics.getFont());
- assertEquals(7, fontMetrics.charWidth('X'));
- assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", fontMetrics.getFont().toString());
- }
-
- @Test
- void testSetFont() {
- Font f = new Font("Helvetica", 0, 12);
- graphics.setFont(f);
- assertEquals(f, graphics.getFont());
- }
-
- @Test
- void testSetColor() {
- graphics.setColor(Color.red);
- assertEquals(Color.red, graphics.getColor());
- }
-
- @Test
- void testFillRect() {
- graphics.fillRect( 10, 10, 20, 20 );
- HSSFSimpleShape s = (HSSFSimpleShape) escherGroupA.getChildren().get(0);
- assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, s.getShapeType());
- assertEquals(10, s.getAnchor().getDx1());
- assertEquals(10, s.getAnchor().getDy1());
- assertEquals(30, s.getAnchor().getDy2());
- assertEquals(30, s.getAnchor().getDx2());
- }
-
- @Test
- void testDrawString() {
- graphics.drawString("This is a test", 10, 10);
- HSSFTextbox t = (HSSFTextbox) escherGroupA.getChildren().get(0);
- assertEquals("This is a test", t.getString().getString());
- }
-
- @Test
- void testGetDataBackAgain() throws Exception {
- HSSFSheet s;
- HSSFShapeGroup s1;
- HSSFShapeGroup s2;
-
- patriarch.setCoordinates(10, 20, 30, 40);
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- workbook.write(baos);
- workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray()));
- s = workbook.getSheetAt(0);
-
- patriarch = s.getDrawingPatriarch();
-
- assertNotNull(patriarch);
- assertEquals(10, patriarch.getX1());
- assertEquals(20, patriarch.getY1());
- assertEquals(30, patriarch.getX2());
- assertEquals(40, patriarch.getY2());
-
- // Check the two groups too
- assertEquals(2, patriarch.countOfAllChildren());
- assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup);
- assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup);
-
- s1 = (HSSFShapeGroup)patriarch.getChildren().get(0);
- s2 = (HSSFShapeGroup)patriarch.getChildren().get(1);
-
- assertEquals(0, s1.getX1());
- assertEquals(0, s1.getY1());
- assertEquals(1023, s1.getX2());
- assertEquals(255, s1.getY2());
- assertEquals(0, s2.getX1());
- assertEquals(0, s2.getY1());
- assertEquals(1023, s2.getX2());
- assertEquals(255, s2.getY2());
-
- assertEquals(0, s1.getAnchor().getDx1());
- assertEquals(0, s1.getAnchor().getDy1());
- assertEquals(1022, s1.getAnchor().getDx2());
- assertEquals(255, s1.getAnchor().getDy2());
- assertEquals(20, s2.getAnchor().getDx1());
- assertEquals(30, s2.getAnchor().getDy1());
- assertEquals(500, s2.getAnchor().getDx2());
- assertEquals(200, s2.getAnchor().getDy2());
-
-
- // Write and re-load once more, to check that's ok
- baos = new ByteArrayOutputStream();
- workbook.write(baos);
- workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray()));
- s = workbook.getSheetAt(0);
- patriarch = s.getDrawingPatriarch();
-
- assertNotNull(patriarch);
- assertEquals(10, patriarch.getX1());
- assertEquals(20, patriarch.getY1());
- assertEquals(30, patriarch.getX2());
- assertEquals(40, patriarch.getY2());
-
- // Check the two groups too
- assertEquals(2, patriarch.countOfAllChildren());
- assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup);
- assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup);
-
- s1 = (HSSFShapeGroup)patriarch.getChildren().get(0);
- s2 = (HSSFShapeGroup)patriarch.getChildren().get(1);
-
- assertEquals(0, s1.getX1());
- assertEquals(0, s1.getY1());
- assertEquals(1023, s1.getX2());
- assertEquals(255, s1.getY2());
- assertEquals(0, s2.getX1());
- assertEquals(0, s2.getY1());
- assertEquals(1023, s2.getX2());
- assertEquals(255, s2.getY2());
-
- assertEquals(0, s1.getAnchor().getDx1());
- assertEquals(0, s1.getAnchor().getDy1());
- assertEquals(1022, s1.getAnchor().getDx2());
- assertEquals(255, s1.getAnchor().getDy2());
- assertEquals(20, s2.getAnchor().getDx1());
- assertEquals(30, s2.getAnchor().getDy1());
- assertEquals(500, s2.getAnchor().getDx2());
- assertEquals(200, s2.getAnchor().getDy2());
-
- // Change the positions of the first groups,
- // but not of their anchors
- s1.setCoordinates(2, 3, 1021, 242);
-
- baos = new ByteArrayOutputStream();
- workbook.write(baos);
- workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray()));
- s = workbook.getSheetAt(0);
- patriarch = s.getDrawingPatriarch();
-
- assertNotNull(patriarch);
- assertEquals(10, patriarch.getX1());
- assertEquals(20, patriarch.getY1());
- assertEquals(30, patriarch.getX2());
- assertEquals(40, patriarch.getY2());
-
- // Check the two groups too
- assertEquals(2, patriarch.countOfAllChildren());
- assertEquals(2, patriarch.getChildren().size());
- assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup);
- assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup);
-
- s1 = (HSSFShapeGroup)patriarch.getChildren().get(0);
- s2 = (HSSFShapeGroup)patriarch.getChildren().get(1);
-
- assertEquals(2, s1.getX1());
- assertEquals(3, s1.getY1());
- assertEquals(1021, s1.getX2());
- assertEquals(242, s1.getY2());
- assertEquals(0, s2.getX1());
- assertEquals(0, s2.getY1());
- assertEquals(1023, s2.getX2());
- assertEquals(255, s2.getY2());
-
- assertEquals(0, s1.getAnchor().getDx1());
- assertEquals(0, s1.getAnchor().getDy1());
- assertEquals(1022, s1.getAnchor().getDx2());
- assertEquals(255, s1.getAnchor().getDy2());
- assertEquals(20, s2.getAnchor().getDx1());
- assertEquals(30, s2.getAnchor().getDy1());
- assertEquals(500, s2.getAnchor().getDx2());
- assertEquals(200, s2.getAnchor().getDy2());
-
-
- // Now add some text to one group, and some more
- // to the base, and check we can get it back again
- HSSFTextbox tbox1 =
- patriarch.createTextbox(new HSSFClientAnchor(1,2,3,4, (short)0,0,(short)0,0));
- tbox1.setString(new HSSFRichTextString("I am text box 1"));
- HSSFTextbox tbox2 =
- s2.createTextbox(new HSSFChildAnchor(41,42,43,44));
- tbox2.setString(new HSSFRichTextString("This is text box 2"));
-
- assertEquals(3, patriarch.getChildren().size());
-
-
- baos = new ByteArrayOutputStream();
- workbook.write(baos);
- workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray()));
- s = workbook.getSheetAt(0);
-
- patriarch = s.getDrawingPatriarch();
-
- assertNotNull(patriarch);
- assertEquals(10, patriarch.getX1());
- assertEquals(20, patriarch.getY1());
- assertEquals(30, patriarch.getX2());
- assertEquals(40, patriarch.getY2());
-
- // Check the two groups and the text
- // Result of patriarch.countOfAllChildren() makes no sense:
- // Returns 4 for 2 empty groups + 1 TextBox.
- //assertEquals(3, patriarch.countOfAllChildren());
- assertEquals(3, patriarch.getChildren().size());
-
- // Should be two groups and a text
- assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup);
- assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup);
- assertTrue(patriarch.getChildren().get(2) instanceof HSSFTextbox);
-
- s1 = (HSSFShapeGroup)patriarch.getChildren().get(0);
- tbox1 = (HSSFTextbox)patriarch.getChildren().get(2);
-
- s2 = (HSSFShapeGroup)patriarch.getChildren().get(1);
-
- assertEquals(2, s1.getX1());
- assertEquals(3, s1.getY1());
- assertEquals(1021, s1.getX2());
- assertEquals(242, s1.getY2());
- assertEquals(0, s2.getX1());
- assertEquals(0, s2.getY1());
- assertEquals(1023, s2.getX2());
- assertEquals(255, s2.getY2());
-
- assertEquals(0, s1.getAnchor().getDx1());
- assertEquals(0, s1.getAnchor().getDy1());
- assertEquals(1022, s1.getAnchor().getDx2());
- assertEquals(255, s1.getAnchor().getDy2());
- assertEquals(20, s2.getAnchor().getDx1());
- assertEquals(30, s2.getAnchor().getDy1());
- assertEquals(500, s2.getAnchor().getDx2());
- assertEquals(200, s2.getAnchor().getDy2());
-
- // Not working just yet
- assertEquals("I am text box 1", tbox1.getString().getString());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java
deleted file mode 100644
index e6aaf092b6..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-import java.awt.Color;
-import java.awt.Font;
-import java.awt.FontMetrics;
-import java.awt.geom.Line2D;
-import java.io.IOException;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the Graphics2d drawing capability.
- */
-final class TestEscherGraphics2d {
- private HSSFWorkbook workbook;
- private HSSFShapeGroup escherGroup;
- private EscherGraphics2d graphics;
-
- @BeforeEach
- void setUp() {
- workbook = new HSSFWorkbook();
- HSSFSheet sheet = workbook.createSheet("test");
- escherGroup = sheet.createDrawingPatriarch().createGroup(new HSSFClientAnchor(0,0,1023,255,(short)0,0,(short) 0,0));
- escherGroup = new HSSFShapeGroup(null, new HSSFChildAnchor());
- EscherGraphics g = new EscherGraphics(escherGroup, workbook, Color.black, 1.0f);
- graphics = new EscherGraphics2d(g);
- }
-
- @AfterEach
- void closeResources() throws IOException {
- workbook.close();
- }
-
- @Test
- void testDrawString() {
- graphics.drawString("This is a test", 10, 10);
- HSSFTextbox t = (HSSFTextbox) escherGroup.getChildren().get(0);
- assertEquals("This is a test", t.getString().getString());
-
- // Check that with a valid font, it's still ok
- Font font = new Font("Forte", Font.PLAIN, 12);
- graphics.setFont(font);
- graphics.drawString("This is another test", 10, 10);
-
- // And test with ones that need the style appending
- font = new Font("dialog", Font.PLAIN, 12);
- graphics.setFont(font);
- graphics.drawString("This is another test", 10, 10);
-
- font = new Font("dialog", Font.BOLD, 12);
- graphics.setFont(font);
- graphics.drawString("This is another test", 10, 10);
-
- // But with an invalid font, we get an exception
- font = new Font("IamAmadeUPfont", Font.PLAIN, 22);
- graphics.setFont(font);
- assertThrows(IllegalArgumentException.class, () -> graphics.drawString("This is another test", 10, 10));
- }
-
- @Test
- void testFillRect() {
- graphics.fillRect( 10, 10, 20, 20 );
- HSSFSimpleShape s = (HSSFSimpleShape) escherGroup.getChildren().get(0);
- assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, s.getShapeType());
- assertEquals(10, s.getAnchor().getDx1());
- assertEquals(10, s.getAnchor().getDy1());
- assertEquals(30, s.getAnchor().getDy2());
- assertEquals(30, s.getAnchor().getDx2());
- }
-
- @Test
- void testGetFontMetrics() {
- FontMetrics fontMetrics = graphics.getFontMetrics(graphics.getFont());
- if (isDialogPresent()) {
- // if dialog is returned we can't run the test properly.
- return;
- }
- assertEquals(7, fontMetrics.charWidth('X'));
- assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", fontMetrics.getFont().toString());
- }
-
- @Test
- void testSetFont() {
- Font f = new Font("Helvetica", Font.PLAIN, 12);
- graphics.setFont(f);
- assertEquals(f, graphics.getFont());
- }
-
- @Test
- void testSetColor() {
- graphics.setColor(Color.red);
- assertEquals(Color.red, graphics.getColor());
- }
-
- @Test
- void testGetFont() {
- Font f = graphics.getFont();
- if (isDialogPresent()) {
- // if dialog is returned we can't run the test properly.
- return;
- }
-
- assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", f.toString());
- }
-
- private boolean isDialogPresent() {
- String fontDebugStr = graphics.getFont().toString();
- return fontDebugStr.contains("dialog") || fontDebugStr.contains("Dialog");
- }
-
- @Test
- void testDraw() {
- graphics.draw(new Line2D.Double(10,10,20,20));
- HSSFSimpleShape s = (HSSFSimpleShape) escherGroup.getChildren().get(0);
- assertEquals(s.getShapeType(), HSSFSimpleShape.OBJECT_TYPE_LINE);
- assertEquals(10, s.getAnchor().getDx1());
- assertEquals(10, s.getAnchor().getDy1());
- assertEquals(20, s.getAnchor().getDx2());
- assertEquals(20, s.getAnchor().getDy2());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java b/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java
deleted file mode 100644
index 2d8ff7e834..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.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.hssf.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.hssf.HSSFTestDataSamples;
-import org.apache.poi.ss.usermodel.CellType;
-import org.junit.jupiter.api.Test;
-
-class TestExternalReferenceChange {
-
- private static final String MAIN_WORKBOOK_FILENAME = "52575_main.xls";
- private static final String SOURCE_DUMMY_WORKBOOK_FILENAME = "source_dummy.xls";
- private static final String SOURCE_WORKBOOK_FILENAME = "52575_source.xls";
-
- @Test
- void testDummyToSource() throws IOException {
- try (HSSFWorkbook mainWorkbook = HSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME);
- HSSFWorkbook sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME)) {
-
- assertNotNull(mainWorkbook);
- assertNotNull(sourceWorkbook);
-
- boolean changed = mainWorkbook.changeExternalReference("DOESNOTEXIST", SOURCE_WORKBOOK_FILENAME);
- assertFalse(changed);
-
- changed = mainWorkbook.changeExternalReference(SOURCE_DUMMY_WORKBOOK_FILENAME, SOURCE_WORKBOOK_FILENAME);
- assertTrue(changed);
-
- HSSFSheet lSheet = mainWorkbook.getSheetAt(0);
- HSSFCell lA1Cell = lSheet.getRow(0).getCell(0);
-
- assertEquals(CellType.FORMULA, lA1Cell.getCellType());
-
- HSSFFormulaEvaluator lMainWorkbookEvaluator = new HSSFFormulaEvaluator(mainWorkbook);
- HSSFFormulaEvaluator lSourceEvaluator = new HSSFFormulaEvaluator(sourceWorkbook);
- HSSFFormulaEvaluator.setupEnvironment(
- new String[]{MAIN_WORKBOOK_FILENAME, SOURCE_WORKBOOK_FILENAME},
- new HSSFFormulaEvaluator[]{lMainWorkbookEvaluator, lSourceEvaluator});
-
- assertEquals(CellType.NUMERIC, lMainWorkbookEvaluator.evaluateFormulaCell(lA1Cell));
-
- assertEquals(20.0d, lA1Cell.getNumericCellValue(), 0.00001d);
- }
- }
-
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java
deleted file mode 100644
index 7341a43b1f..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.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.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.util.Properties;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the implementation of the FontDetails class.
- */
-final class TestFontDetails {
- private FontDetails fontDetails;
-
- @BeforeEach
- void setUp() {
- Properties properties = new Properties();
- properties.setProperty("font.Arial.height", "13");
- properties.setProperty("font.Arial.characters", "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ");
- properties.setProperty("font.Arial.widths", "6, 6, 6, 6, 6, 3, 6, 6, 3, 4, 6, 3, 9, 6, 6, 6, 6, 4, 6, 3, 6, 7, 9, 6, 5, 5, 7, 7, 7, 7, 7, 6, 8, 7, 3, 6, 7, 6, 9, 7, 8, 7, 8, 7, 7, 5, 7, 7, 9, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, ");
- fontDetails = FontDetails.create("Arial", properties);
- }
-
- @Test
- void testCreate() {
- assertEquals(13, fontDetails.getHeight());
- assertEquals(6, fontDetails.getCharWidth('a'));
- assertEquals(3, fontDetails.getCharWidth('f'));
- }
-
- @Test
- void testGetStringWidth() {
- assertEquals(9, fontDetails.getStringWidth("af"));
- }
-
- @Test
- void testGetCharWidth() {
- assertEquals(6, fontDetails.getCharWidth('a'));
- assertEquals(9, fontDetails.getCharWidth('='));
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java
deleted file mode 100644
index 0ddc016d29..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java
+++ /dev/null
@@ -1,578 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook;
-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.io.File;
-import java.io.FileOutputStream;
-import java.util.Calendar;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.FormulaRecord;
-import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
-import org.apache.poi.ss.formula.EvaluationCell;
-import org.apache.poi.ss.formula.EvaluationListener;
-import org.apache.poi.ss.formula.WorkbookEvaluator;
-import org.apache.poi.ss.formula.WorkbookEvaluatorTestHelper;
-import org.apache.poi.ss.formula.eval.ErrorEval;
-import org.apache.poi.ss.formula.eval.ValueEval;
-import org.apache.poi.ss.formula.ptg.AreaPtg;
-import org.apache.poi.ss.formula.ptg.FuncPtg;
-import org.apache.poi.ss.formula.ptg.FuncVarPtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.formula.ptg.RefPtg;
-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.util.CellReference;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-
-/**
- *
- */
-final class TestFormulaEvaluatorBugs {
- private static boolean OUTPUT_TEST_FILES;
- private static String tmpDirName;
-
- @BeforeAll
- public static void setUp() {
- tmpDirName = System.getProperty("java.io.tmpdir");
- OUTPUT_TEST_FILES = Boolean.parseBoolean(
- System.getProperty("org.apache.poi.test.output_test_files", "False"));
- }
-
- /**
- * An odd problem with evaluateFormulaCell giving the
- * right values when file is opened, but changes
- * to the source data in some versions of excel
- * doesn't cause them to be updated. However, other
- * versions of excel, and gnumeric, work just fine
- * WARNING - tedious bug where you actually have to
- * open up excel
- */
- @Test
- void test44636() throws Exception {
- // Open the existing file, tweak one value and
- // re-calculate
-
- HSSFWorkbook wb = openSampleWorkbook("44636.xls");
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFRow row = sheet.getRow(0);
-
- row.getCell(0).setCellValue(4.2);
- row.getCell(2).setCellValue(25);
-
- HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
- assertEquals(4.2 * 25, row.getCell(3).getNumericCellValue(), 0.0001);
-
- if (OUTPUT_TEST_FILES) {
- // Save
- File existing = new File(tmpDirName, "44636-existing.xls");
- FileOutputStream out = new FileOutputStream(existing);
- wb.write(out);
- out.close();
- System.err.println("Existing file for bug #44636 written to " + existing);
- }
- wb.close();
-
- // Now, do a new file from scratch
- wb = new HSSFWorkbook();
- sheet = wb.createSheet();
-
- row = sheet.createRow(0);
- row.createCell(0).setCellValue(1.2);
- row.createCell(1).setCellValue(4.2);
-
- row = sheet.createRow(1);
- row.createCell(0).setCellFormula("SUM(A1:B1)");
-
- HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
- assertEquals(5.4, row.getCell(0).getNumericCellValue(), 0.0001);
-
- if (OUTPUT_TEST_FILES) {
- // Save
- File scratch = new File(tmpDirName, "44636-scratch.xls");
- FileOutputStream out = new FileOutputStream(scratch);
- wb.write(out);
- out.close();
- System.err.println("New file for bug #44636 written to " + scratch);
- }
- wb.close();
- }
-
- /**
- * Bug 44297: 32767+32768 is evaluated to -1
- * Fix: IntPtg must operate with unsigned short. Reading signed short results in incorrect formula calculation
- * if a formula has values in the interval [Short.MAX_VALUE, (Short.MAX_VALUE+1)*2]
- */
- @Test
- void test44297() throws Exception {
-
- HSSFWorkbook wb = openSampleWorkbook("44297.xls");
-
- HSSFRow row;
- HSSFCell cell;
-
- HSSFSheet sheet = wb.getSheetAt(0);
-
- HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(wb);
-
- row = sheet.getRow(0);
- cell = row.getCell(0);
- assertEquals("31+46", cell.getCellFormula());
- assertEquals(77, eva.evaluate(cell).getNumberValue(), 0);
-
- row = sheet.getRow(1);
- cell = row.getCell(0);
- assertEquals("30+53", cell.getCellFormula());
- assertEquals(83, eva.evaluate(cell).getNumberValue(), 0);
-
- row = sheet.getRow(2);
- cell = row.getCell(0);
- assertEquals("SUM(A1:A2)", cell.getCellFormula());
- assertEquals(160, eva.evaluate(cell).getNumberValue(), 0);
-
- row = sheet.getRow(4);
- cell = row.getCell(0);
- assertEquals("32767+32768", cell.getCellFormula());
- assertEquals(65535, eva.evaluate(cell).getNumberValue(), 0);
-
- row = sheet.getRow(7);
- cell = row.getCell(0);
- assertEquals("32744+42333", cell.getCellFormula());
- assertEquals(75077, eva.evaluate(cell).getNumberValue(), 0);
-
- row = sheet.getRow(8);
- cell = row.getCell(0);
- assertEquals("327680/32768", cell.getCellFormula());
- assertEquals(10, eva.evaluate(cell).getNumberValue(), 0);
-
- row = sheet.getRow(9);
- cell = row.getCell(0);
- assertEquals("32767+32769", cell.getCellFormula());
- assertEquals(65536, eva.evaluate(cell).getNumberValue(), 0);
-
- row = sheet.getRow(10);
- cell = row.getCell(0);
- assertEquals("35000+36000", cell.getCellFormula());
- assertEquals(71000, eva.evaluate(cell).getNumberValue(), 0);
-
- row = sheet.getRow(11);
- cell = row.getCell(0);
- assertEquals("-1000000-3000000", cell.getCellFormula());
- assertEquals(-4000000, eva.evaluate(cell).getNumberValue(), 0);
-
- wb.close();
- }
-
- /**
- * Bug 44410: SUM(C:C) is valid in excel, and means a sum
- * of all the rows in Column C
- */
- @Test
- void test44410() throws Exception {
- HSSFWorkbook wb = openSampleWorkbook("SingleLetterRanges.xls");
-
- HSSFSheet sheet = wb.getSheetAt(0);
-
- HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(wb);
-
- // =index(C:C,2,1) -> 2
- HSSFRow rowIDX = sheet.getRow(3);
- // =sum(C:C) -> 6
- HSSFRow rowSUM = sheet.getRow(4);
- // =sum(C:D) -> 66
- HSSFRow rowSUM2D = sheet.getRow(5);
-
- // Test the sum
- HSSFCell cellSUM = rowSUM.getCell(0);
-
- FormulaRecordAggregate frec = (FormulaRecordAggregate) cellSUM.getCellValueRecord();
- Ptg[] ops = frec.getFormulaRecord().getParsedExpression();
- assertEquals(2, ops.length);
- assertEquals(AreaPtg.class, ops[0].getClass());
- assertEquals(FuncVarPtg.class, ops[1].getClass());
-
- // Actually stored as C1 to C65536
- // (last row is -1 === 65535)
- AreaPtg ptg = (AreaPtg) ops[0];
- assertEquals(2, ptg.getFirstColumn());
- assertEquals(2, ptg.getLastColumn());
- assertEquals(0, ptg.getFirstRow());
- assertEquals(65535, ptg.getLastRow());
- assertEquals("C:C", ptg.toFormulaString());
-
- // Will show as C:C, but won't know how many
- // rows it covers as we don't have the sheet
- // to hand when turning the Ptgs into a string
- assertEquals("SUM(C:C)", cellSUM.getCellFormula());
-
- // But the evaluator knows the sheet, so it
- // can do it properly
- assertEquals(6, eva.evaluate(cellSUM).getNumberValue(), 0);
-
- // Test the index
- // Again, the formula string will be right but
- // lacking row count, evaluated will be right
- HSSFCell cellIDX = rowIDX.getCell(0);
- assertEquals("INDEX(C:C,2,1)", cellIDX.getCellFormula());
- assertEquals(2, eva.evaluate(cellIDX).getNumberValue(), 0);
-
- // Across two colums
- HSSFCell cellSUM2D = rowSUM2D.getCell(0);
- assertEquals("SUM(C:D)", cellSUM2D.getCellFormula());
- assertEquals(66, eva.evaluate(cellSUM2D).getNumberValue(), 0);
-
- wb.close();
- }
-
- /**
- * Tests that we can evaluate boolean cells properly
- */
- @Test
- void testEvaluateBooleanInCell_bug44508() throws Exception {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet();
- wb.setSheetName(0, "Sheet1");
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell = row.createCell(0);
-
- cell.setCellFormula("1=1");
-
- HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
- try {
- fe.evaluateInCell(cell);
- } catch (NumberFormatException e) {
- fail("Identified bug 44508");
- }
- assertTrue(cell.getBooleanCellValue());
-
- wb.close();
- }
-
- @Test
- void testClassCast_bug44861() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("44861.xls")) {
- // Check direct
- HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
-
- // And via calls
- for (Sheet s : wb) {
- HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb);
-
- for (Row r : s) {
- for (Cell c : r) {
- CellType ct = eval.evaluateFormulaCell(c);
- assertNotNull(ct);
- }
- }
- }
-
- }
- }
-
- @Test
- void testEvaluateInCellWithErrorCode_bug44950() throws Exception {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet("Sheet1");
- HSSFRow row = sheet.createRow(1);
- HSSFCell cell = row.createCell(0);
- cell.setCellFormula("na()"); // this formula evaluates to an Excel error code '#N/A'
- HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
- fe.evaluateInCell(cell);
- } catch (NumberFormatException e) {
- if (e.getMessage().equals("You cannot get an error value from a non-error cell")) {
- fail("Identified bug 44950 b");
- }
- throw e;
- }
- }
-
- @Test
- void testDateWithNegativeParts_bug48528() throws Exception {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet("Sheet1");
- HSSFRow row = sheet.createRow(1);
- HSSFCell cell = row.createCell(0);
- HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
-
- // 5th Feb 2012 = 40944
- // 1st Feb 2012 = 40940
- // 5th Jan 2012 = 40913
- // 5th Dec 2011 = 40882
- // 5th Feb 2011 = 40579
-
- cell.setCellFormula("DATE(2012,2,1)");
- fe.notifyUpdateCell(cell);
- assertEquals(40940.0, fe.evaluate(cell).getNumberValue(), 0);
-
- cell.setCellFormula("DATE(2012,2,1+4)");
- fe.notifyUpdateCell(cell);
- assertEquals(40944.0, fe.evaluate(cell).getNumberValue(), 0);
-
- cell.setCellFormula("DATE(2012,2-1,1+4)");
- fe.notifyUpdateCell(cell);
- assertEquals(40913.0, fe.evaluate(cell).getNumberValue(), 0);
-
- cell.setCellFormula("DATE(2012,2,1-27)");
- fe.notifyUpdateCell(cell);
- assertEquals(40913.0, fe.evaluate(cell).getNumberValue(), 0);
-
- cell.setCellFormula("DATE(2012,2-2,1+4)");
- fe.notifyUpdateCell(cell);
- assertEquals(40882.0, fe.evaluate(cell).getNumberValue(), 0);
-
- cell.setCellFormula("DATE(2012,2,1-58)");
- fe.notifyUpdateCell(cell);
- assertEquals(40882.0, fe.evaluate(cell).getNumberValue(), 0);
-
- cell.setCellFormula("DATE(2012,2-12,1+4)");
- fe.notifyUpdateCell(cell);
- assertEquals(40579.0, fe.evaluate(cell).getNumberValue(), 0);
-
- wb.close();
- }
-
- private static final class EvalListener extends EvaluationListener {
- private int _countCacheHits;
- private int _countCacheMisses;
-
- public EvalListener() {
- _countCacheHits = 0;
- _countCacheMisses = 0;
- }
- public int getCountCacheHits() {
- return _countCacheHits;
- }
- public int getCountCacheMisses() {
- return _countCacheMisses;
- }
-
- @Override
- public void onCacheHit(int sheetIndex, int srcRowNum, int srcColNum, ValueEval result) {
- _countCacheHits++;
- }
- @Override
- public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) {
- _countCacheMisses++;
- }
- }
-
- /**
- * The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values
- */
- @Test
- void testSlowEvaluate45376() throws Exception {
- /*
- * Note - to observe behaviour without caching, disable the call to
- * updateValue() from FormulaCellCacheEntry.updateFormulaResult().
- */
-
- // Firstly set up a sequence of formula cells where each depends on the previous multiple
- // times. Without caching, each subsequent cell take about 4 times longer to evaluate.
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet("Sheet1");
- HSSFRow row = sheet.createRow(0);
- for(int i=1; i<10; i++) {
- HSSFCell cell = row.createCell(i);
- char prevCol = (char) ('A' + i-1);
- String prevCell = prevCol + "1";
- // this formula is inspired by the offending formula of the attachment for bug 45376
- // IF(DATE(YEAR(A1),MONTH(A1)+1,1)<=$D$3,DATE(YEAR(A1),MONTH(A1)+1,1),NA()) etc
- String formula = "IF(DATE(YEAR(" + prevCell + "),MONTH(" + prevCell + ")+1,1)<=$D$3," +
- "DATE(YEAR(" + prevCell + "),MONTH(" + prevCell + ")+1,1),NA())";
- cell.setCellFormula(formula);
- }
- Calendar cal = LocaleUtil.getLocaleCalendar(2000, 0, 1, 0, 0, 0);
- row.createCell(0).setCellValue(cal);
-
- // Choose cell A9 instead of A10, so that the failing test case doesn't take too long to execute.
- HSSFCell cell = row.getCell(8);
- EvalListener evalListener = new EvalListener();
- WorkbookEvaluator evaluator = WorkbookEvaluatorTestHelper.createEvaluator(wb, evalListener);
- ValueEval ve = evaluator.evaluate(HSSFEvaluationTestHelper.wrapCell(cell));
- int evalCount = evalListener.getCountCacheMisses();
- // Without caching, evaluating cell 'A9' takes 21845 evaluations which consumes
- // much time (~3 sec on Core 2 Duo 2.2GHz)
- // short-circuit-if optimisation cuts this down to 255 evaluations which is still too high
- // System.err.println("Cell A9 took " + evalCount + " intermediate evaluations");
- assertTrue(evalCount <= 10, "Identifed bug 45376 - Formula evaluator should cache values");
- // With caching, the evaluationCount is 8 which is exactly the
- // number of formula cells that needed to be evaluated.
- assertEquals(8, evalCount);
-
- // The cache hits would be 24 if fully evaluating all arguments of the
- // "IF()" functions (Each of the 8 formulas has 4 refs to formula cells
- // which result in 1 cache miss and 3 cache hits). However with the
- // short-circuit-if optimisation, 2 of the cell refs get skipped
- // reducing this metric 8.
- assertEquals(8, evalListener.getCountCacheHits());
-
- // confirm the evaluation result too
- assertEquals(ErrorEval.NA, ve);
-
- wb.close();
- }
-
- @SuppressWarnings("resource")
- @Test
- void test55747_55324() throws Exception {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFFormulaEvaluator ev = wb.getCreationHelper().createFormulaEvaluator();
- HSSFSheet ws = wb.createSheet();
- HSSFRow row = ws.createRow(0);
- HSSFCell cell;
-
- // Our test value
- cell = row.createCell(0);
- cell.setCellValue("abc");
-
- // Lots of IF cases
-
- cell = row.createCell(1);
- cell.setCellFormula("IF(A1<>\"\",MID(A1,1,2),\"X\")");//if(expr,func,val)
-
- cell = row.createCell(2);
- cell.setCellFormula("IF(A1<>\"\",\"A\",\"B\")");// if(expr,val,val)
-
- cell = row.createCell(3);
- cell.setCellFormula("IF(A1=\"\",\"X\",MID(A1,1,2))");//if(expr,val,func),
-
- cell = row.createCell(4);
- cell.setCellFormula("IF(A1<>\"\",\"X\",MID(A1,1,2))");//if(expr,val,func),
-
- cell = row.createCell(5);
- cell.setCellFormula("IF(A1=\"\",MID(A1,1,2),MID(A1,2,2))");//if(exp,func,func)
- cell = row.createCell(6);
- cell.setCellFormula("IF(A1<>\"\",MID(A1,1,2),MID(A1,2,2))");//if(exp,func,func)
-
- cell = row.createCell(7);
- cell.setCellFormula("IF(MID(A1,1,2)<>\"\",\"A\",\"B\")");//if(func_expr,val,val)
-
- // And some MID ones just to check
- row = ws.createRow(1);
- cell = row.createCell(1);
- cell.setCellFormula("MID(A1,1,2)");
- cell = row.createCell(2);
- cell.setCellFormula("MID(A1,2,2)");
- cell = row.createCell(3);
- cell.setCellFormula("MID(A1,2,1)");
- cell = row.createCell(4);
- cell.setCellFormula("MID(A1,3,1)");
-
- // Evaluate
- ev.evaluateAll();
-
- // Save and re-load
- wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
- ws = wb.getSheetAt(0);
-
- // Check the MID Ptgs in Row 2 have V RefPtgs for A1
- row = ws.getRow(1);
- for (int i=1; i<=4; i++) {
- cell = row.getCell(i);
- Ptg[] ptgs = getPtgs(cell);
- assertEquals(4, ptgs.length);
- assertEquals(FuncPtg.class, ptgs[3].getClass());
- assertEquals("MID", ((FuncPtg)ptgs[3]).getName());
- assertRefPtgA1('V', ptgs, 0);
- }
-
- // Now check the IF formulas
- row = ws.getRow(0);
-
- // H1, MID is used in the expression IF checks, so A1 should be V
- cell = row.getCell(CellReference.convertColStringToIndex("H"));
- assertRefPtgA1('V', getPtgs(cell), 0);
-
- // E1, MID is used in the FALSE route, so:
- // A1 should be V in the IF check
- // A1 should be R in the FALSE route
- cell = row.getCell(CellReference.convertColStringToIndex("E"));
- assertRefPtgA1('V', getPtgs(cell), 0);
- assertRefPtgA1('R', getPtgs(cell), 6);
-
- // Check that, for B1, D1, F1 and G1, the references to A1
- // from all of IF check, True and False are V
- cell = row.getCell(CellReference.convertColStringToIndex("B"));
- assertRefPtgA1('V', getPtgs(cell), 0);
-// assertRefPtgA1('V', getPtgs(cell), 4); // FIXME!
-
- cell = row.getCell(CellReference.convertColStringToIndex("D"));
- assertRefPtgA1('V', getPtgs(cell), 0);
-// assertRefPtgA1('V', getPtgs(cell), 6); // FIXME!
-
- cell = row.getCell(CellReference.convertColStringToIndex("F"));
- assertRefPtgA1('V', getPtgs(cell), 0);
-// assertRefPtgA1('V', getPtgs(cell), 4); // FIXME!
-// assertRefPtgA1('V', getPtgs(cell), 9); // FIXME!
-
- cell = row.getCell(CellReference.convertColStringToIndex("G"));
- assertRefPtgA1('V', getPtgs(cell), 0);
-// assertRefPtgA1('V', getPtgs(cell), 4); // FIXME!
-// assertRefPtgA1('V', getPtgs(cell), 9); // FIXME!
-
-
- // Check our cached values were correctly evaluated
- cell = row.getCell(CellReference.convertColStringToIndex("A"));
- assertEquals("abc", cell.getStringCellValue());
- cell = row.getCell(CellReference.convertColStringToIndex("B"));
- assertEquals("ab", cell.getStringCellValue());
- cell = row.getCell(CellReference.convertColStringToIndex("C"));
- assertEquals("A", cell.getStringCellValue());
- cell = row.getCell(CellReference.convertColStringToIndex("D"));
- assertEquals("ab", cell.getStringCellValue());
- cell = row.getCell(CellReference.convertColStringToIndex("E"));
- assertEquals("X", cell.getStringCellValue());
- cell = row.getCell(CellReference.convertColStringToIndex("F"));
- assertEquals("bc", cell.getStringCellValue());
- cell = row.getCell(CellReference.convertColStringToIndex("G"));
- assertEquals("ab", cell.getStringCellValue());
- cell = row.getCell(CellReference.convertColStringToIndex("H"));
- assertEquals("A", cell.getStringCellValue());
-
- // Enable this to write out + check in Excel
- if (OUTPUT_TEST_FILES) {
- FileOutputStream out = new FileOutputStream("/tmp/test.xls");
- wb.write(out);
- out.close();
- }
- }
- private Ptg[] getPtgs(HSSFCell cell) {
- assertEquals(CellType.FORMULA, cell.getCellType());
- assertEquals(FormulaRecordAggregate.class, cell.getCellValueRecord().getClass());
- FormulaRecordAggregate agg = (FormulaRecordAggregate)cell.getCellValueRecord();
- FormulaRecord rec = agg.getFormulaRecord();
- return rec.getParsedExpression();
- }
- private void assertRefPtgA1(char rv, Ptg[] ptgs, int at) {
- Ptg ptg = ptgs[at];
- assertEquals(RefPtg.class, ptg.getClass());
- assertEquals(0, ((RefPtg)ptg).getRow());
- assertEquals(0, ((RefPtg)ptg).getColumn());
- assertEquals(rv, ptg.getRVAType());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java
deleted file mode 100644
index ef8cd2538a..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-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.CellType;
-import org.apache.poi.ss.usermodel.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests to show that our documentation at
- * https://poi.apache.org/hssf/eval.html
- * all actually works as we'd expect them to
- */
-final class TestFormulaEvaluatorDocs {
-
- /**
- * https://poi.apache.org/hssf/eval.html#EvaluateAll
- */
- @Test
- void testEvaluateAll() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s1 = wb.createSheet();
- HSSFSheet s2 = wb.createSheet();
- wb.setSheetName(0, "S1");
- wb.setSheetName(1, "S2");
-
- HSSFRow s1r1 = s1.createRow(0);
- HSSFRow s1r2 = s1.createRow(1);
- HSSFRow s2r1 = s2.createRow(0);
-
- HSSFCell s1r1c1 = s1r1.createCell(0);
- HSSFCell s1r1c2 = s1r1.createCell(1);
- HSSFCell s1r1c3 = s1r1.createCell(2);
- s1r1c1.setCellValue(22.3);
- s1r1c2.setCellValue(33.4);
- s1r1c3.setCellFormula("SUM(A1:B1)");
-
- HSSFCell s1r2c1 = s1r2.createCell(0);
- HSSFCell s1r2c2 = s1r2.createCell(1);
- HSSFCell s1r2c3 = s1r2.createCell(2);
- s1r2c1.setCellValue(-1.2);
- s1r2c2.setCellValue(-3.4);
- s1r2c3.setCellFormula("SUM(A2:B2)");
-
- HSSFCell s2r1c1 = s2r1.createCell(0);
- s2r1c1.setCellFormula("S1!A1");
-
- // Not evaluated yet
- assertEquals(0.0, s1r1c3.getNumericCellValue(), 0);
- assertEquals(0.0, s1r2c3.getNumericCellValue(), 0);
- assertEquals(0.0, s2r1c1.getNumericCellValue(), 0);
-
- // Do a full evaluate, as per our docs
- // uses evaluateFormulaCell()
- for (Sheet sheet : wb) {
- HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb);
- for (Row r : sheet) {
- for (Cell c : r) {
- if (c.getCellType() == CellType.FORMULA) {
- evaluator.evaluateFormulaCell(c);
-
- // For testing - all should be numeric
- assertEquals(CellType.NUMERIC, evaluator.evaluateFormulaCell(c));
- }
- }
- }
- }
-
- // Check now as expected
- assertEquals(55.7, wb.getSheetAt(0).getRow(0).getCell(2).getNumericCellValue(), 0);
- assertEquals("SUM(A1:B1)", wb.getSheetAt(0).getRow(0).getCell(2).getCellFormula());
- assertEquals(CellType.FORMULA, wb.getSheetAt(0).getRow(0).getCell(2).getCellType());
-
- assertEquals(-4.6, wb.getSheetAt(0).getRow(1).getCell(2).getNumericCellValue(), 0);
- assertEquals("SUM(A2:B2)", wb.getSheetAt(0).getRow(1).getCell(2).getCellFormula());
- assertEquals(CellType.FORMULA, wb.getSheetAt(0).getRow(1).getCell(2).getCellType());
-
- assertEquals(22.3, wb.getSheetAt(1).getRow(0).getCell(0).getNumericCellValue(), 0);
- assertEquals("'S1'!A1", wb.getSheetAt(1).getRow(0).getCell(0).getCellFormula());
- assertEquals(CellType.FORMULA, wb.getSheetAt(1).getRow(0).getCell(0).getCellType());
-
-
- // Now do the alternate call, which zaps the formulas
- // uses evaluateInCell()
- for (Sheet sheet : wb) {
- HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb);
-
- for (Row r : sheet) {
- for (Cell c : r) {
- if (c.getCellType() == CellType.FORMULA) {
- evaluator.evaluateInCell(c);
- }
- }
- }
- }
-
- assertEquals(55.7, wb.getSheetAt(0).getRow(0).getCell(2).getNumericCellValue(), 0);
- assertEquals(CellType.NUMERIC, wb.getSheetAt(0).getRow(0).getCell(2).getCellType());
-
- assertEquals(-4.6, wb.getSheetAt(0).getRow(1).getCell(2).getNumericCellValue(), 0);
- assertEquals(CellType.NUMERIC, wb.getSheetAt(0).getRow(1).getCell(2).getCellType());
-
- assertEquals(22.3, wb.getSheetAt(1).getRow(0).getCell(0).getNumericCellValue(), 0);
- assertEquals(CellType.NUMERIC, wb.getSheetAt(1).getRow(0).getCell(0).getCellType());
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java
deleted file mode 100644
index 836ed32bae..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java
+++ /dev/null
@@ -1,950 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack;
-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.assertTrue;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Calendar;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.HSSFFormulaParser;
-import org.apache.poi.ss.formula.FormulaType;
-import org.apache.poi.ss.formula.ptg.NamePtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.DateUtil;
-import org.apache.poi.ss.usermodel.Name;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.util.CellReference;
-import org.apache.poi.util.LocaleUtil;
-import org.apache.poi.util.TempFile;
-import org.junit.jupiter.api.Test;
-
-final class TestFormulas {
-
- private static HSSFWorkbook openSample(String sampleFileName) {
- return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
- }
-
- /**
- * Add 1+1 -- WHoohoo!
- */
- @Test
- void testBasicAddIntegers() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
-
- //get our minimum values
- HSSFRow r = s.createRow(1);
- HSSFCell c = r.createCell(1);
- c.setCellFormula(1 + "+" + 1);
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- s = wb2.getSheetAt(0);
- r = s.getRow(1);
- c = r.getCell(1);
-
- assertEquals("1+1", c.getCellFormula(), "Formula is as expected");
- }
- }
- }
-
- /**
- * Add various integers
- */
- @Test
- void testAddIntegers() throws IOException {
- binomialOperator("+");
- }
-
- /**
- * Multiply various integers
- */
- @Test
- void testMultplyIntegers() throws IOException {
- binomialOperator("*");
- }
-
- /**
- * Subtract various integers
- */
- @Test
- void testSubtractIntegers() throws IOException {
- binomialOperator("-");
- }
-
- /**
- * Subtract various integers
- */
- @Test
- void testDivideIntegers() throws IOException {
- binomialOperator("/");
- }
-
- /**
- * Exponentialize various integers;
- */
- @Test
- void testPowerIntegers() throws IOException {
- binomialOperator("^");
- }
-
- /**
- * Concatenate two numbers 1&2 = 12
- */
- @Test
- void testConcatIntegers() throws IOException {
- binomialOperator("&");
- }
-
- /**
- * tests 1*2+3*4
- */
- @Test
- void testOrderOfOperationsMultiply() throws IOException {
- orderTest("1*2+3*4");
- }
-
- /**
- * tests 1*2+3^4
- */
- @Test
- void testOrderOfOperationsPower() throws IOException {
- orderTest("1*2+3^4");
- }
-
- /**
- * Tests that parenthesis are obeyed
- */
- @Test
- void testParenthesis() throws IOException {
- orderTest("(1*3)+2+(1+2)*(3^4)^5");
- }
-
- @Test
- void testReferencesOpr() throws IOException {
- String[] operation = new String[] {
- "+", "-", "*", "/", "^", "&"
- };
- for (final String op : operation) {
- operationRefTest(op);
- }
- }
-
- /**
- * Tests creating a file with floating point in a formula.
- *
- */
- @Test
- void testFloat() throws IOException {
- floatTest("*");
- floatTest("/");
- }
-
- private static void floatTest(String operator) throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
-
- //get our minimum values
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(1);
- c.setCellFormula("" + Float.MIN_VALUE + operator + Float.MIN_VALUE);
-
- for (int x = 1; x < Short.MAX_VALUE && x > 0; x = (short) (x * 2)) {
- r = s.createRow(x);
-
- for (int y = 1; y < 256 && y > 0; y = (short) (y + 2)) {
- c = r.createCell(y);
- c.setCellFormula("" + x + "." + y + operator + y + "." + x);
- }
- }
- if (s.getLastRowNum() < Short.MAX_VALUE) {
- r = s.createRow(0);
- c = r.createCell(0);
- c.setCellFormula("" + Float.MAX_VALUE + operator + Float.MAX_VALUE);
- }
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- floatVerify(operator, wb2);
- }
- }
- }
-
- private static void floatVerify(String operator, HSSFWorkbook wb) {
- HSSFSheet s = wb.getSheetAt(0);
-
- // don't know how to check correct result .. for the moment, we just verify that the file can be read.
- for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) {
- HSSFRow r = s.getRow(x);
-
- for (int y = 1; y < 256 && y > 0; y=(short)(y+2)) {
-
- HSSFCell c = r.getCell(y);
- assertNotNull(c.getCellFormula(), "got a formula");
-
- assertEquals(("" + x + "." + y + operator + y + "." + x), c.getCellFormula(),
- "loop Formula is as expected " + x + "." + y + operator + y + "." + x + "!=" + c.getCellFormula());
- }
- }
- }
-
- @Test
- void testAreaSum() throws IOException {
- areaFunctionTest("SUM");
- }
-
- @Test
- void testAreaAverage() throws IOException {
- areaFunctionTest("AVERAGE");
- }
-
- @Test
- void testRefArraySum() throws IOException {
- refArrayFunctionTest("SUM");
- }
-
- @Test
- void testAreaArraySum() throws IOException {
- refAreaArrayFunctionTest("SUM");
- }
-
- private static void operationRefTest(String operator) throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
-
- //get our minimum values
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(1);
- c.setCellFormula("A2" + operator + "A3");
-
- for (int x = 1; x < Short.MAX_VALUE && x > 0; x = (short) (x * 2)) {
- r = s.createRow(x);
-
- for (int y = 1; y < 256 && y > 0; y++) {
- short refx1 = (short)(x + (x + 50 < Short.MAX_VALUE ? 50 : -4));
- short refx2 = (short)(x + (x + 50 < Short.MAX_VALUE ? 46 : -3));
- short refy1 = (short)(y + (y + 50 < 255 ? 50 : -4));
- short refy2 = (short)(y + (y + 50 < 255 ? 49 : -3));
-
- CellReference cr = new CellReference(refx1, refy1, false, false);
- String ref = cr.formatAsString();
- cr = new CellReference(refx2, refy2, false, false);
- String ref2 = cr.formatAsString();
-
- c = r.createCell(y);
- c.setCellFormula("" + ref + operator + ref2);
- }
- }
-
- //make sure we do the maximum value of the Int operator
- if (s.getLastRowNum() < Short.MAX_VALUE) {
- r = s.getRow(0);
- c = r.createCell(0);
- c.setCellFormula("" + "B1" + operator + "IV255");
- }
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- operationalRefVerify(operator, wb2);
- }
- }
- }
-
- /**
- * Opens the sheet we wrote out by binomialOperator and makes sure the formulas
- * all match what we expect (x operator y)
- */
- private static void operationalRefVerify(String operator, HSSFWorkbook wb) {
-
- HSSFSheet s = wb.getSheetAt(0);
-
- //get our minimum values
- HSSFRow r = s.getRow(0);
- HSSFCell c = r.getCell(1);
- //get our minimum values
- assertEquals(("A2" + operator + "A3"), c.getCellFormula(),
- "minval Formula is as expected A2" + operator + "A3 != " + c.getCellFormula());
-
-
- for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) {
- r = s.getRow(x);
-
- for (int y = 1; y < 256 && y > 0; y++) {
-
- int refx1 = x + (x+50 < Short.MAX_VALUE ? 50 : -4);
- int refx2 = x + (x+50 < Short.MAX_VALUE ? 46 : -3);
- int refy1 = y + (y+50 < 255 ? 50 : -4);
- int refy2 = y + (y+50 < 255 ? 49 : -3);
-
- c = r.getCell(y);
- CellReference cr= new CellReference(refx1, refy1, false, false);
- String ref=cr.formatAsString();
- cr=new CellReference(refx2,refy2, false, false);
- String ref2=cr.formatAsString();
-
-
- assertEquals(("" + ref + operator + ref2), c.getCellFormula(),
- "loop Formula is as expected " + ref + operator + ref2 + "!=" + c.getCellFormula());
- }
- }
-
- //test our maximum values
- r = s.getRow(0);
- c = r.getCell(0);
-
- assertEquals("B1"+operator+"IV255", c.getCellFormula());
- }
-
-
-
- /**
- * tests order wrting out == order writing in for a given formula
- */
- private static void orderTest(String formula) throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
-
- //get our minimum values
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(1);
- c.setCellFormula(formula);
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- s = wb2.getSheetAt(0);
-
- //get our minimum values
- r = s.getRow(0);
- c = r.getCell(1);
- assertEquals(formula, c.getCellFormula(), "minval Formula is as expected");
- }
- }
- }
-
- /**
- * All multi-binomial operator tests use this to create a worksheet with a
- * huge set of x operator y formulas. Next we call binomialVerify and verify
- * that they are all how we expect.
- */
- private static void binomialOperator(String operator) throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
-
- //get our minimum values
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(1);
- c.setCellFormula(1 + operator + 1);
-
- for (int x = 1; x < Short.MAX_VALUE && x > 0; x = (short) (x * 2)) {
- r = s.createRow(x);
-
- for (int y = 1; y < 256 && y > 0; y++) {
- c = r.createCell(y);
- c.setCellFormula("" + x + operator + y);
- }
- }
-
- //make sure we do the maximum value of the Int operator
- if (s.getLastRowNum() < Short.MAX_VALUE) {
- r = s.getRow(0);
- c = r.createCell(0);
- c.setCellFormula("" + Short.MAX_VALUE + operator + Short.MAX_VALUE);
- }
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- binomialVerify(operator, wb2);
- }
- }
- }
-
- /**
- * Opens the sheet we wrote out by binomialOperator and makes sure the formulas
- * all match what we expect (x operator y)
- */
- private static void binomialVerify(String operator, HSSFWorkbook wb) {
- HSSFSheet s = wb.getSheetAt(0);
-
- //get our minimum values
- HSSFRow r = s.getRow(0);
- HSSFCell c = r.getCell(1);
- assertEquals(("1" + operator + "1"), c.getCellFormula(),
- "minval Formula is as expected 1" + operator + "1 != " + c.getCellFormula());
-
- for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) {
- r = s.getRow(x);
-
- for (int y = 1; y < 256 && y > 0; y++) {
- c = r.getCell(y);
- assertEquals(("" + x + operator + y), c.getCellFormula(),
- "loop Formula is as expected " + x + operator + y + "!=" + c.getCellFormula());
- }
- }
-
- //test our maximum values
- r = s.getRow(0);
- c = r.getCell(0);
-
- assertEquals(("" + Short.MAX_VALUE + operator + Short.MAX_VALUE), c.getCellFormula(),
- "maxval Formula is as expected");
- }
-
- /**
- * Writes a function then tests to see if its correct
- */
- public static void areaFunctionTest(String function) throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(0);
- c.setCellFormula(function + "(A2:A3)");
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- s = wb2.getSheetAt(0);
- r = s.getRow(0);
- c = r.getCell(0);
-
- assertEquals(function + "(A2:A3)", c.getCellFormula(),
- "function =" + function + "(A2:A3)");
- }
- }
- }
-
- /**
- * Writes a function then tests to see if its correct
- */
- void refArrayFunctionTest(String function) throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
- HSSFRow r = s.createRow(0);
-
- HSSFCell c = r.createCell(0);
- c.setCellFormula(function + "(A2,A3)");
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- s = wb2.getSheetAt(0);
- r = s.getRow(0);
- c = r.getCell(0);
-
- assertEquals((function + "(A2,A3)"), c.getCellFormula(), "function =" + function + "(A2,A3)");
- }
- }
- }
-
-
- /**
- * Writes a function then tests to see if its correct
- *
- */
- void refAreaArrayFunctionTest(String function) throws IOException {
-
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(0);
- c.setCellFormula(function + "(A2:A4,B2:B4)");
- c = r.createCell(1);
- c.setCellFormula(function + "($A$2:$A4,B$2:B4)");
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- s = wb2.getSheetAt(0);
- r = s.getRow(0);
- c = r.getCell(0);
-
- assertEquals((function + "(A2:A4,B2:B4)"), c.getCellFormula(), "function =" + function + "(A2:A4,B2:B4)");
-
- c = r.getCell(1);
- assertEquals((function + "($A$2:$A4,B$2:B4)"), c.getCellFormula(), "function =" + function + "($A$2:$A4,B$2:B4)");
- }
- }
- }
-
-
- @Test
- void testAbsRefs() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(0);
- c.setCellFormula("A3+A2");
- c = r.createCell(1);
- c.setCellFormula("$A3+$A2");
- c = r.createCell(2);
- c.setCellFormula("A$3+A$2");
- c = r.createCell(3);
- c.setCellFormula("$A$3+$A$2");
- c = r.createCell(4);
- c.setCellFormula("SUM($A$3,$A$2)");
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- s = wb2.getSheetAt(0);
- r = s.getRow(0);
- c = r.getCell(0);
- assertEquals("A3+A2", c.getCellFormula());
- c = r.getCell(1);
- assertEquals("$A3+$A2", c.getCellFormula());
- c = r.getCell(2);
- assertEquals("A$3+A$2", c.getCellFormula());
- c = r.getCell(3);
- assertEquals("$A$3+$A$2", c.getCellFormula());
- c = r.getCell(4);
- assertEquals("SUM($A$3,$A$2)", c.getCellFormula());
- }
- }
- }
-
- @Test
- void testSheetFunctions() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet("A");
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(0);
- c.setCellValue(1);
- c = r.createCell(1);
- c.setCellValue(2);
-
- s = wb1.createSheet("B");
- r = s.createRow(0);
- c = r.createCell(0);
- c.setCellFormula("AVERAGE(A!A1:B1)");
- c = r.createCell(1);
- c.setCellFormula("A!A1+A!B1");
- c = r.createCell(2);
- c.setCellFormula("A!$A$1+A!$B1");
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- s = wb2.getSheet("B");
- r = s.getRow(0);
- c = r.getCell(0);
- assertEquals("AVERAGE(A!A1:B1)", c.getCellFormula(),
- "expected: AVERAGE(A!A1:B1) got: " + c.getCellFormula());
- c = r.getCell(1);
- assertEquals("A!A1+A!B1", c.getCellFormula(),
- "expected: A!A1+A!B1 got: " + c.getCellFormula());
- }
- }
- }
-
- @Test
- void testRVAoperands() throws IOException {
- File file = TempFile.createTempFile("testFormulaRVA",".xls");
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(0);
- c.setCellFormula("A3+A2");
- c = r.createCell(1);
- c.setCellFormula("AVERAGE(A3,A2)");
- c = r.createCell(2);
- c.setCellFormula("ROW(A3)");
- c = r.createCell(3);
- c.setCellFormula("AVERAGE(A2:A3)");
- c = r.createCell(4);
- c.setCellFormula("POWER(A2,A3)");
- c = r.createCell(5);
- c.setCellFormula("SIN(A2)");
-
- c = r.createCell(6);
- c.setCellFormula("SUM(A2:A3)");
-
- c = r.createCell(7);
- c.setCellFormula("SUM(A2,A3)");
-
- r = s.createRow(1);
- c = r.createCell(0);
- c.setCellValue(2.0);
- r = s.createRow(2);
- c = r.createCell(0);
- c.setCellValue(3.0);
-
- try (FileOutputStream out = new FileOutputStream(file)) {
- wb.write(out);
- }
- assertTrue(file.exists());
- }
- }
-
- @Test
- void testStringFormulas() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet("A");
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(1);
- c.setCellFormula("UPPER(\"abc\")");
- c = r.createCell(2);
- c.setCellFormula("LOWER(\"ABC\")");
- c = r.createCell(3);
- c.setCellFormula("CONCATENATE(\" my \",\" name \")");
-
- writeOutAndReadBack(wb).close();
- }
-
- try (HSSFWorkbook wb = openSample("StringFormulas.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
- HSSFRow r = s.getRow(0);
- HSSFCell c = r.getCell(0);
- assertEquals("UPPER(\"xyz\")", c.getCellFormula());
- }
- }
-
- @Test
- void testLogicalFormulas() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet("A");
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(1);
- c.setCellFormula("IF(A14000\",B1:B5)";
-
- try (HSSFWorkbook wb = openSample("sumifformula.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
- HSSFRow r = s.getRow(0);
- HSSFCell c = r.getCell(2);
- assertEquals(function, c.getCellFormula());
- }
-
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
-
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(0);
- c.setCellValue(1000);
- c = r.createCell(1);
- c.setCellValue(1);
-
- r = s.createRow(1);
- c = r.createCell(0);
- c.setCellValue(2000);
- c = r.createCell(1);
- c.setCellValue(2);
-
- r = s.createRow(2);
- c = r.createCell(0);
- c.setCellValue(3000);
- c = r.createCell(1);
- c.setCellValue(3);
-
- r = s.createRow(3);
- c = r.createCell(0);
- c.setCellValue(4000);
- c = r.createCell(1);
- c.setCellValue(4);
-
- r = s.createRow(4);
- c = r.createCell(0);
- c.setCellValue(5000);
- c = r.createCell(1);
- c.setCellValue(5);
-
- r = s.getRow(0);
- c = r.createCell(2);
- c.setCellFormula(function);
-
- writeOutAndReadBack(wb).close();
- }
- }
-
- @Test
- void testSquareMacro() throws IOException {
- try (HSSFWorkbook w = openSample("SquareMacro.xls")) {
- HSSFSheet s0 = w.getSheetAt(0);
- HSSFRow[] r = {s0.getRow(0), s0.getRow(1)};
-
- HSSFCell a1 = r[0].getCell(0);
- assertEquals("square(1)", a1.getCellFormula());
- assertEquals(1d, a1.getNumericCellValue(), 1e-9);
-
- HSSFCell a2 = r[1].getCell(0);
- assertEquals("square(2)", a2.getCellFormula());
- assertEquals(4d, a2.getNumericCellValue(), 1e-9);
-
- HSSFCell b1 = r[0].getCell(1);
- assertEquals("IF(TRUE,square(1))", b1.getCellFormula());
- assertEquals(1d, b1.getNumericCellValue(), 1e-9);
-
- HSSFCell b2 = r[1].getCell(1);
- assertEquals("IF(TRUE,square(2))", b2.getCellFormula());
- assertEquals(4d, b2.getNumericCellValue(), 1e-9);
-
- HSSFCell c1 = r[0].getCell(2);
- assertEquals("square(square(1))", c1.getCellFormula());
- assertEquals(1d, c1.getNumericCellValue(), 1e-9);
-
- HSSFCell c2 = r[1].getCell(2);
- assertEquals("square(square(2))", c2.getCellFormula());
- assertEquals(16d, c2.getNumericCellValue(), 1e-9);
-
- HSSFCell d1 = r[0].getCell(3);
- assertEquals("square(one())", d1.getCellFormula());
- assertEquals(1d, d1.getNumericCellValue(), 1e-9);
-
- HSSFCell d2 = r[1].getCell(3);
- assertEquals("square(two())", d2.getCellFormula());
- assertEquals(4d, d2.getNumericCellValue(), 1e-9);
- }
- }
-
- @Test
- void testStringFormulaRead() throws IOException {
- try (HSSFWorkbook w = openSample("StringFormulas.xls")) {
- HSSFCell c = w.getSheetAt(0).getRow(0).getCell(0);
- assertEquals("XYZ", c.getRichStringCellValue().getString(), "String Cell value");
- }
- }
-
- /** test for bug 34021*/
- @Test
- void testComplexSheetRefs() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s1 = wb1.createSheet("Sheet a.1");
- HSSFSheet s2 = wb1.createSheet("Sheet.A");
- s2.createRow(1).createCell(2).setCellFormula("'Sheet a.1'!A1");
- s1.createRow(1).createCell(2).setCellFormula("'Sheet.A'!A1");
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- s1 = wb2.getSheet("Sheet a.1");
- assertNotNull(s1);
- assertEquals("Sheet.A!A1", s1.getRow(1).getCell(2).getCellFormula());
- s2 = wb2.getSheet("Sheet.A");
- assertNotNull(s2);
- assertEquals("'Sheet a.1'!A1", s2.getRow(1).getCell(2).getCellFormula());
- }
- }
- }
-
- /** Unknown Ptg 3C*/
- @Test
- void test27272_1() throws IOException {
- try (HSSFWorkbook wb = openSample("27272_1.xls")) {
- wb.getSheetAt(0);
- assertEquals("Compliance!#REF!", wb.getNameAt(0).getRefersToFormula(), "Reference for named range");
- writeOutAndReadBack(wb).close();
- }
- }
-
- /** Unknown Ptg 3D*/
- @Test
- void test27272_2() throws IOException {
- try (HSSFWorkbook wb = openSample("27272_2.xls")) {
- assertEquals("LOAD.POD_HISTORIES!#REF!", wb.getNameAt(0).getRefersToFormula(), "Reference for named range");
- writeOutAndReadBack(wb).close();
- }
- }
-
- /** MissingArgPtg */
- @Test
- void testMissingArgPtg() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell(0);
- assertDoesNotThrow(() -> cell.setCellFormula("IF(A1=\"A\",1,)"));
- }
- }
-
- @Test
- void testSharedFormula() throws IOException {
- try (HSSFWorkbook wb = openSample("SharedFormulaTest.xls")) {
- assertEquals("A$1*2", wb.getSheetAt(0).getRow(1).getCell(1).toString());
- assertEquals("$A11*2", wb.getSheetAt(0).getRow(11).getCell(1).toString());
- assertEquals("DZ2*2", wb.getSheetAt(0).getRow(1).getCell(128).toString());
- assertEquals("B32770*2", wb.getSheetAt(0).getRow(32768).getCell(1).toString());
- }
- }
-
- /**
- * Test creation / evaluation of formulas with sheet-level names
- */
- @Test
- void testSheetLevelFormulas() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sh1 = wb.createSheet("Sheet1");
- HSSFName nm1 = wb.createName();
- nm1.setNameName("sales_1");
- nm1.setSheetIndex(0);
- nm1.setRefersToFormula("Sheet1!$A$1");
- HSSFRow row = sh1.createRow(0);
- row.createCell(0).setCellValue(3);
- row.createCell(1).setCellFormula("sales_1");
- row.createCell(2).setCellFormula("sales_1*2");
-
-
- HSSFSheet sh2 = wb.createSheet("Sheet2");
- HSSFName nm2 = wb.createName();
- nm2.setNameName("sales_1");
- nm2.setSheetIndex(1);
- nm2.setRefersToFormula("Sheet2!$A$1");
-
- row = sh2.createRow(0);
- row.createCell(0).setCellValue(5);
- row.createCell(1).setCellFormula("sales_1");
- row.createCell(2).setCellFormula("sales_1*3");
-
- //check that NamePtg refers to the correct NameRecord
- Ptg[] ptgs1 = HSSFFormulaParser.parse("sales_1", wb, FormulaType.CELL, 0);
- NamePtg nPtg1 = (NamePtg) ptgs1[0];
- assertSame(nm1, wb.getNameAt(nPtg1.getIndex()));
-
- Ptg[] ptgs2 = HSSFFormulaParser.parse("sales_1", wb, FormulaType.CELL, 1);
- NamePtg nPtg2 = (NamePtg) ptgs2[0];
- assertSame(nm2, wb.getNameAt(nPtg2.getIndex()));
-
- //check that the formula evaluator returns the correct result
- HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb);
- assertEquals(3.0, evaluator.evaluate(sh1.getRow(0).getCell(1)).getNumberValue(), 0.0);
- assertEquals(6.0, evaluator.evaluate(sh1.getRow(0).getCell(2)).getNumberValue(), 0.0);
-
- assertEquals(5.0, evaluator.evaluate(sh2.getRow(0).getCell(1)).getNumberValue(), 0.0);
- assertEquals(15.0, evaluator.evaluate(sh2.getRow(0).getCell(2)).getNumberValue(), 0.0);
- }
- }
-
- /**
- * Verify that FormulaParser handles defined names beginning with underscores,
- * see Bug #49640
- */
- @Test
- void testFormulasWithUnderscore() throws IOException{
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- Name nm1 = wb.createName();
- nm1.setNameName("_score1");
- nm1.setRefersToFormula("A1");
-
- Name nm2 = wb.createName();
- nm2.setNameName("_score2");
- nm2.setRefersToFormula("A2");
-
- Sheet sheet = wb.createSheet();
- Cell cell = sheet.createRow(0).createCell(2);
- cell.setCellFormula("_score1*SUM(_score1+_score2)");
- assertEquals("_score1*SUM(_score1+_score2)", cell.getCellFormula());
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java
deleted file mode 100644
index 57f0fbc19d..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java
+++ /dev/null
@@ -1,418 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.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 java.io.IOException;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-import java.util.ListIterator;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.InternalSheet;
-import org.apache.poi.hssf.record.DBCellRecord;
-import org.apache.poi.hssf.record.FormulaRecord;
-import org.apache.poi.hssf.record.StringRecord;
-import org.apache.poi.ss.usermodel.BaseTestCell;
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.CellType;
-import org.apache.poi.ss.usermodel.FormulaError;
-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.util.LocaleUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests various functionality having to do with {@link HSSFCell}. For instance support for
- * particular datatypes, etc.
- */
-final class TestHSSFCell extends BaseTestCell {
-
- public TestHSSFCell() {
- super(HSSFITestDataProvider.instance);
- }
-
- /**
- * Checks that the recognition of files using 1904 date windowing
- * is working properly. Conversion of the date is also an issue,
- * but there's a separate unit test for that.
- */
- @Test
- void testDateWindowingRead() throws IOException {
- Calendar cal = LocaleUtil.getLocaleCalendar(2000, 0, 1, 0, 0, 0);// Jan. 1, 2000
- Date date = cal.getTime();
-
- // first check a file with 1900 Date Windowing
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("1900DateWindowing.xls")) {
- HSSFSheet sheet = wb.getSheetAt(0);
-
- assertEquals(date.getTime(),
- sheet.getRow(0).getCell(0).getDateCellValue().getTime(),
- "Date from file using 1900 Date Windowing");
- }
-
- // now check a file with 1904 Date Windowing
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("1904DateWindowing.xls")) {
- HSSFSheet sheet = wb.getSheetAt(0);
-
- assertEquals(date.getTime(),
- sheet.getRow(0).getCell(0).getDateCellValue().getTime(),
- "Date from file using 1904 Date Windowing");
- }
- }
-
-
-
- /**
- * Checks that dates are properly written to both types of files:
- * those with 1900 and 1904 date windowing. Note that if the
- * previous test ({@link #testDateWindowingRead}) fails, the
- * results of this test are meaningless.
- */
- @Test
- void testDateWindowingWrite() throws IOException {
- Calendar cal = LocaleUtil.getLocaleCalendar(2000,0,1,0,0,0); // Jan. 1, 2000
- Date date = cal.getTime();
-
- // first check a file with 1900 Date Windowing
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("1900DateWindowing.xls")) {
-
- setCell(wb1, 0, 1, date);
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
-
- assertEquals(date.getTime(),
- readCell(wb2, 0, 1).getTime(),
- "Date from file using 1900 Date Windowing");
- }
- }
-
- // now check a file with 1904 Date Windowing
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("1904DateWindowing.xls")) {
- setCell(wb1, 0, 1, date);
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
- assertEquals(date.getTime(),
- readCell(wb2, 0, 1).getTime(),
- "Date from file using 1900 Date Windowing");
- }
- }
- }
-
- private static void setCell(HSSFWorkbook workbook, int rowIdx, int colIdx, Date date) {
- HSSFSheet sheet = workbook.getSheetAt(0);
- HSSFRow row = sheet.getRow(rowIdx);
- HSSFCell cell = row.getCell(colIdx);
-
- if (cell == null) {
- cell = row.createCell(colIdx);
- }
- cell.setCellValue(date);
- }
-
- private static Date readCell(HSSFWorkbook workbook, int rowIdx, int colIdx) {
- HSSFSheet sheet = workbook.getSheetAt(0);
- HSSFRow row = sheet.getRow(rowIdx);
- HSSFCell cell = row.getCell(colIdx);
- return cell.getDateCellValue();
- }
-
- /**
- * Tests that the active cell can be correctly read and set
- */
- @Test
- void testActiveCell() throws IOException {
- //read in sample
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls")) {
-
- //check initial position
- HSSFSheet umSheet = wb1.getSheetAt(0);
- InternalSheet s = umSheet.getSheet();
- assertEquals((short) 0, s.getActiveCellCol(), "Initial active cell should be in col 0");
- assertEquals(1, s.getActiveCellRow(), "Initial active cell should be on row 1");
-
- //modify position through HSSFCell
- HSSFCell cell = umSheet.createRow(3).createCell(2);
- cell.setAsActiveCell();
- assertEquals((short) 2, s.getActiveCellCol(), "After modify, active cell should be in col 2");
- assertEquals(3, s.getActiveCellRow(), "After modify, active cell should be on row 3");
-
- //write book to temp file; read and verify that position is serialized
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
- umSheet = wb2.getSheetAt(0);
- s = umSheet.getSheet();
-
- assertEquals((short) 2, s.getActiveCellCol(), "After serialize, active cell should be in col 2");
- assertEquals(3, s.getActiveCellRow(), "After serialize, active cell should be on row 3");
- }
- }
- }
-
-
- @Test
- void testActiveCellBug56114() throws IOException {
- try (Workbook wb = new HSSFWorkbook()) {
- Sheet sh = wb.createSheet();
-
- sh.createRow(0);
- sh.createRow(1);
- sh.createRow(2);
- sh.createRow(3);
-
- Cell cell = sh.getRow(1).createCell(3);
- sh.getRow(3).createCell(3);
-
- assertEquals(0, ((HSSFSheet) wb.getSheetAt(0)).getSheet().getActiveCellRow());
- assertEquals(0, ((HSSFSheet) wb.getSheetAt(0)).getSheet().getActiveCellCol());
-
- cell.setAsActiveCell();
- cell.setCellValue("this should be active");
-
- assertEquals(1, ((HSSFSheet) wb.getSheetAt(0)).getSheet().getActiveCellRow());
- assertEquals(3, ((HSSFSheet) wb.getSheetAt(0)).getSheet().getActiveCellCol());
-
- try (Workbook wbBack = _testDataProvider.writeOutAndReadBack(wb)) {
- assertEquals(1, ((HSSFSheet) wbBack.getSheetAt(0)).getSheet().getActiveCellRow());
- assertEquals(3, ((HSSFSheet) wbBack.getSheetAt(0)).getSheet().getActiveCellCol());
-
- wbBack.getSheetAt(0).getRow(3).getCell(3).setAsActiveCell();
-
- assertEquals(3, ((HSSFSheet) wbBack.getSheetAt(0)).getSheet().getActiveCellRow());
- assertEquals(3, ((HSSFSheet) wbBack.getSheetAt(0)).getSheet().getActiveCellCol());
-
- try (Workbook wbBack2 = _testDataProvider.writeOutAndReadBack(wbBack)) {
- assertEquals(3, ((HSSFSheet) wbBack2.getSheetAt(0)).getSheet().getActiveCellRow());
- assertEquals(3, ((HSSFSheet) wbBack2.getSheetAt(0)).getSheet().getActiveCellCol());
- }
- }
- }
- }
-
- /**
- * Test reading hyperlinks
- */
- @Test
- void testWithHyperlink() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithHyperlink.xls")) {
-
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFCell cell = sheet.getRow(4).getCell(0);
- HSSFHyperlink link = cell.getHyperlink();
- assertNotNull(link);
-
- assertEquals("Foo", link.getLabel());
- assertEquals("http://poi.apache.org/", link.getAddress());
- assertEquals(4, link.getFirstRow());
- assertEquals(0, link.getFirstColumn());
- }
- }
-
- /**
- * Test reading hyperlinks
- */
- @Test
- void testWithTwoHyperlinks() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithTwoHyperLinks.xls")) {
-
- HSSFSheet sheet = wb.getSheetAt(0);
-
- HSSFCell cell1 = sheet.getRow(4).getCell(0);
- HSSFHyperlink link1 = cell1.getHyperlink();
- assertNotNull(link1);
- assertEquals("Foo", link1.getLabel());
- assertEquals("http://poi.apache.org/", link1.getAddress());
- assertEquals(4, link1.getFirstRow());
- assertEquals(0, link1.getFirstColumn());
-
- HSSFCell cell2 = sheet.getRow(8).getCell(1);
- HSSFHyperlink link2 = cell2.getHyperlink();
- assertNotNull(link2);
- assertEquals("Bar", link2.getLabel());
- assertEquals("http://poi.apache.org/hssf/", link2.getAddress());
- assertEquals(8, link2.getFirstRow());
- assertEquals(1, link2.getFirstColumn());
- }
- }
-
- /**
- * Test to ensure we can only assign cell styles that belong
- * to our workbook, and not those from other workbooks.
- */
- @Test
- void testCellStyleWorkbookMatch() throws IOException {
- try (HSSFWorkbook wbA = new HSSFWorkbook();
- HSSFWorkbook wbB = new HSSFWorkbook()) {
-
- HSSFCellStyle styA = wbA.createCellStyle();
- HSSFCellStyle styB = wbB.createCellStyle();
-
- styA.verifyBelongsToWorkbook(wbA);
- styB.verifyBelongsToWorkbook(wbB);
- assertThrows(IllegalArgumentException.class, () -> styA.verifyBelongsToWorkbook(wbB));
- assertThrows(IllegalArgumentException.class, () -> styB.verifyBelongsToWorkbook(wbA));
-
- Cell cellA = wbA.createSheet().createRow(0).createCell(0);
- Cell cellB = wbB.createSheet().createRow(0).createCell(0);
-
- cellA.setCellStyle(styA);
- cellB.setCellStyle(styB);
- assertThrows(IllegalArgumentException.class, () -> cellA.setCellStyle(styB));
- assertThrows(IllegalArgumentException.class, () -> cellB.setCellStyle(styA));
- }
- }
-
- /**
- * Test for small bug observable around r736460 (prior to version 3.5). POI fails to remove
- * the {@link StringRecord} following the {@link FormulaRecord} after the result type had been
- * changed to number/boolean/error. Excel silently ignores the extra record, but some POI
- * versions (prior to bug 46213 / r717883) crash instead.
- */
- @Test
- void testCachedTypeChange() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet("Sheet1");
- Cell cell = sheet.createRow(0).createCell(0);
- cell.setCellFormula("A1");
- cell.setCellValue("abc");
- confirmStringRecord(sheet, true);
- cell.setCellValue(123);
-
- final List recs = new ArrayList<>();
- sheet.getSheet().visitContainedRecords(recs::add, 0);
- assertFalse(recs.size() == 28 && recs.get(23) instanceof StringRecord, "Identified bug - leftover StringRecord");
- confirmStringRecord(sheet, false);
-
- // string to error code
- cell.setCellValue("abc");
- confirmStringRecord(sheet, true);
- cell.setCellErrorValue(FormulaError.REF.getCode());
- confirmStringRecord(sheet, false);
-
- // string to boolean
- cell.setCellValue("abc");
- confirmStringRecord(sheet, true);
- cell.setCellValue(false);
- confirmStringRecord(sheet, false);
- }
- }
-
- private static void confirmStringRecord(HSSFSheet sheet, boolean isPresent) {
- List recs = new ArrayList<>();
- sheet.getSheet().visitContainedRecords(recs::add, 0);
- assertEquals(isPresent ? 28 : 27, recs.size());
-
- ListIterator iter = recs.listIterator(22);
- assertEquals(FormulaRecord.class, iter.next().getClass());
- if (isPresent) {
- assertEquals(StringRecord.class, iter.next().getClass());
- }
- assertEquals(DBCellRecord.class, iter.next().getClass());
- }
-
- /**
- * HSSF prior to version 3.7 had a bug: it could write a NaN but could not read such a file back.
- */
- @Test
- void testReadNaN() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49761.xls")) {
- assertNotNull(wb);
- }
- }
-
- @Test
- void testHSSFCell() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- HSSFRow row = sheet.createRow(0);
- row.createCell(0);
- HSSFCell cell = new HSSFCell(wb, sheet, 0, (short) 0);
- assertNotNull(cell);
- }
- }
-
- @Test
- void testDeprecatedMethods() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell = row.createCell(0);
-
- // cover some deprecated methods and other smaller stuff...
- assertEquals(wb.getWorkbook(), cell.getBoundWorkbook());
-
- assertThrows(IllegalStateException.class, cell::getCachedFormulaResultType);
-
- cell.removeCellComment();
- cell.removeCellComment();
- }
- }
-
- @Test
- void testCellType() throws IOException {
- try (Workbook wb = _testDataProvider.createWorkbook()) {
- Sheet sheet = wb.createSheet();
- Row row = sheet.createRow(0);
- Cell cell = row.createCell(0);
-
- cell.setBlank();
- assertNull(cell.getDateCellValue());
- assertFalse(cell.getBooleanCellValue());
- assertEquals("", cell.toString());
-
- cell.setCellType(CellType.STRING);
- assertEquals("", cell.toString());
- cell.setCellValue(1.2);
- assertEquals("1.2", cell.toString());
- cell.setCellType(CellType.BOOLEAN);
- assertEquals("TRUE", cell.toString());
- cell.setCellType(CellType.BOOLEAN);
- cell.setCellValue("" + FormulaError.VALUE.name());
- assertEquals(CellType.STRING, cell.getCellType());
- cell.setCellType(CellType.BOOLEAN);
- assertEquals("FALSE", cell.toString());
- cell.setCellValue(1.2);
- assertEquals("1.2", cell.toString());
- cell.setCellType(CellType.BOOLEAN);
- cell.setCellType(CellType.STRING);
- cell.setCellType(CellType.ERROR);
- cell.setCellType(CellType.STRING);
- cell.setCellValue(1.2);
- cell.setCellType(CellType.STRING);
- assertEquals("1.2", cell.toString());
-
- cell.setCellValue((String) null);
- cell.setCellValue((RichTextString) null);
- }
- }
-
- @Test
- void getErrorCellValue_throwsISE_onABlankCell() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- Cell cell = wb.createSheet().createRow(0).createCell(0);
- assertThrows(IllegalStateException.class, cell::getErrorCellValue);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java
deleted file mode 100644
index a6555e3f6c..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook;
-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 java.io.IOException;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.record.chart.SeriesRecord;
-import org.apache.poi.hssf.usermodel.HSSFChart.HSSFSeries;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.apache.poi.ss.util.CellRangeAddressBase;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link HSSFChart}
- */
-final class TestHSSFChart {
-
- @Test
- void testSingleChart() {
- HSSFWorkbook wb = openSampleWorkbook("WithChart.xls");
-
- HSSFSheet s1 = wb.getSheetAt(0);
- HSSFSheet s2 = wb.getSheetAt(1);
- HSSFSheet s3 = wb.getSheetAt(2);
-
- assertEquals(0, HSSFChart.getSheetCharts(s1).length);
- assertEquals(1, HSSFChart.getSheetCharts(s2).length);
- assertEquals(0, HSSFChart.getSheetCharts(s3).length);
-
- HSSFChart[] charts;
-
- // Check the chart on the 2nd sheet
- charts = HSSFChart.getSheetCharts(s2);
- assertEquals(1, charts.length);
-
- assertEquals(2, charts[0].getSeries().length);
- assertEquals("1st Column", charts[0].getSeries()[0].getSeriesTitle());
- assertEquals("2nd Column", charts[0].getSeries()[1].getSeriesTitle());
- assertNull(charts[0].getChartTitle());
-
- // Check x, y, width, height
- assertEquals(0, charts[0].getChartX());
- assertEquals(0, charts[0].getChartY());
- assertEquals(26492928, charts[0].getChartWidth());
- assertEquals(15040512, charts[0].getChartHeight());
- }
-
- @Test
- void testTwoCharts() {
- HSSFWorkbook wb = openSampleWorkbook("WithTwoCharts.xls");
-
- HSSFSheet s1 = wb.getSheetAt(0);
- HSSFSheet s2 = wb.getSheetAt(1);
- HSSFSheet s3 = wb.getSheetAt(2);
-
- assertEquals(0, HSSFChart.getSheetCharts(s1).length);
- assertEquals(1, HSSFChart.getSheetCharts(s2).length);
- assertEquals(1, HSSFChart.getSheetCharts(s3).length);
-
- HSSFChart[] charts;
-
- // Check the chart on the 2nd sheet
- charts = HSSFChart.getSheetCharts(s2);
- assertEquals(1, charts.length);
-
- assertEquals(2, charts[0].getSeries().length);
- assertEquals("1st Column", charts[0].getSeries()[0].getSeriesTitle());
- assertEquals("2nd Column", charts[0].getSeries()[1].getSeriesTitle());
- assertNull(charts[0].getChartTitle());
-
- // And the third sheet
- charts = HSSFChart.getSheetCharts(s3);
- assertEquals(1, charts.length);
-
- assertEquals(2, charts[0].getSeries().length);
- assertEquals("Squares", charts[0].getSeries()[0].getSeriesTitle());
- assertEquals("Base Numbers", charts[0].getSeries()[1].getSeriesTitle());
- assertNull(charts[0].getChartTitle());
- }
-
- @Test
- void testThreeCharts() {
- HSSFWorkbook wb = openSampleWorkbook("WithThreeCharts.xls");
-
- HSSFSheet s1 = wb.getSheetAt(0);
- HSSFSheet s2 = wb.getSheetAt(1);
- HSSFSheet s3 = wb.getSheetAt(2);
-
- assertEquals(0, HSSFChart.getSheetCharts(s1).length);
- assertEquals(2, HSSFChart.getSheetCharts(s2).length);
- assertEquals(1, HSSFChart.getSheetCharts(s3).length);
-
- HSSFChart[] charts;
-
- // Check the charts on the 2nd sheet
- charts = HSSFChart.getSheetCharts(s2);
- assertEquals(2, charts.length);
-
- assertEquals(2, charts[0].getSeries().length);
- assertEquals("1st Column", charts[0].getSeries()[0].getSeriesTitle());
- assertEquals("2nd Column", charts[0].getSeries()[1].getSeriesTitle());
- assertEquals(6, charts[0].getSeries()[0].getNumValues());
- assertEquals(6, charts[0].getSeries()[1].getNumValues());
- assertEquals(SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC, charts[0].getSeries()[0].getValueType());
- assertEquals(SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC, charts[0].getSeries()[1].getValueType());
- assertNull(charts[0].getChartTitle());
-
- assertEquals(1, charts[1].getSeries().length);
- assertNull(charts[1].getSeries()[0].getSeriesTitle());
- assertEquals("Pie Chart Title Thingy", charts[1].getChartTitle());
-
- // And the third sheet
- charts = HSSFChart.getSheetCharts(s3);
- assertEquals(1, charts.length);
-
- assertEquals(2, charts[0].getSeries().length);
- assertEquals("Squares", charts[0].getSeries()[0].getSeriesTitle());
- assertEquals("Base Numbers", charts[0].getSeries()[1].getSeriesTitle());
- assertEquals("Sheet 3 Chart with Title", charts[0].getChartTitle());
- }
-
- @Test
- void testExistingSheet3() throws Exception {
- HSSFWorkbook wb = openSampleWorkbook("49581.xls");
-
- HSSFSheet sheet = wb.getSheetAt( 2 ) ;
- HSSFChart[] charts = HSSFChart.getSheetCharts( sheet ) ;
- assertEquals(1, charts.length);
-
- for ( HSSFChart chart : charts ) {
- for ( HSSFSeries series : chart.getSeries() ) {
- chart.removeSeries( series ) ;
- }
- }
-
- // Save and re-check
- wb = HSSFITestDataProvider.instance.writeOutAndReadBack(wb);
- sheet = wb.getSheetAt( 2 ) ;
- assertEquals(1, HSSFChart.getSheetCharts(sheet).length);
-
- HSSFChart c = HSSFChart.getSheetCharts(sheet)[0];
- assertEquals(0, c.getSeries().length);
- }
-
- @Test
- void testExistingSheet2() throws Exception {
- HSSFWorkbook wb = openSampleWorkbook("49581.xls");
- HSSFSheet sheet = wb.getSheetAt( 1 ) ;
- HSSFChart[] charts = HSSFChart.getSheetCharts( sheet ) ;
-
- assertEquals(1, charts.length);
- for ( HSSFChart chart : charts ) {
- HSSFSeries series ;
-
- // Starts with one
- assertEquals(1, chart.getSeries().length);
-
- // Add two more
- series = chart.createSeries() ;
- series.setCategoryLabelsCellRange( new CellRangeAddress( 3, 4, 0, 0 ) ) ;
- series.setValuesCellRange( new CellRangeAddress( 3, 4, 1, 1 ) ) ;
-
- series = chart.createSeries() ;
- series.setCategoryLabelsCellRange( new CellRangeAddress( 6, 7, 0, 0 ) ) ;
- series.setValuesCellRange( new CellRangeAddress( 6, 7, 1, 1 ) ) ;
- }
-
- // Save and re-check
- wb = HSSFITestDataProvider.instance.writeOutAndReadBack(wb);
- sheet = wb.getSheetAt( 1 ) ;
- assertEquals(1, HSSFChart.getSheetCharts(sheet).length);
-
- HSSFChart c = HSSFChart.getSheetCharts(sheet)[0];
- assertEquals(3, c.getSeries().length);
- }
-
- @Test
- void testExistingSheet1() throws Exception {
- try (HSSFWorkbook wb = openSampleWorkbook("49581.xls")) {
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFChart[] charts = HSSFChart.getSheetCharts(sheet);
-
- for (HSSFChart chart : charts) {
- for (HSSFSeries series : chart.getSeries()) {
- CellRangeAddressBase range;
-
- range = series.getValuesCellRange();
- range.setLastRow(range.getLastRow() + 1);
- series.setValuesCellRange(range);
-
- range = series.getCategoryLabelsCellRange();
- range.setLastRow(range.getLastRow() + 1);
- series.setCategoryLabelsCellRange(range);
- }
-
- for (int id = 0; id < 2; id++) {
- HSSFSeries newSeries = chart.createSeries();
- assertNotNull(newSeries);
- newSeries.setValuesCellRange(new CellRangeAddress(1 + id, 4, 3, 3));
- String oldSeriesTitle = newSeries.getSeriesTitle();
- if (oldSeriesTitle != null) {
- newSeries.setSeriesTitle("new series");
- }
- }
- }
-
- HSSFChart chart = charts[2];
- chart.removeSeries(chart.getSeries()[0]);
- assertEquals(2, chart.getSeries().length);
- }
- }
-
- /**
- * Bug 26862: HSSFWorkbook.cloneSheet copies charts
- */
- @Test
- void test26862() throws IOException, Exception {
- HSSFWorkbook wb = openSampleWorkbook("SimpleChart.xls");
- HSSFSheet srcSheet = wb.getSheetAt(0);
- HSSFChart[] srcCharts = HSSFChart.getSheetCharts(srcSheet);
- assertEquals(1, srcCharts.length);
- HSSFChart srcChart = srcCharts[0];
-
- // Clone the sheet
- HSSFSheet clonedSheet = wb.cloneSheet(0);
-
- // Verify the chart was copied
- HSSFChart[] clonedCharts = HSSFChart.getSheetCharts(clonedSheet);
- assertEquals(1, clonedCharts.length);
- HSSFChart clonedChart = clonedCharts[0];
- assertNotSame(srcChart, clonedChart); //refer to different objects
- assertEquals(srcChart.getType(), clonedChart.getType());
- assertEquals(srcChart.getChartTitle(), clonedChart.getChartTitle());
- assertEquals(srcChart.getChartWidth(), clonedChart.getChartWidth());
- assertEquals(srcChart.getChartHeight(), clonedChart.getChartHeight());
- assertEquals(srcChart.getChartX(), clonedChart.getChartX());
- assertEquals(srcChart.getChartY(), clonedChart.getChartY());
-
- // Check if chart was shallow copied or deep copied
- clonedChart.setChartWidth(clonedChart.getChartWidth()+10);
- assertEquals(srcChart.getChartWidth()+10, clonedChart.getChartWidth());
-
- wb.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java
deleted file mode 100644
index 1cc79736c1..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-import java.io.IOException;
-
-import org.apache.poi.ddf.EscherClientAnchorRecord;
-import org.apache.poi.hssf.model.ConvertAnchor;
-import org.junit.jupiter.api.Test;
-
-/**
- * Various tests for HSSFClientAnchor.
- */
-final class TestHSSFClientAnchor {
- @Test
- void testGetAnchorHeightInPoints() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet("test");
- HSSFClientAnchor a = new HSSFClientAnchor(0, 0, 1023, 255, (short) 0, 0, (short) 0, 0);
- float p = a.getAnchorHeightInPoints(sheet);
- assertEquals(12.7, p, 0.001);
-
- sheet.createRow(0).setHeightInPoints(14);
- a = new HSSFClientAnchor(0, 0, 1023, 255, (short) 0, 0, (short) 0, 0);
- p = a.getAnchorHeightInPoints(sheet);
- assertEquals(13.945, p, 0.001);
-
- a = new HSSFClientAnchor(0, 0, 1023, 127, (short) 0, 0, (short) 0, 0);
- p = a.getAnchorHeightInPoints(sheet);
- assertEquals(6.945, p, 0.001);
-
- a = new HSSFClientAnchor(0, 126, 1023, 127, (short) 0, 0, (short) 0, 0);
- p = a.getAnchorHeightInPoints(sheet);
- assertEquals(0.054, p, 0.001);
-
- a = new HSSFClientAnchor(0, 0, 1023, 0, (short) 0, 0, (short) 0, 1);
- p = a.getAnchorHeightInPoints(sheet);
- assertEquals(14.0, p, 0.001);
-
- sheet.createRow(0).setHeightInPoints(12);
- a = new HSSFClientAnchor(0, 127, 1023, 127, (short) 0, 0, (short) 0, 1);
- p = a.getAnchorHeightInPoints(sheet);
- assertEquals(12.372, p, 0.001);
- }
- }
-
- /**
- * When HSSFClientAnchor is converted into EscherClientAnchorRecord
- * check that dx1, dx2, dy1 and dy2 are written "as is".
- * (Bug 42999 reported that dx1 and dx2 are swapped if dx1>dx2. It doesn't make sense for client anchors.)
- */
- @Test
- void testConvertAnchor() {
- HSSFClientAnchor[] anchors = {
- new HSSFClientAnchor( 0 , 0 , 0 , 0 ,(short)0, 1,(short)1,3),
- new HSSFClientAnchor( 100 , 0 , 900 , 255 ,(short)0, 1,(short)1,3),
- new HSSFClientAnchor( 900 , 0 , 100 , 255 ,(short)0, 1,(short)1,3)
- };
- for (HSSFClientAnchor anchor : anchors) {
- EscherClientAnchorRecord record = (EscherClientAnchorRecord)ConvertAnchor.createAnchor(anchor);
- assertEquals(anchor.getDx1(), record.getDx1());
- assertEquals(anchor.getDx2(), record.getDx2());
- assertEquals(anchor.getDy1(), record.getDy1());
- assertEquals(anchor.getDy2(), record.getDy2());
- assertEquals(anchor.getCol1(), record.getCol1());
- assertEquals(anchor.getCol2(), record.getCol2());
- assertEquals(anchor.getRow1(), record.getRow1());
- assertEquals(anchor.getRow2(), record.getRow2());
- }
- }
-
- @Test
- void testAnchorHeightInPoints() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
-
- HSSFClientAnchor[] anchor = {
- new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 1, (short) 1, 3),
- new HSSFClientAnchor(0, 254, 0, 126, (short) 0, 1, (short) 1, 3),
- new HSSFClientAnchor(0, 128, 0, 128, (short) 0, 1, (short) 1, 3),
- new HSSFClientAnchor(0, 0, 0, 128, (short) 0, 1, (short) 1, 3),
- };
- float[] ref = {25.5f, 19.125f, 25.5f, 31.875f};
- for (int i = 0; i < anchor.length; i++) {
- float height = anchor[i].getAnchorHeightInPoints(sheet);
- assertEquals(ref[i], height, 0);
- }
- }
- }
-
- /**
- * Check {@link HSSFClientAnchor} constructor does not treat 32768 as -32768.
- */
- @Test
- void testCanHaveRowGreaterThan32767() {
- // Maximum permitted row number should be 65535.
- HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 32768, (short) 0, 32768);
-
- assertEquals(32768, anchor.getRow1());
- assertEquals(32768, anchor.getRow2());
- }
-
- /**
- * Check the maximum is not set at 255*256 instead of 256*256 - 1.
- */
- @Test
- void testCanHaveRowUpTo65535() {
- HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 65535, (short) 0, 65535);
-
- assertEquals(65535, anchor.getRow1());
- assertEquals(65535, anchor.getRow2());
- }
-
- @Test
- void testCannotHaveRowGreaterThan65535() {
- assertThrows(IllegalArgumentException.class, () ->
- new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 65536, (short) 0, 65536));
- }
-
- /**
- * Check the same maximum value enforced when using {@link HSSFClientAnchor#setRow1}.
- */
- @Test
- void testCanSetRowUpTo65535() {
- HSSFClientAnchor anchor = new HSSFClientAnchor();
- anchor.setRow1(65535);
- anchor.setRow2(65535);
-
- assertEquals(65535, anchor.getRow1());
- assertEquals(65535, anchor.getRow2());
- }
-
- @Test
- void testCannotSetRow1GreaterThan65535() {
- assertThrows(IllegalArgumentException.class, () ->
- new HSSFClientAnchor().setRow1(65536));
- }
-
- @Test
- void testCannotSetRow2GreaterThan65535() {
- assertThrows(IllegalArgumentException.class, () ->
- new HSSFClientAnchor().setRow2(65536));
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFColumnShifting.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFColumnShifting.java
deleted file mode 100644
index 66a5c308df..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFColumnShifting.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.hssf.usermodel;
-
-import org.apache.poi.hssf.usermodel.helpers.HSSFColumnShifter;
-import org.apache.poi.ss.usermodel.BaseTestColumnShifting;
-
-class TestHSSFColumnShifting extends BaseTestColumnShifting {
- public TestHSSFColumnShifting() {
- super();
- wb = new HSSFWorkbook();
- }
- @Override
- protected void initColumnShifter(){
- columnShifter = new HSSFColumnShifter((HSSFSheet)sheet1);
- }
-
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java
deleted file mode 100644
index 181cd5052b..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java
+++ /dev/null
@@ -1,452 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-package org.apache.poi.hssf.usermodel;
-
-import static org.apache.poi.poifs.storage.RawDataUtil.decompress;
-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.io.IOException;
-
-import org.apache.poi.ddf.EscherSpRecord;
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.CommonObjectDataSubRecord;
-import org.apache.poi.hssf.record.EscherAggregate;
-import org.apache.poi.hssf.record.NoteRecord;
-import org.apache.poi.hssf.record.ObjRecord;
-import org.apache.poi.hssf.record.TextObjectRecord;
-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.Drawing;
-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.junit.jupiter.api.Test;
-
-/**
- * Tests TestHSSFCellComment.
- *
- * @author Yegor Kozlov
- */
-final class TestHSSFComment extends BaseTestCellComment {
-
- public TestHSSFComment() {
- super(HSSFITestDataProvider.instance);
- }
-
- @Test
- void defaultShapeType() {
- HSSFComment comment = new HSSFComment(null, new HSSFClientAnchor());
- assertEquals(HSSFSimpleShape.OBJECT_TYPE_COMMENT, comment.getShapeType());
- }
-
- /**
- * HSSFCell#findCellComment should NOT rely on the order of records
- * when matching cells and their cell comments. The correct algorithm is to map
- */
- @Test
- void bug47924() throws IOException {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("47924.xls");
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFCell cell;
- HSSFComment comment;
-
- cell = sheet.getRow(0).getCell(0);
- comment = cell.getCellComment();
- assertEquals("a1", comment.getString().getString());
-
- cell = sheet.getRow(1).getCell(0);
- comment = cell.getCellComment();
- assertEquals("a2", comment.getString().getString());
-
- cell = sheet.getRow(2).getCell(0);
- comment = cell.getCellComment();
- assertEquals("a3", comment.getString().getString());
-
- cell = sheet.getRow(2).getCell(2);
- comment = cell.getCellComment();
- assertEquals("c3", comment.getString().getString());
-
- cell = sheet.getRow(4).getCell(1);
- comment = cell.getCellComment();
- assertEquals("b5", comment.getString().getString());
-
- cell = sheet.getRow(5).getCell(2);
- comment = cell.getCellComment();
- assertEquals("c6", comment.getString().getString());
-
- wb.close();
- }
-
- @Test
- void testBug56380InsertComments() throws Exception {
- HSSFWorkbook workbook = new HSSFWorkbook();
- Sheet sheet = workbook.createSheet();
- Drawing> drawing = sheet.createDrawingPatriarch();
- int noOfRows = 1025;
- String comment = "c";
-
- for(int i = 0; i < noOfRows; i++) {
- Row row = sheet.createRow(i);
- Cell cell = row.createCell(0);
- insertComment(drawing, cell, comment + i);
- }
-
- // assert that the comments are created properly before writing
- checkComments(sheet, noOfRows, comment);
-
- /*// store in temp-file
- OutputStream fs = new FileOutputStream("/tmp/56380.xls");
- try {
- sheet.getWorkbook().write(fs);
- } finally {
- fs.close();
- }*/
-
- // save and recreate the workbook from the saved file
- HSSFWorkbook workbookBack = HSSFTestDataSamples.writeOutAndReadBack(workbook);
- sheet = workbookBack.getSheetAt(0);
-
- // assert that the comments are created properly after reading back in
- checkComments(sheet, noOfRows, comment);
-
- workbook.close();
- workbookBack.close();
- }
-
- @Test
- void testBug56380InsertTooManyComments() throws Exception {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- Sheet sheet = workbook.createSheet();
- Drawing> drawing = sheet.createDrawingPatriarch();
- String comment = "c";
-
- for (int rowNum = 0; rowNum < 258; rowNum++) {
- sheet.createRow(rowNum);
- }
-
- // should still work, for some reason DrawingManager2.allocateShapeId() skips the first 1024...
- for (int count = 1025; count < 65535; count++) {
- int rowNum = count / 255;
- int cellNum = count % 255;
- Cell cell = sheet.getRow(rowNum).createCell(cellNum);
- try {
- Comment commentObj = insertComment(drawing, cell, comment + cellNum);
-
- assertEquals(count, ((HSSFComment) commentObj).getNoteRecord().getShapeId());
- } catch (IllegalArgumentException e) {
- throw new IllegalArgumentException("While adding shape number " + count, e);
- }
- }
-
- // this should now fail to insert
- Row row = sheet.createRow(257);
- Cell cell = row.createCell(0);
- insertComment(drawing, cell, comment + 0);
- }
- }
-
- private void checkComments(Sheet sheet, int noOfRows, String comment) {
- for(int i = 0; i < noOfRows; i++) {
- assertNotNull(sheet.getRow(i));
- assertNotNull(sheet.getRow(i).getCell(0));
- assertNotNull(sheet.getRow(i).getCell(0).getCellComment(), "Did not get a Cell Comment for row " + i);
- assertNotNull(sheet.getRow(i).getCell(0).getCellComment().getString());
- assertEquals(comment + i, sheet.getRow(i).getCell(0).getCellComment().getString().getString());
- }
- }
-
- private Comment insertComment(Drawing> drawing, Cell cell, String message) {
- CreationHelper factory = cell.getSheet().getWorkbook().getCreationHelper();
-
- ClientAnchor anchor = factory.createClientAnchor();
- anchor.setCol1(cell.getColumnIndex());
- anchor.setCol2(cell.getColumnIndex() + 1);
- anchor.setRow1(cell.getRowIndex());
- anchor.setRow2(cell.getRowIndex() + 1);
- anchor.setDx1(100);
- anchor.setDx2(100);
- anchor.setDy1(100);
- anchor.setDy2(100);
-
- Comment comment = drawing.createCellComment(anchor);
-
- RichTextString str = factory.createRichTextString(message);
- comment.setString(str);
- comment.setAuthor("fanfy");
- cell.setCellComment(comment);
-
- return comment;
- }
-
- @Test
- void resultEqualsToNonExistingAbstractShape() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
-
- HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor());
- HSSFRow row = sh.createRow(0);
- HSSFCell cell = row.createCell(0);
- cell.setCellComment(comment);
-
- assertEquals(comment.getEscherContainer().getChildCount(), 5);
-
- //sp record
- byte[] expected = decompress("H4sIAAAAAAAAAFvEw/WBg4GBgZEFSHAxMAAA9gX7nhAAAAA=");
- byte[] actual = comment.getEscherContainer().getChild(0).serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- expected = decompress("H4sIAAAAAAAAAGNgEPggxIANAABK4+laGgAAAA==");
- actual = comment.getEscherContainer().getChild(2).serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- expected = decompress("H4sIAAAAAAAAAGNgEPzAAAQACl6c5QgAAAA=");
- actual = comment.getEscherContainer().getChild(3).serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- expected = decompress("H4sIAAAAAAAAAGNg4P3AAAQA6pyIkQgAAAA=");
- actual = comment.getEscherContainer().getChild(4).serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- ObjRecord obj = comment.getObjRecord();
-
- expected = decompress("H4sIAAAAAAAAAItlMGEQZRBikGRgZBF0YEACvAxiDLgBAJZsuoU4AAAA");
- actual = obj.serialize();
-
- assertEquals(expected.length, actual.length);
- //assertArrayEquals(expected, actual);
-
- TextObjectRecord tor = comment.getTextObjectRecord();
-
- expected = decompress("H4sIAAAAAAAAANvGKMQgxMSABgBGi8T+FgAAAA==");
- actual = tor.serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- NoteRecord note = comment.getNoteRecord();
-
- expected = decompress("H4sIAAAAAAAAAJNh4GGAAEYWEAkAS0KXuRAAAAA=");
- actual = note.serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- wb.close();
- }
-
- @Test
- void addToExistingFile() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
- int idx = wb.addPicture(new byte[]{1,2,3}, Workbook.PICTURE_TYPE_PNG);
-
- HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor());
- comment.setColumn(5);
- comment.setString(new HSSFRichTextString("comment1"));
- comment = patriarch.createCellComment(new HSSFClientAnchor(0,0,100,100,(short)0,0,(short)10,10));
- comment.setRow(5);
- comment.setString(new HSSFRichTextString("comment2"));
- comment.setBackgroundImage(idx);
- assertEquals(comment.getBackgroundImageId(), idx);
-
- assertEquals(patriarch.getChildren().size(), 2);
-
- HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sh = wbBack.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- comment = (HSSFComment) patriarch.getChildren().get(1);
- assertEquals(comment.getBackgroundImageId(), idx);
- comment.resetBackgroundImage();
- assertEquals(comment.getBackgroundImageId(), 0);
-
- assertEquals(patriarch.getChildren().size(), 2);
- comment = patriarch.createCellComment(new HSSFClientAnchor());
- comment.setString(new HSSFRichTextString("comment3"));
-
- assertEquals(patriarch.getChildren().size(), 3);
- HSSFWorkbook wbBack2 = HSSFTestDataSamples.writeOutAndReadBack(wbBack);
- sh = wbBack2.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
- comment = (HSSFComment) patriarch.getChildren().get(1);
- assertEquals(comment.getBackgroundImageId(), 0);
- assertEquals(patriarch.getChildren().size(), 3);
- assertEquals(((HSSFComment) patriarch.getChildren().get(0)).getString().getString(), "comment1");
- assertEquals(((HSSFComment) patriarch.getChildren().get(1)).getString().getString(), "comment2");
- assertEquals(((HSSFComment) patriarch.getChildren().get(2)).getString().getString(), "comment3");
-
- wb.close();
- wbBack.close();
- wbBack2.close();
- }
-
- @Test
- void setGetProperties() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
-
- HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor());
- comment.setString(new HSSFRichTextString("comment1"));
- assertEquals(comment.getString().getString(), "comment1");
-
- comment.setAuthor("poi");
- assertEquals(comment.getAuthor(), "poi");
-
- comment.setColumn(3);
- assertEquals(comment.getColumn(), 3);
-
- comment.setRow(4);
- assertEquals(comment.getRow(), 4);
-
- comment.setVisible(false);
- assertFalse(comment.isVisible());
-
- HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sh = wbBack.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- comment = (HSSFComment) patriarch.getChildren().get(0);
-
- assertEquals(comment.getString().getString(), "comment1");
- assertEquals("poi", comment.getAuthor());
- assertEquals(comment.getColumn(), 3);
- assertEquals(comment.getRow(), 4);
- assertFalse(comment.isVisible());
-
- comment.setString(new HSSFRichTextString("comment12"));
- comment.setAuthor("poi2");
- comment.setColumn(32);
- comment.setRow(42);
- comment.setVisible(true);
-
- HSSFWorkbook wbBack2 = HSSFTestDataSamples.writeOutAndReadBack(wbBack);
- sh = wbBack2.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
- comment = (HSSFComment) patriarch.getChildren().get(0);
-
- assertEquals(comment.getString().getString(), "comment12");
- assertEquals("poi2", comment.getAuthor());
- assertEquals(comment.getColumn(), 32);
- assertEquals(comment.getRow(), 42);
- assertTrue(comment.isVisible());
-
- wb.close();
- wbBack.close();
- wbBack2.close();
- }
-
- @Test
- void existingFileWithComment() throws IOException {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls");
- HSSFSheet sheet = wb.getSheet("comments");
- HSSFPatriarch drawing = sheet.getDrawingPatriarch();
- assertEquals(1, drawing.getChildren().size());
- HSSFComment comment = (HSSFComment) drawing.getChildren().get(0);
- assertEquals(comment.getAuthor(), "evgeniy");
- assertEquals(comment.getString().getString(), "evgeniy:\npoi test");
- assertEquals(comment.getColumn(), 1);
- assertEquals(comment.getRow(), 2);
- wb.close();
- }
-
- @Test
- void findComments() throws IOException{
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
-
- HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor());
- HSSFRow row = sh.createRow(5);
- HSSFCell cell = row.createCell(4);
- cell.setCellComment(comment);
-
- assertNotNull(sh.findCellComment(5, 4));
- assertNull(sh.findCellComment(5, 5));
-
- HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sh = wbBack.getSheetAt(0);
-
- assertNotNull(sh.findCellComment(5, 4));
- assertNull(sh.findCellComment(5, 5));
-
- wb.close();
- wbBack.close();
- }
-
- @Test
- void initState() throws IOException{
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
-
- EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch);
- assertEquals(agg.getTailRecords().size(), 0);
-
- HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor());
- assertEquals(agg.getTailRecords().size(), 1);
-
- HSSFSimpleShape shape = patriarch.createSimpleShape(new HSSFClientAnchor());
- assertNotNull(shape);
-
- assertEquals(comment.getOptRecord().getEscherProperties().size(), 10);
-
- wb.close();
- }
-
- @Test
- void shapeId() throws IOException{
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
-
- HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor());
-
- comment.setShapeId(2024);
-
- assertEquals(comment.getShapeId(), 2024);
-
- CommonObjectDataSubRecord cod = (CommonObjectDataSubRecord) comment.getObjRecord().getSubRecords().get(0);
- assertEquals(2024, cod.getObjectId());
- EscherSpRecord spRecord = (EscherSpRecord) comment.getEscherContainer().getChild(0);
- assertEquals(2024, spRecord.getShapeId(), 2024);
- assertEquals(2024, comment.getShapeId(), 2024);
- assertEquals(2024, comment.getNoteRecord().getShapeId());
-
- wb.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java
deleted file mode 100644
index b6a472ad38..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.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.hssf.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.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.util.HSSFColor;
-import org.apache.poi.ss.usermodel.BaseTestConditionalFormatting;
-import org.apache.poi.ss.usermodel.Color;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.SheetConditionalFormatting;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.junit.jupiter.api.Test;
-
-/**
- * HSSF-specific Conditional Formatting tests
- */
-final class TestHSSFConditionalFormatting extends BaseTestConditionalFormatting {
- public TestHSSFConditionalFormatting(){
- super(HSSFITestDataProvider.instance);
- }
- @Override
- protected void assertColor(String hexExpected, Color actual) {
- assertNotNull(actual, "Colour must be given");
- if (actual instanceof HSSFColor) {
- HSSFColor colour = (HSSFColor)actual;
- assertEquals(hexExpected, colour.getHexString());
- } else {
- HSSFExtendedColor colour = (HSSFExtendedColor)actual;
- if (hexExpected.length() == 8) {
- assertEquals(hexExpected, colour.getARGBHex());
- } else {
- assertEquals(hexExpected, colour.getARGBHex().substring(2));
- }
- }
- }
-
- @Test
- void testRead() throws IOException {
- testRead("WithConditionalFormatting.xls");
- }
-
- @Test
- void testReadOffice2007() throws IOException {
- testReadOffice2007("NewStyleConditionalFormattings.xls");
- }
-
- @Test
- void test53691() throws IOException {
- SheetConditionalFormatting cf;
- final Workbook wb = HSSFITestDataProvider.instance.openSampleWorkbook("53691.xls");
- /*
- FileInputStream s = new FileInputStream("C:\\temp\\53691bbadfixed.xls");
- try {
- wb = new HSSFWorkbook(s);
- } finally {
- s.close();
- }
-
- wb.removeSheetAt(1);*/
-
- // initially it is good
- writeTemp53691(wb, "agood");
-
- // clone sheet corrupts it
- Sheet sheet = wb.cloneSheet(0);
- writeTemp53691(wb, "bbad");
-
- // removing the sheet makes it good again
- wb.removeSheetAt(wb.getSheetIndex(sheet));
- writeTemp53691(wb, "cgood");
-
- // cloning again and removing the conditional formatting makes it good again
- sheet = wb.cloneSheet(0);
- removeConditionalFormatting(sheet);
- writeTemp53691(wb, "dgood");
-
- // cloning the conditional formatting manually makes it bad again
- cf = sheet.getSheetConditionalFormatting();
- SheetConditionalFormatting scf = wb.getSheetAt(0).getSheetConditionalFormatting();
- for (int j = 0; j < scf.getNumConditionalFormattings(); j++) {
- cf.addConditionalFormatting(scf.getConditionalFormattingAt(j));
- }
- writeTemp53691(wb, "ebad");
-
- // remove all conditional formatting for comparing BIFF output
- removeConditionalFormatting(sheet);
- removeConditionalFormatting(wb.getSheetAt(0));
- writeTemp53691(wb, "fgood");
-
- wb.close();
- }
-
- private void removeConditionalFormatting(Sheet sheet) {
- SheetConditionalFormatting cf = sheet.getSheetConditionalFormatting();
- for (int j = 0; j < cf.getNumConditionalFormattings(); j++) {
- cf.removeConditionalFormatting(j);
- }
- }
-
- private void writeTemp53691(Workbook wb, @SuppressWarnings("UnusedParameters") String suffix) throws IOException {
- // assert that we can write/read it in memory
- Workbook wbBack = HSSFITestDataProvider.instance.writeOutAndReadBack(wb);
- assertNotNull(wbBack);
- wbBack.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java
deleted file mode 100644
index 98195b11d5..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.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.hssf.usermodel;
-
-import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-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.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link HSSFDataFormat}
- */
-final class TestHSSFDataFormat extends BaseTestDataFormat {
-
- public TestHSSFDataFormat() {
- super(HSSFITestDataProvider.instance);
- }
-
- /**
- * Bug 51378: getDataFormatString method call crashes when reading the test file
- */
- @Test
- void test51378() throws IOException {
- List expNull = Arrays.asList( "0-3-0","0-43-11" );
- try (HSSFWorkbook wb = openSampleWorkbook("12561-1.xls")) {
- for (Sheet sheet : wb) {
- for (Row row : sheet) {
- for (Cell cell : row) {
- CellStyle style = cell.getCellStyle();
- assertNotNull(style);
- String coord = wb.getSheetIndex(sheet)+"-"+cell.getRowIndex()+"-"+cell.getColumnIndex();
- String fmt = style.getDataFormatString();
- assertEquals(expNull.contains(coord), fmt == null, coord+" unexpected");
- }
- }
- }
- }
- }
-
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java
deleted file mode 100644
index 4e2843ad22..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java
+++ /dev/null
@@ -1,459 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.text.DecimalFormat;
-import java.text.DecimalFormatSymbols;
-import java.text.Format;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.TimeZone;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.CellType;
-import org.apache.poi.ss.usermodel.DateUtil;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-
-/**
- * Unit tests for HSSFDataFormatter.java
- */
-public final class TestHSSFDataFormatter {
- private static TimeZone userTimeZone;
-
- @BeforeAll
- public static void setTimeZone() {
- userTimeZone = LocaleUtil.getUserTimeZone();
- LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET"));
- LocaleUtil.setUserLocale(Locale.US);
- }
-
- @AfterAll
- public static void resetTimeZone() {
- LocaleUtil.setUserTimeZone(userTimeZone);
- LocaleUtil.setUserLocale(Locale.ROOT);
- }
-
-
- private final HSSFDataFormatter formatter;
- private final HSSFWorkbook wb;
-
- public TestHSSFDataFormatter() {
- // create the formatter to test
- formatter = new HSSFDataFormatter();
-
- // create a workbook to test with
- wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet();
- HSSFDataFormat format = wb.createDataFormat();
-
- // create a row and put some cells in it
- HSSFRow row = sheet.createRow(0);
-
- // date value for July 8 1901 1:19 PM
- double dateNum = 555.555;
- // date value for July 8 1901 11:23 AM
- double timeNum = 555.47431;
-
- //valid date formats -- all should have "Jul" in output
- String[] goodDatePatterns = {
- "[$-F800]dddd\\,\\ mmmm\\ dd\\,\\ yyyy",
- "mmm/d/yy\\ h:mm PM;@",
- "mmmm/d/yy\\ h:mm;@",
- "mmmm/d;@",
- "mmmm/d/yy;@",
- "mmm/dd/yy;@",
- "[$-409]d\\-mmm;@",
- "[$-409]d\\-mmm\\-yy;@",
- "[$-409]dd\\-mmm\\-yy;@",
- "[$-409]mmm\\-yy;@",
- "[$-409]mmmm\\-yy;@",
- "[$-409]mmmm\\ d\\,\\ yyyy;@",
- "[$-409]mmm/d/yy\\ h:mm:ss;@",
- "[$-409]mmmm/d/yy\\ h:mm:ss am;@",
- "[$-409]mmmmm;@",
- "[$-409]mmmmm\\-yy;@",
- "mmmm/d/yyyy;@",
- "[$-409]d\\-mmm\\-yyyy;@",
- "[$-409]d\\-mmm;[$-3]d\\-mmm;@", // international three-part
- "[$-41f]d\\-mmm;[$-41f]d\\-mmm;@", // turkish international three-part
- "[$-F40f]d\\-mmm;[$-F40f]d\\-mmm;@", // custom international three-part
- "[$-F40f]d\\-mmm;[$-F40f]d\\-mmm;0;@" // custom international four-part
- };
-
- //valid time formats - all should have 11:23 in output
- String[] goodTimePatterns = {
- "HH:MM",
- "HH:MM:SS",
- "HH:MM;HH:MM;HH:MM",
- // This is fun - blue if positive time,
- // red if negative time or green for zero!
- "[BLUE]HH:MM;[RED]HH:MM;[GREEN]HH:MM",
- "yyyy-mm-dd hh:mm",
- "yyyy-mm-dd hh:mm:ss",
- };
-
- // valid number formats
- String[] goodNumPatterns = {
- "#,##0.0000",
- "#,##0;[Red]#,##0",
- "(#,##0.00_);(#,##0.00)",
- "($#,##0.00_);[Red]($#,##0.00)",
- "$#,##0.00",
- "[$-809]#,##0.00", // international format
- "[$-2]#,##0.00", // international format
- "[$-041f]#,##0.00", // international format
- "0000.00000%",
- "0.000E+00",
- "0.00E+00",
- "[BLACK]0.00;[COLOR 5]##.##",
- "[>999999]#,,\"M\";[>999]#,\"K\";#", // num/K/M
- "[>999999]#.000,,\"M\";[>999]#.000,\"K\";#.000", // with decimals
- "[$-809]#,##0.00;[$-809]#,##0.00", // two-part international format
- "[$-809]#,##0.00;[$-809]#,##0.00;0", // three-part international format
- "[$-809]#,##0.00;[$-809]#,##0.00;0;@", // four-part international format
- };
-
- // invalid date formats -- will throw exception in DecimalFormat ctor
- String[] badNumPatterns = {
- "#,#$'#0.0000",
- "'#','#ABC#0;##,##0",
- "000 '123 4'5'6 000",
- "#''0#0'1#10L16EE"
- };
-
- // create cells with good date patterns
- for (int i = 0; i < goodDatePatterns.length; i++) {
- HSSFCell cell = row.createCell(i);
- cell.setCellValue(dateNum);
- HSSFCellStyle cellStyle = wb.createCellStyle();
- cellStyle.setDataFormat(format.getFormat(goodDatePatterns[i]));
- cell.setCellStyle(cellStyle);
- }
- row = sheet.createRow(1);
-
- // create cells with time patterns
- for (int i = 0; i < goodTimePatterns.length; i++) {
- HSSFCell cell = row.createCell(i);
- cell.setCellValue(timeNum);
- HSSFCellStyle cellStyle = wb.createCellStyle();
- cellStyle.setDataFormat(format.getFormat(goodTimePatterns[i]));
- cell.setCellStyle(cellStyle);
- }
- row = sheet.createRow(2);
-
- // create cells with num patterns
- for (int i = 0; i < goodNumPatterns.length; i++) {
- HSSFCell cell = row.createCell(i);
- cell.setCellValue(-1234567890.12345);
- HSSFCellStyle cellStyle = wb.createCellStyle();
- cellStyle.setDataFormat(format.getFormat(goodNumPatterns[i]));
- cell.setCellStyle(cellStyle);
- }
- row = sheet.createRow(3);
-
- // create cells with bad num patterns
- for (int i = 0; i < badNumPatterns.length; i++) {
- HSSFCell cell = row.createCell(i);
- // If the '.' is any later, ExcelGeneralNumberFormat will render an integer, as Excel does.
- cell.setCellValue(12345678.9012345);
- HSSFCellStyle cellStyle = wb.createCellStyle();
- cellStyle.setDataFormat(format.getFormat(badNumPatterns[i]));
- cell.setCellStyle(cellStyle);
- }
-
- // Built in formats
-
- { // Zip + 4 format
- row = sheet.createRow(4);
- HSSFCell cell = row.createCell(0);
- cell.setCellValue(123456789);
- HSSFCellStyle cellStyle = wb.createCellStyle();
- cellStyle.setDataFormat(format.getFormat("00000-0000"));
- cell.setCellStyle(cellStyle);
- }
-
- { // Phone number format
- row = sheet.createRow(5);
- HSSFCell cell = row.createCell(0);
- cell.setCellValue(5551234567D);
- HSSFCellStyle cellStyle = wb.createCellStyle();
- cellStyle.setDataFormat(format.getFormat("[<=9999999]###-####;(###) ###-####"));
- cell.setCellStyle(cellStyle);
- }
-
- { // SSN format
- row = sheet.createRow(6);
- HSSFCell cell = row.createCell(0);
- cell.setCellValue(444551234);
- HSSFCellStyle cellStyle = wb.createCellStyle();
- cellStyle.setDataFormat(format.getFormat("000-00-0000"));
- cell.setCellStyle(cellStyle);
- }
-
- { // formula cell
- row = sheet.createRow(7);
- HSSFCell cell = row.createCell(0);
- cell.setCellFormula("SUM(12.25,12.25)/100");
- HSSFCellStyle cellStyle = wb.createCellStyle();
- cellStyle.setDataFormat(format.getFormat("##.00%;"));
- cell.setCellStyle(cellStyle);
- }
- }
-
- /**
- * Test getting formatted values from numeric and date cells.
- */
- @Test
- void testGetFormattedCellValueHSSFCell() {
- // Valid date formats -- cell values should be date formatted & not "555.555"
- HSSFRow row = wb.getSheetAt(0).getRow(0);
- Iterator it = row.cellIterator();
- log("==== VALID DATE FORMATS ====");
- while (it.hasNext()) {
- Cell cell = it.next();
- String fmtval = formatter.formatCellValue(cell);
- log(fmtval);
-
- // should not be equal to "555.555"
- assertTrue( DateUtil.isCellDateFormatted(cell) );
- assertNotEquals(fmtval, "555.555");
-
- String fmt = cell.getCellStyle().getDataFormatString();
-
- //assert the correct month form, as in the original Excel format
- String monthPtrn = fmt.contains("mmmm") ? "MMMM" : "MMM";
- // this line is intended to compute how "July" would look like in the current locale
- SimpleDateFormat sdf = new SimpleDateFormat(monthPtrn, LocaleUtil.getUserLocale());
- sdf.setTimeZone(LocaleUtil.getUserTimeZone());
- Calendar calDef = LocaleUtil.getLocaleCalendar(2010, 6, 15, 0, 0, 0);
- String jul = sdf.format(calDef.getTime());
- // special case for MMMMM = 1st letter of month name
- if(fmt.contains("mmmmm")) {
- jul = jul.substring(0,1);
- }
- // check we found july properly
- assertTrue(fmtval.contains(jul), "Format came out incorrect - " + fmt);
- }
-
- row = wb.getSheetAt(0).getRow(1);
- it = row.cellIterator();
- log("==== VALID TIME FORMATS ====");
- while (it.hasNext()) {
- Cell cell = it.next();
- String fmt = cell.getCellStyle().getDataFormatString();
- String fmtval = formatter.formatCellValue(cell);
- log(fmtval);
-
- // should not be equal to "555.47431"
- assertTrue( DateUtil.isCellDateFormatted(cell) );
- assertNotEquals(fmtval, "555.47431");
-
- // check we found the time properly
- assertTrue(fmtval.contains("11:23"),
- "Format came out incorrect - " + fmt + " - found " + fmtval + ", but expected to find '11:23'");
- }
-
- // test number formats
- row = wb.getSheetAt(0).getRow(1);
- it = row.cellIterator();
- log("\n==== VALID NUMBER FORMATS ====");
- while (it.hasNext()) {
- HSSFCell cell = (HSSFCell) it.next();
- final String formatted = formatter.formatCellValue(cell);
- log(formatted);
-
- // should not include "12345678" - note that the input value was negative
- assertTrue(formatted != null && ! formatted.contains("12345678"));
- }
-
- // test bad number formats
- row = wb.getSheetAt(0).getRow(3);
- it = row.cellIterator();
- log("\n==== INVALID NUMBER FORMATS ====");
- while (it.hasNext()) {
- HSSFCell cell = (HSSFCell) it.next();
- log(formatter.formatCellValue(cell));
- // in some locales the the decimal delimiter is a comma, not a dot
- char decimalSeparator = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale()).getDecimalSeparator();
- assertEquals("12345678" + decimalSeparator + "9", formatter.formatCellValue(cell));
- }
-
- // test Zip+4 format
- row = wb.getSheetAt(0).getRow(4);
- HSSFCell cell = row.getCell(0);
- log("\n==== ZIP FORMAT ====");
- log(formatter.formatCellValue(cell));
- assertEquals("12345-6789", formatter.formatCellValue(cell));
-
- // test phone number format
- row = wb.getSheetAt(0).getRow(5);
- cell = row.getCell(0);
- log("\n==== PHONE FORMAT ====");
- log(formatter.formatCellValue(cell));
- assertEquals("(555) 123-4567", formatter.formatCellValue(cell));
-
- // test SSN format
- row = wb.getSheetAt(0).getRow(6);
- cell = row.getCell(0);
- log("\n==== SSN FORMAT ====");
- log(formatter.formatCellValue(cell));
- assertEquals("444-55-1234", formatter.formatCellValue(cell));
-
- // null test-- null cell should result in empty String
- assertEquals(formatter.formatCellValue(null), "");
-
- // null test-- null cell should result in empty String
- assertEquals(formatter.formatCellValue(null), "");
- }
-
- @Test
- void testGetFormattedCellValueHSSFCellHSSFFormulaEvaluator() {
- // test formula format
- HSSFRow row = wb.getSheetAt(0).getRow(7);
- HSSFCell cell = row.getCell(0);
- log("\n==== FORMULA CELL ====");
-
- // first without a formula evaluator
- log(formatter.formatCellValue(cell) + "\t (without evaluator)");
- assertEquals("SUM(12.25,12.25)/100", formatter.formatCellValue(cell));
-
- // now with a formula evaluator
- HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb);
- log(formatter.formatCellValue(cell, evaluator) + "\t\t\t (with evaluator)");
- char decimalSeparator = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale()).getDecimalSeparator();
- assertEquals("24" + decimalSeparator + "50%", formatter.formatCellValue(cell,evaluator));
-
- }
-
- /**
- * Test using a default number format. The format should be used when a
- * format pattern cannot be parsed by DecimalFormat.
- */
- @Test
- void testSetDefaultNumberFormat() {
- HSSFRow row = wb.getSheetAt(0).getRow(3);
- Iterator it = row.cellIterator();
- DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale());
- Format defaultFormat = new DecimalFormat("Balance $#,#00.00 USD;Balance -$#,#00.00 USD", dfs);
- formatter.setDefaultNumberFormat(defaultFormat);
-
- log("\n==== DEFAULT NUMBER FORMAT ====");
- while (it.hasNext()) {
- Cell cell = it.next();
- cell.setCellValue(cell.getNumericCellValue() * Math.random() / 1000000 - 1000);
- log(formatter.formatCellValue(cell));
-
- String formatted = formatter.formatCellValue(cell);
- assertTrue(formatted.startsWith("Balance "), "Doesn't start with Balance: " + formatted);
- assertTrue(formatted.endsWith(" USD"), "Doesn't end with USD: " + formatted);
- }
- }
-
- /**
- * A format of "@" means use the general format
- */
- @Test
- void testGeneralAtFormat() {
- HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("47154.xls");
- HSSFSheet sheet = workbook.getSheetAt(0);
- HSSFRow row = sheet.getRow(0);
- HSSFCell cellA1 = row.getCell(0);
-
- assertEquals(CellType.NUMERIC, cellA1.getCellType());
- assertEquals(2345.0, cellA1.getNumericCellValue(), 0.0001);
- assertEquals("@", cellA1.getCellStyle().getDataFormatString());
-
- HSSFDataFormatter f = new HSSFDataFormatter();
-
- assertEquals("2345", f.formatCellValue(cellA1));
- }
-
- /**
- * Tests various formattings of dates and numbers
- */
- @Test
- void testFromFile() {
- HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("Formatting.xls");
- HSSFSheet sheet = workbook.getSheetAt(0);
-
- HSSFDataFormatter f = new HSSFDataFormatter();
-
- // This one is one of the nasty auto-locale changing ones...
- assertEquals("dd/mm/yyyy", sheet.getRow(1).getCell(0).getStringCellValue());
- assertEquals("m/d/yy", sheet.getRow(1).getCell(1).getCellStyle().getDataFormatString());
- assertEquals("11/24/06", f.formatCellValue(sheet.getRow(1).getCell(1)));
-
- assertEquals("yyyy/mm/dd", sheet.getRow(2).getCell(0).getStringCellValue());
- assertEquals("yyyy/mm/dd", sheet.getRow(2).getCell(1).getCellStyle().getDataFormatString());
- assertEquals("2006/11/24", f.formatCellValue(sheet.getRow(2).getCell(1)));
-
- assertEquals("yyyy-mm-dd", sheet.getRow(3).getCell(0).getStringCellValue());
- assertEquals("yyyy\\-mm\\-dd", sheet.getRow(3).getCell(1).getCellStyle().getDataFormatString());
- assertEquals("2006-11-24", f.formatCellValue(sheet.getRow(3).getCell(1)));
-
- assertEquals("yy/mm/dd", sheet.getRow(4).getCell(0).getStringCellValue());
- assertEquals("yy/mm/dd", sheet.getRow(4).getCell(1).getCellStyle().getDataFormatString());
- assertEquals("06/11/24", f.formatCellValue(sheet.getRow(4).getCell(1)));
-
- // Another builtin fun one
- assertEquals("dd/mm/yy", sheet.getRow(5).getCell(0).getStringCellValue());
- assertEquals("d/m/yy;@", sheet.getRow(5).getCell(1).getCellStyle().getDataFormatString());
- assertEquals("24/11/06", f.formatCellValue(sheet.getRow(5).getCell(1)));
-
- assertEquals("dd-mm-yy", sheet.getRow(6).getCell(0).getStringCellValue());
- assertEquals("dd\\-mm\\-yy", sheet.getRow(6).getCell(1).getCellStyle().getDataFormatString());
- assertEquals("24-11-06", f.formatCellValue(sheet.getRow(6).getCell(1)));
-
-
- // Another builtin fun one
- assertEquals("nn.nn", sheet.getRow(9).getCell(0).getStringCellValue());
- assertEquals("General", sheet.getRow(9).getCell(1).getCellStyle().getDataFormatString());
- assertEquals("10.52", f.formatCellValue(sheet.getRow(9).getCell(1)));
-
- // text isn't quite the format rule...
- assertEquals("nn.nnn", sheet.getRow(10).getCell(0).getStringCellValue());
- assertEquals("0.000", sheet.getRow(10).getCell(1).getCellStyle().getDataFormatString());
- assertEquals("10.520", f.formatCellValue(sheet.getRow(10).getCell(1)));
-
- // text isn't quite the format rule...
- assertEquals("nn.n", sheet.getRow(11).getCell(0).getStringCellValue());
- assertEquals("0.0", sheet.getRow(11).getCell(1).getCellStyle().getDataFormatString());
- assertEquals("10.5", f.formatCellValue(sheet.getRow(11).getCell(1)));
-
- // text isn't quite the format rule...
- assertEquals("\u00a3nn.nn", sheet.getRow(12).getCell(0).getStringCellValue());
- assertEquals("\"\u00a3\"#,##0.00", sheet.getRow(12).getCell(1).getCellStyle().getDataFormatString());
- assertEquals("\u00a310.52", f.formatCellValue(sheet.getRow(12).getCell(1)));
- }
-
- private static void log(@SuppressWarnings("UnusedParameters") String msg) {
-// if (false) { // successful tests should be silent
-// System.out.println(msg);
-// }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java
deleted file mode 100644
index 2949dbeeee..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.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.hssf.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 java.util.TimeZone;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.InternalWorkbook;
-import org.apache.poi.ss.usermodel.DateUtil;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class TestHSSFDateUtil
- */
-class TestHSSFDateUtil {
-
- static TimeZone userTimeZone;
-
- @BeforeAll
- public static void setCEST() {
- userTimeZone = LocaleUtil.getUserTimeZone();
- LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CEST"));
- }
-
- @AfterAll
- public static void resetTimeZone() {
- LocaleUtil.setUserTimeZone(userTimeZone);
- }
-
- /**
- * Test that against a real, test file, we still do everything
- * correctly
- */
- @Test
- void onARealFile() throws IOException {
-
- HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls");
- HSSFSheet sheet = workbook.getSheetAt(0);
- InternalWorkbook wb = workbook.getWorkbook();
- assertNotNull(wb);
-
- HSSFRow row;
- HSSFCell cell;
- HSSFCellStyle style;
-
- double aug_10_2007 = 39304.0;
-
- // Should have dates in 2nd column
- // All of them are the 10th of August
- // 2 US dates, 3 UK dates
- row = sheet.getRow(0);
- cell = row.getCell(1);
- style = cell.getCellStyle();
- assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001);
- assertEquals("d-mmm-yy", style.getDataFormatString());
- assertTrue(DateUtil.isInternalDateFormat(style.getDataFormat()));
- assertTrue(DateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString()));
- assertTrue(DateUtil.isCellDateFormatted(cell));
-
- row = sheet.getRow(1);
- cell = row.getCell(1);
- style = cell.getCellStyle();
- assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001);
- assertFalse(DateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat()));
- assertTrue(DateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString()));
- assertTrue(DateUtil.isCellDateFormatted(cell));
-
- row = sheet.getRow(2);
- cell = row.getCell(1);
- style = cell.getCellStyle();
- assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001);
- assertTrue(DateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat()));
- assertTrue(DateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString()));
- assertTrue(DateUtil.isCellDateFormatted(cell));
-
- row = sheet.getRow(3);
- cell = row.getCell(1);
- style = cell.getCellStyle();
- assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001);
- assertFalse(DateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat()));
- assertTrue(DateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString()));
- assertTrue(DateUtil.isCellDateFormatted(cell));
-
- row = sheet.getRow(4);
- cell = row.getCell(1);
- style = cell.getCellStyle();
- assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001);
- assertFalse(DateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat()));
- assertTrue(DateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString()));
- assertTrue(DateUtil.isCellDateFormatted(cell));
-
- workbook.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFEvaluationSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFEvaluationSheet.java
deleted file mode 100644
index dfc64df1bb..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFEvaluationSheet.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.hssf.usermodel;
-
-import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook;
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-
-import java.io.IOException;
-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 TestHSSFEvaluationSheet extends BaseTestXEvaluationSheet {
- @Override
- protected Map.Entry getInstance() {
- HSSFSheet sheet = new HSSFWorkbook().createSheet();
- return new AbstractMap.SimpleEntry<>(sheet, new HSSFEvaluationSheet(sheet));
- }
-
- @Test
- void testMissingExternalName() throws IOException {
- try (HSSFWorkbook wb = openSampleWorkbook("external_name.xls")) {
- // this sometimes causes exceptions
- wb.getAllNames().stream().filter(n -> !n.isFunctionName()).forEach(
- n -> assertDoesNotThrow(n::getRefersToFormula)
- );
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFExternalFunctions.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFExternalFunctions.java
deleted file mode 100644
index 552e028aff..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFExternalFunctions.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.hssf.usermodel;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.ss.formula.BaseTestExternalFunctions;
-
-/**
- * Tests setting and evaluating user-defined functions in HSSF
- */
-final class TestHSSFExternalFunctions extends BaseTestExternalFunctions {
- public TestHSSFExternalFunctions() {
- super(HSSFITestDataProvider.instance, "atp.xls");
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java
deleted file mode 100644
index e4859923ff..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.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.hssf.usermodel;
-
-import java.util.stream.Stream;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.ss.usermodel.BaseTestFont;
-import org.apache.poi.ss.usermodel.Font;
-import org.junit.jupiter.params.provider.Arguments;
-
-/**
- * Tests various functionality having to do with {@link org.apache.poi.ss.usermodel.Name}.
- */
-final class TestHSSFFont extends BaseTestFont {
-
- public TestHSSFFont() {
- super(HSSFITestDataProvider.instance);
- }
-
- @SuppressWarnings("unused")
- public static Stream defaultFont() {
- return Stream.of(Arguments.of(HSSFFont.FONT_ARIAL, (short)200, Font.COLOR_NORMAL));
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java
deleted file mode 100644
index afe96936fd..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import java.io.IOException;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.NameRecord;
-import org.apache.poi.ss.formula.EvaluationCell;
-import org.apache.poi.ss.formula.EvaluationListener;
-import org.apache.poi.ss.formula.WorkbookEvaluator;
-import org.apache.poi.ss.formula.WorkbookEvaluatorTestHelper;
-import org.apache.poi.ss.formula.eval.NumberEval;
-import org.apache.poi.ss.formula.eval.ValueEval;
-import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator;
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.CellType;
-import org.apache.poi.ss.usermodel.CellValue;
-import org.junit.jupiter.api.Test;
-
-final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator {
-
- public TestHSSFFormulaEvaluator() {
- super(HSSFITestDataProvider.instance);
- }
-
- /**
- * Test that the HSSFFormulaEvaluator can evaluate simple named ranges
- * (single cells and rectangular areas)
- */
- @Test
- void testEvaluateSimple() throws IOException {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testNames.xls");
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFCell cell = sheet.getRow(8).getCell(0);
- HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
- CellValue cv = fe.evaluate(cell);
- assertEquals(CellType.NUMERIC, cv.getCellType());
- assertEquals(3.72, cv.getNumberValue(), 0.0);
- wb.close();
- }
-
- /**
- * When evaluating defined names, POI has to decide whether it is capable. Currently
- * (May2009) POI only supports simple cell and area refs.
- * The sample spreadsheet (bugzilla attachment 23508) had a name flagged as 'complex'
- * which contained a simple area ref. It is not clear what the 'complex' flag is used
- * for but POI should look elsewhere to decide whether it can evaluate the name.
- */
- @Test
- void testDefinedNameWithComplexFlag_bug47048() throws IOException {
- // Mock up a spreadsheet to match the critical details of the sample
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet("Input");
- HSSFName definedName = wb.createName();
- definedName.setNameName("Is_Multicar_Vehicle");
- definedName.setRefersToFormula("Input!$B$17:$G$17");
-
- // Set up some data and the formula
- HSSFRow row17 = sheet.createRow(16);
- row17.createCell(0).setCellValue(25.0);
- row17.createCell(1).setCellValue(1.33);
- row17.createCell(2).setCellValue(4.0);
-
- HSSFRow row = sheet.createRow(0);
- HSSFCell cellA1 = row.createCell(0);
- cellA1.setCellFormula("SUM(Is_Multicar_Vehicle)");
-
- // Set the complex flag - POI doesn't usually manipulate this flag
- NameRecord nameRec = TestHSSFName.getNameRecord(definedName);
- nameRec.setOptionFlag((short) 0x10); // 0x10 -> complex
-
- HSSFFormulaEvaluator hsf = new HSSFFormulaEvaluator(wb);
- CellValue value;
- try {
- value = hsf.evaluate(cellA1);
-
- assertEquals(CellType.NUMERIC, value.getCellType());
- assertEquals(5.33, value.getNumberValue(), 0.0);
-
- } catch (RuntimeException e) {
- if (e.getMessage().equals("Don't know how to evaluate name 'Is_Multicar_Vehicle'")) {
- fail("Identified bug 47048a");
- }
- throw e;
- } finally {
- wb.close();
- }
- }
-
- private static final class EvalCountListener extends EvaluationListener {
- private int _evalCount;
-
- public EvalCountListener() {
- _evalCount = 0;
- }
-
- @Override
- public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) {
- _evalCount++;
- }
-
- public int getEvalCount() {
- return _evalCount;
- }
- }
-
- /**
- * The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values
- */
- @Test
- void testShortCircuitIfEvaluation() throws IOException {
- // Set up a simple IF() formula that has measurable evaluation cost for its operands.
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet("Sheet1");
- HSSFRow row = sheet.createRow(0);
- HSSFCell cellA1 = row.createCell(0);
- cellA1.setCellFormula("if(B1,C1,D1+E1+F1)");
- // populate cells B1..F1 with simple formulas instead of plain values so we can use
- // EvaluationListener to check which parts of the first formula get evaluated
- for (int i = 1; i < 6; i++) {
- // formulas are just literal constants "1".."5"
- row.createCell(i).setCellFormula(String.valueOf(i));
- }
-
- EvalCountListener evalListener = new EvalCountListener();
- WorkbookEvaluator evaluator = WorkbookEvaluatorTestHelper.createEvaluator(wb, evalListener);
- ValueEval ve = evaluator.evaluate(HSSFEvaluationTestHelper.wrapCell(cellA1));
- int evalCount = evalListener.getEvalCount();
- // Without short-circuit-if evaluation, evaluating cell 'A1' takes 3 extra evaluations (for D1,E1,F1)
- assertNotEquals(6, evalCount, "Identifed bug 48195 - Formula evaluator should short-circuit IF() calculations.");
- assertEquals(3, evalCount);
- assertEquals(2.0, ((NumberEval) ve).getNumberValue(), 0D);
- }
- }
-
- /**
- * Ensures that we can handle NameXPtgs in the formulas
- * we parse.
- */
- @Test
- void testXRefs() throws IOException {
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("XRefCalc.xls");
- HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook("XRefCalcData.xls")) {
- Cell cell;
-
- // VLookup on a name in another file
- cell = wb1.getSheetAt(0).getRow(1).getCell(2);
- assertEquals(CellType.FORMULA, cell.getCellType());
- assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType());
- assertEquals(12.30, cell.getNumericCellValue(), 0.0001);
- // WARNING - this is wrong!
- // The file name should be showing, but bug #45970 is fixed
- // we seem to loose it
- assertEquals("VLOOKUP(PART,COSTS,2,FALSE)", cell.getCellFormula());
-
-
- // Simple reference to a name in another file
- cell = wb1.getSheetAt(0).getRow(1).getCell(4);
- assertEquals(CellType.FORMULA, cell.getCellType());
- assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType());
- assertEquals(36.90, cell.getNumericCellValue(), 0.0001);
- // TODO Correct this!
- // The file name should be shown too, see bug #56742
- assertEquals("Cost*Markup_Cost", cell.getCellFormula());
-
-
- // Evaluate the cells
- HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb1);
- HSSFFormulaEvaluator.setupEnvironment(
- new String[]{"XRefCalc.xls", "XRefCalcData.xls"},
- new HSSFFormulaEvaluator[]{
- eval,
- new HSSFFormulaEvaluator(wb2)
- }
- );
- eval.evaluateFormulaCell(
- wb1.getSheetAt(0).getRow(1).getCell(2)
- );
- eval.evaluateFormulaCell(
- wb1.getSheetAt(0).getRow(1).getCell(4)
- );
-
-
- // Re-check VLOOKUP one
- cell = wb1.getSheetAt(0).getRow(1).getCell(2);
- assertEquals(CellType.FORMULA, cell.getCellType());
- assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType());
- assertEquals(12.30, cell.getNumericCellValue(), 0.0001);
-
- // Re-check ref one
- cell = wb1.getSheetAt(0).getRow(1).getCell(4);
- assertEquals(CellType.FORMULA, cell.getCellType());
- assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultType());
- assertEquals(36.90, cell.getNumericCellValue(), 0.0001);
-
-
- // Add a formula that refers to one of the existing external workbooks
- cell = wb1.getSheetAt(0).getRow(1).createCell(40);
- cell.setCellFormula("Cost*[XRefCalcData.xls]MarkupSheet!$B$1");
-
- // Check is was stored correctly
- assertEquals("Cost*[XRefCalcData.xls]MarkupSheet!$B$1", cell.getCellFormula());
-
- // Check it evaluates correctly
- eval.evaluateFormulaCell(cell);
- assertEquals(24.60 * 1.8, cell.getNumericCellValue(), 0);
-
- // Try to add a formula for a new external workbook, won't be allowed to start
- cell = wb1.getSheetAt(0).getRow(1).createCell(42);
- final Cell cell2 = cell;
- assertThrows(Exception.class, () -> cell2.setCellFormula("[alt.xls]Sheet0!$A$1"),
- "New workbook not linked, shouldn't be able to add");
-
- // Link our new workbook
- try (HSSFWorkbook wb3 = new HSSFWorkbook()) {
- wb3.createSheet().createRow(0).createCell(0).setCellValue("In another workbook");
- assertEquals(2, wb1.linkExternalWorkbook("alt.xls", wb3));
-
- // Now add a formula that refers to our new workbook
- cell.setCellFormula("[alt.xls]Sheet0!$A$1");
- assertEquals("[alt.xls]Sheet0!$A$1", cell.getCellFormula());
-
- HSSFFormulaEvaluator eval2 = eval;
- assertThrows(Exception.class, () -> eval2.evaluate(cell2),
- "No cached value and no link to workbook, shouldn't evaluate");
-
- // Add a link, check it does
- HSSFFormulaEvaluator.setupEnvironment(
- new String[]{"XRefCalc.xls", "XRefCalcData.xls", "alt.xls"},
- new HSSFFormulaEvaluator[]{
- eval,
- new HSSFFormulaEvaluator(wb2),
- new HSSFFormulaEvaluator(wb3)
- }
- );
- eval.evaluateFormulaCell(cell);
- assertEquals("In another workbook", cell.getStringCellValue());
-
-
- // Save and re-load
- try (HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
- eval = new HSSFFormulaEvaluator(wb4);
- HSSFFormulaEvaluator.setupEnvironment(
- new String[]{"XRefCalc.xls", "XRefCalcData.xls", "alt.xls"},
- new HSSFFormulaEvaluator[]{
- eval,
- new HSSFFormulaEvaluator(wb2),
- new HSSFFormulaEvaluator(wb3)
- }
- );
-
- // Check the one referring to the previously existing workbook behaves
- cell = wb4.getSheetAt(0).getRow(1).getCell(40);
- assertEquals("Cost*[XRefCalcData.xls]MarkupSheet!$B$1", cell.getCellFormula());
- eval.evaluateFormulaCell(cell);
- assertEquals(24.60 * 1.8, cell.getNumericCellValue(), 0);
-
- // Now check the newly added reference
- cell = wb4.getSheetAt(0).getRow(1).getCell(42);
- assertEquals("[alt.xls]Sheet0!$A$1", cell.getCellFormula());
- eval.evaluateFormulaCell(cell);
- assertEquals("In another workbook", cell.getStringCellValue());
- }
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java
deleted file mode 100644
index a104bba25f..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.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.hssf.usermodel;
-
-import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.IOException;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link HSSFHeader} / {@link HSSFFooter}
- */
-final class TestHSSFHeaderFooter {
-
- /**
- * Tests that get header retrieves the proper values.
- */
- @Test
- void testRetrieveCorrectHeader() throws IOException {
-
- try (HSSFWorkbook wb = openSampleWorkbook("EmbeddedChartHeaderTest.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
- HSSFHeader head = s.getHeader();
-
- assertEquals("Top Left", head.getLeft());
- assertEquals("Top Center", head.getCenter());
- assertEquals("Top Right", head.getRight());
- }
- }
-
- @Test
- void testSpecialChars() {
- assertEquals("&U", HSSFHeader.startUnderline());
- assertEquals("&U", HSSFHeader.endUnderline());
- assertEquals("&P", HSSFHeader.page());
-
- assertEquals("&22", HSSFFooter.fontSize((short)22));
- assertEquals("&\"Arial,bold\"", HSSFFooter.font("Arial", "bold"));
- }
-
- @Test
- void testStripFields() throws IOException {
- 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, HSSFHeader.stripFields(simple));
- assertEquals(simple, HSSFHeader.stripFields(withPage));
- assertEquals(simple, HSSFHeader.stripFields(withLots));
- assertEquals(simple, HSSFHeader.stripFields(withFont));
- assertEquals(simple + "&&", HSSFHeader.stripFields(withOtherAnds));
- assertEquals(simple + "&a&b", HSSFHeader.stripFields(withOtherAnds2));
-
- // Now test the default strip flag
- try (HSSFWorkbook wb = openSampleWorkbook("EmbeddedChartHeaderTest.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
- HSSFHeader head = s.getHeader();
-
- assertEquals("Top Left", head.getLeft());
- assertEquals("Top Center", head.getCenter());
- assertEquals("Top Right", head.getRight());
-
- head.setLeft("Top &P&F&D Left");
- assertEquals("Top &P&F&D Left", head.getLeft());
-
- assertEquals("Top Left", HeaderFooter.stripFields(head.getLeft()));
-
- // Now even more complex
- head.setCenter("HEADER TEXT &P&N&D&T&Z&F&F&A&G&X END");
- assertEquals("HEADER TEXT END", HeaderFooter.stripFields(head.getCenter()));
- }
- }
-
- /**
- * Tests that get header retrieves the proper values.
- */
- @Test
- void testRetrieveCorrectFooter() throws IOException {
- try (HSSFWorkbook wb = openSampleWorkbook("EmbeddedChartHeaderTest.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
- HSSFFooter foot = s.getFooter();
-
- assertEquals("Bottom Left", foot.getLeft());
- assertEquals("Bottom Center", foot.getCenter());
- assertEquals("Bottom Right", foot.getRight());
- }
- }
-
- /**
- * Testcase for Bug 17039 HSSFHeader does not support DBCS
- */
- @Test
- void testHeaderHas16bitCharacter() throws IOException {
- try (HSSFWorkbook b = new HSSFWorkbook()) {
- HSSFSheet s = b.createSheet("Test");
- HSSFHeader h = s.getHeader();
- h.setLeft("\u0391");
- h.setCenter("\u0392");
- h.setRight("\u0393");
-
- try (HSSFWorkbook b2 = HSSFTestDataSamples.writeOutAndReadBack(b)) {
- HSSFHeader h2 = b2.getSheet("Test").getHeader();
-
- assertEquals(h2.getLeft(), "\u0391");
- assertEquals(h2.getCenter(), "\u0392");
- assertEquals(h2.getRight(), "\u0393");
- }
- }
- }
-
- /**
- * Testcase for Bug 17039 HSSFFooter does not support DBCS
- */
- @Test
- void testFooterHas16bitCharacter() throws IOException {
- try (HSSFWorkbook b = new HSSFWorkbook()) {
- HSSFSheet s = b.createSheet("Test");
- HSSFFooter f = s.getFooter();
- f.setLeft("\u0391");
- f.setCenter("\u0392");
- f.setRight("\u0393");
-
- try (HSSFWorkbook b2 = HSSFTestDataSamples.writeOutAndReadBack(b)) {
- HSSFFooter f2 = b2.getSheet("Test").getFooter();
-
- assertEquals(f2.getLeft(), "\u0391");
- assertEquals(f2.getCenter(), "\u0392");
- assertEquals(f2.getRight(), "\u0393");
- }
- }
- }
-
- @Test
- void testReadDBCSHeaderFooter() throws IOException {
- try (HSSFWorkbook wb = openSampleWorkbook("DBCSHeader.xls")) {
- HSSFSheet s = wb.getSheetAt(0);
- HSSFHeader h = s.getHeader();
- assertEquals(h.getLeft(), "\u090f\u0915", "Header Left");
- assertEquals(h.getCenter(), "\u0939\u094b\u0917\u093e", "Header Center");
- assertEquals(h.getRight(), "\u091c\u093e", "Header Right");
-
- HSSFFooter f = s.getFooter();
- assertEquals(f.getLeft(), "\u091c\u093e", "Footer Left");
- assertEquals(f.getCenter(), "\u091c\u093e", "Footer Center");
- assertEquals(f.getRight(), "\u091c\u093e", "Footer Right");
- }
- }
-
- /**
- * Excel tolerates files with missing HEADER/FOOTER records. POI should do the same.
- */
- @Test
- void testMissingHeaderFooterRecord_bug47244() throws IOException {
- // noHeaderFooter47244.xls was created by a slightly modified POI
- // which omitted the HEADER/FOOTER records
- try (HSSFWorkbook wb = openSampleWorkbook("noHeaderFooter47244.xls")) {
- HSSFSheet sheet = wb.getSheetAt(0);
- // bug 47244a - NullPointerException
- HSSFFooter footer = sheet.getFooter();
- assertEquals("", footer.getRawText());
- HSSFHeader header = sheet.getHeader();
- assertEquals("", header.getRawText());
-
- // make sure header / footer is properly linked to underlying data
- HSSFHeader header2 = sheet.getHeader();
- header.setCenter("foo");
- assertEquals("foo", header2.getCenter());
-
- HSSFFooter footer2 = sheet.getFooter();
- footer.setCenter("bar");
- assertEquals("bar", footer2.getCenter());
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java
deleted file mode 100644
index 67cb04010d..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.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.common.usermodel.HyperlinkType;
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.ss.usermodel.BaseTestHyperlink;
-import org.apache.poi.ss.usermodel.Hyperlink;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests HSSFHyperlink.
- *
- * @author Yegor Kozlov
- */
-final class TestHSSFHyperlink extends BaseTestHyperlink {
-
- public TestHSSFHyperlink() {
- super(HSSFITestDataProvider.instance);
- }
- /**
- * Test that we can read hyperlinks.
- */
- @Test
- void testRead() {
-
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
-
- HSSFSheet sheet;
- HSSFCell cell;
- HSSFHyperlink link;
-
- sheet = wb.getSheet("WebLinks");
- cell = sheet.getRow(4).getCell(0);
- link = cell.getHyperlink();
- assertNotNull(link);
- assertEquals("POI", link.getLabel());
- assertEquals("POI", cell.getRichStringCellValue().getString());
- assertEquals("http://poi.apache.org/", link.getAddress());
- assertEquals(HyperlinkType.URL, link.getType());
-
- cell = sheet.getRow(8).getCell(0);
- link = cell.getHyperlink();
- assertNotNull(link);
- assertEquals("HSSF", link.getLabel());
- assertEquals("HSSF", cell.getRichStringCellValue().getString());
- assertEquals("http://poi.apache.org/hssf/", link.getAddress());
- assertEquals(HyperlinkType.URL, link.getType());
-
- sheet = wb.getSheet("Emails");
- cell = sheet.getRow(4).getCell(0);
- link = cell.getHyperlink();
- assertNotNull(link);
- assertEquals("dev", link.getLabel());
- assertEquals("dev", cell.getRichStringCellValue().getString());
- assertEquals("mailto:dev@poi.apache.org", link.getAddress());
- assertEquals(HyperlinkType.EMAIL, link.getType());
-
- sheet = wb.getSheet("Internal");
- cell = sheet.getRow(4).getCell(0);
- link = cell.getHyperlink();
- assertNotNull(link);
- assertEquals("Link To First Sheet", link.getLabel());
- assertEquals("Link To First Sheet", cell.getRichStringCellValue().getString());
- assertEquals("WebLinks!A1", link.getTextMark());
- assertEquals("WebLinks!A1", link.getAddress());
- assertEquals(HyperlinkType.DOCUMENT, link.getType());
- }
-
- @Test
- void testModify() {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
-
- HSSFSheet sheet;
- HSSFCell cell;
- HSSFHyperlink link;
-
- sheet = wb.getSheet("WebLinks");
- cell = sheet.getRow(4).getCell(0);
- link = cell.getHyperlink();
- //modify the link
- link.setAddress("www.apache.org");
-
- wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sheet = wb.getSheet("WebLinks");
- cell = sheet.getRow(4).getCell(0);
- link = cell.getHyperlink();
- assertNotNull(link);
- assertEquals("www.apache.org", link.getAddress());
-
- }
-
- /**
- * HSSF-specific ways of creating links to a place in workbook.
- * You can set the target in two ways:
- * link.setTextMark("'Target Sheet-1'!A1"); //HSSF-specific
- * or
- * link.setAddress("'Target Sheet-1'!A1"); //common between XSSF and HSSF
- * @throws IOException
- */
- @Test
- void testCreateDocumentLink() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- //link to a place in this workbook
- HSSFHyperlink link;
- HSSFCell cell;
- HSSFSheet sheet = wb.createSheet("Hyperlinks");
-
- //create a target sheet and cell
- HSSFSheet sheet2 = wb.createSheet("Target Sheet");
- sheet2.createRow(0).createCell(0).setCellValue("Target Cell");
-
- //cell A1 has a link to 'Target Sheet-1'!A1
- cell = sheet.createRow(0).createCell(0);
- cell.setCellValue("Worksheet Link");
- link = new HSSFHyperlink(HyperlinkType.DOCUMENT);
- link.setTextMark("'Target Sheet'!A1");
- cell.setHyperlink(link);
-
- //cell B1 has a link to cell A1 on the same sheet
- cell = sheet.createRow(1).createCell(0);
- cell.setCellValue("Worksheet Link");
- link = new HSSFHyperlink(HyperlinkType.DOCUMENT);
- link.setAddress("'Hyperlinks'!A1");
- cell.setHyperlink(link);
-
- HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
- wb.close();
-
- sheet = wbBack.getSheet("Hyperlinks");
-
- cell = sheet.getRow(0).getCell(0);
- link = cell.getHyperlink();
- assertNotNull(link);
- assertEquals("'Target Sheet'!A1", link.getTextMark());
- assertEquals("'Target Sheet'!A1", link.getAddress());
-
- cell = sheet.getRow(1).getCell(0);
- link = cell.getHyperlink();
- assertNotNull(link);
- assertEquals("'Hyperlinks'!A1", link.getTextMark());
- assertEquals("'Hyperlinks'!A1", link.getAddress());
-
- wbBack.close();
- }
-
- @Test
- void testCloneSheet() {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls");
-
- HSSFCell cell;
- HSSFHyperlink link;
-
- HSSFSheet sheet = wb.cloneSheet(0);
-
- cell = sheet.getRow(4).getCell(0);
- link = cell.getHyperlink();
- assertNotNull(link);
- assertEquals("http://poi.apache.org/", link.getAddress());
-
- cell = sheet.getRow(8).getCell(0);
- link = cell.getHyperlink();
- assertNotNull(link);
- assertEquals("http://poi.apache.org/hssf/", link.getAddress());
- }
-
- @Test
- void testCreate() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- HSSFHyperlink link;
- HSSFCell cell;
- HSSFSheet sheet = wb.createSheet("Hyperlinks");
-
- cell = sheet.createRow(1).createCell(0);
- cell.setCellValue("File Link");
- link = new HSSFHyperlink(HyperlinkType.FILE);
- link.setAddress("testfolder\\test.PDF");
- cell.setHyperlink(link);
-
- HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
-
- wb.close();
-
- sheet = wbBack.getSheet("Hyperlinks");
-
- cell = sheet.getRow(1).getCell(0);
- link = cell.getHyperlink();
- assertNotNull(link);
- assertEquals("testfolder\\test.PDF", link.getAddress());
-
- wbBack.close();
- }
-
- /**
- * Test that HSSFSheet#shiftRows moves hyperlinks,
- * see bugs #46445 and #29957
- */
- @Test
- void testShiftRows(){
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("46445.xls");
-
-
- HSSFSheet sheet = wb.getSheetAt(0);
-
- //verify existing hyperlink in A3
- HSSFCell cell1 = sheet.getRow(2).getCell(0);
- HSSFHyperlink link1 = cell1.getHyperlink();
- assertNotNull(link1);
- assertEquals(2, link1.getFirstRow());
- assertEquals(2, link1.getLastRow());
-
- //assign a hyperlink to A4
- HSSFHyperlink link2 = new HSSFHyperlink(HyperlinkType.DOCUMENT);
- link2.setAddress("Sheet2!A2");
- HSSFCell cell2 = sheet.getRow(3).getCell(0);
- cell2.setHyperlink(link2);
- assertEquals(3, link2.getFirstRow());
- assertEquals(3, link2.getLastRow());
-
- //move the 3rd row two rows down
- sheet.shiftRows(sheet.getFirstRowNum(), sheet.getLastRowNum(), 2);
-
- //cells A3 and A4 don't contain hyperlinks anymore
- assertNull(sheet.getRow(2).getCell(0).getHyperlink());
- assertNull(sheet.getRow(3).getCell(0).getHyperlink());
-
- //the first hyperlink now belongs to A5
- HSSFHyperlink link1_shifted = sheet.getRow(2+2).getCell(0).getHyperlink();
- assertNotNull(link1_shifted);
- assertEquals(4, link1_shifted.getFirstRow());
- assertEquals(4, link1_shifted.getLastRow());
-
- //the second hyperlink now belongs to A6
- HSSFHyperlink link2_shifted = sheet.getRow(3+2).getCell(0).getHyperlink();
- assertNotNull(link2_shifted);
- assertEquals(5, link2_shifted.getFirstRow());
- assertEquals(5, link2_shifted.getLastRow());
- }
-
- @Override
- public HSSFHyperlink copyHyperlink(Hyperlink link) {
- return new HSSFHyperlink(link);
- }
-
- /*
- @Test
- void testCopyXSSFHyperlink() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFCreationHelper helper = wb.getCreationHelper();
- XSSFHyperlink xlink = helper.createHyperlink(Hyperlink.LINK_URL);
- xlink.setAddress("http://poi.apache.org/");
- xlink.setCellReference("D3");
- xlink.setTooltip("tooltip");
- HSSFHyperlink hlink = new HSSFHyperlink(xlink);
-
- assertEquals("http://poi.apache.org/", hlink.getAddress());
- assertEquals("D3", new CellReference(hlink.getFirstRow(), hlink.getFirstColumn()).formatAsString());
- // Are HSSFHyperlink.label and XSSFHyperlink.tooltip the same? If so, perhaps one of these needs renamed for a consistent Hyperlink interface
- // assertEquals("tooltip", hlink.getLabel());
-
- wb.close();
- }*/
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java
deleted file mode 100644
index e3e6cea444..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.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 org.apache.poi.POITestCase;
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.HSSFFormulaParser;
-import org.apache.poi.hssf.record.NameRecord;
-import org.apache.poi.ss.formula.FormulaType;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.usermodel.BaseTestNamedRange;
-import org.apache.poi.ss.usermodel.Name;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests various functionality having to do with {@link org.apache.poi.ss.usermodel.Name}.
- */
-public final class TestHSSFName extends BaseTestNamedRange {
-
- /**
- * For manipulating the internals of {@link HSSFName} during testing.
- * Some tests need a {@link NameRecord} with unusual state, not normally producible by POI.
- * This method achieves the aims at low cost without augmenting the POI usermodel api.
- * @return a reference to the wrapped {@link NameRecord}
- */
- public static NameRecord getNameRecord(HSSFName definedName) {
- return POITestCase.getFieldValue(HSSFName.class, definedName, NameRecord.class, "_definedNameRec");
- }
-
- public TestHSSFName() {
- super(HSSFITestDataProvider.instance);
- }
-
- @Test
- void testRepeatingRowsAndColumnsNames() throws Exception {
- // First test that setting RR&C for same sheet more than once only creates a
- // single Print_Titles built-in record
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet("FirstSheet");
-
- // set repeating rows and columns twice for the first sheet
- CellRangeAddress cra = CellRangeAddress.valueOf("A1:A3");
- for (int i = 0; i < 2; i++) {
- sheet.setRepeatingColumns(cra);
- sheet.setRepeatingRows(cra);
- sheet.createFreezePane(0, 3);
- }
- assertEquals(1, wb.getNumberOfNames());
- HSSFName nr1 = wb.getNameAt(0);
-
- assertEquals("Print_Titles", nr1.getNameName());
- // TODO - full column references not rendering properly, absolute markers not present either
- // assertEquals("FirstSheet!$A:$A,FirstSheet!$1:$3", nr1.getRefersToFormula());
- assertEquals("FirstSheet!A:A,FirstSheet!$A$1:$IV$3", nr1.getRefersToFormula());
-
- // Save and re-open
- HSSFWorkbook nwb = HSSFTestDataSamples.writeOutAndReadBack(wb);
- wb.close();
-
- assertEquals(1, nwb.getNumberOfNames());
- nr1 = nwb.getNameAt(0);
-
- assertEquals("Print_Titles", nr1.getNameName());
- assertEquals("FirstSheet!A:A,FirstSheet!$A$1:$IV$3", nr1.getRefersToFormula());
-
- // check that setting RR&C on a second sheet causes a new Print_Titles built-in
- // name to be created
- sheet = nwb.createSheet("SecondSheet");
- cra = CellRangeAddress.valueOf("B1:C1");
- sheet.setRepeatingColumns(cra);
- sheet.setRepeatingRows(cra);
-
- assertEquals(2, nwb.getNumberOfNames());
- HSSFName nr2 = nwb.getNameAt(1);
-
- assertEquals("Print_Titles", nr2.getNameName());
- assertEquals("SecondSheet!B:C,SecondSheet!$A$1:$IV$1", nr2.getRefersToFormula());
-
- nwb.close();
- }
-
- @Test
- void testNamedRange() throws Exception {
- HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls");
-
- //Creating new Named Range
- HSSFName newNamedRange = wb1.createName();
-
- //Getting Sheet Name for the reference
- String sheetName = wb1.getSheetName(0);
-
- //Setting its name
- newNamedRange.setNameName("RangeTest");
- //Setting its reference
- newNamedRange.setRefersToFormula(sheetName + "!$D$4:$E$8");
-
- //Getting NAmed Range
- HSSFName namedRange1 = wb1.getNameAt(0);
- //Getting it sheet name
- sheetName = namedRange1.getSheetName();
- assertNotNull(sheetName);
-
- // sanity check
- SanityChecker c = new SanityChecker();
- c.checkHSSFWorkbook(wb1);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- HSSFName nm = wb2.getNameAt(wb2.getNameIndex("RangeTest"));
- assertEquals("RangeTest", nm.getNameName(), "Name is " + nm.getNameName());
- assertEquals(wb2.getSheetName(0)+"!$D$4:$E$8", nm.getRefersToFormula());
- wb2.close();
- wb1.close();
- }
-
- /**
- * Reads an excel file already containing a named range.
- *
- * Addresses Bug #9632
- */
- @Test
- void testNamedRead() throws Exception {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("namedinput.xls");
-
- //Get index of the named range with the name = "NamedRangeName" , which was defined in input.xls as A1:D10
- int NamedRangeIndex = wb.getNameIndex("NamedRangeName");
-
- //Getting NAmed Range
- HSSFName namedRange1 = wb.getNameAt(NamedRangeIndex);
- String sheetName = wb.getSheetName(0);
-
- //Getting its reference
- String reference = namedRange1.getRefersToFormula();
-
- assertEquals(sheetName+"!$A$1:$D$10", reference);
- assertFalse(namedRange1.isDeleted());
- assertFalse(namedRange1.isHidden());
-
- HSSFName namedRange2 = wb.getNameAt(1);
-
- assertEquals(sheetName+"!$D$17:$G$27", namedRange2.getRefersToFormula());
- assertEquals("SecondNamedRange", namedRange2.getNameName());
- assertFalse(namedRange2.isDeleted());
- assertFalse(namedRange2.isHidden());
-
- wb.close();
- }
-
- /**
- * Reads an excel file already containing a named range and updates it
- *
- * Addresses Bug #16411
- */
- @Test
- void testNamedReadModify() throws Exception {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("namedinput.xls");
-
- HSSFName name = wb.getNameAt(0);
- String sheetName = wb.getSheetName(0);
-
- assertEquals(sheetName+"!$A$1:$D$10", name.getRefersToFormula());
-
- name = wb.getNameAt(1);
- String newReference = sheetName +"!$A$1:$C$36";
-
- name.setRefersToFormula(newReference);
- assertEquals(newReference, name.getRefersToFormula());
-
- wb.close();
- }
-
- /**
- * Test to see if the print area can be retrieved from an excel created file
- */
- @Test
- void testPrintAreaFileRead() throws Exception {
- HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPrintArea.xls");
-
- String sheetName = workbook.getSheetName(0);
- String reference = sheetName+"!$A$1:$C$5";
-
- assertEquals(reference, workbook.getPrintArea(0));
- workbook.close();
- }
-
- @Test
- void testDeletedReference() throws Exception {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("24207.xls")) {
- assertEquals(2, wb.getNumberOfNames());
-
- HSSFName name1 = wb.getNameAt(0);
- assertEquals("a", name1.getNameName());
- assertEquals("Sheet1!$A$1", name1.getRefersToFormula());
- wb.getCreationHelper().createAreaReference(name1.getRefersToFormula());
-
- HSSFName name2 = wb.getNameAt(1);
- assertEquals("b", name2.getNameName());
- assertEquals("Sheet1!#REF!", name2.getRefersToFormula());
- assertTrue(name2.isDeleted());
- // TODO - use a stronger typed exception for this condition
- assertThrows(IllegalArgumentException.class, () ->
- wb.getCreationHelper().createAreaReference(name2.getRefersToFormula()),
- "attempt to supply an invalid reference to AreaReference constructor results in exception");
- }
- }
-
- /**
- * When setting A1 type of references with HSSFName.setRefersToFormula
- * must set the type of operands to Ptg.CLASS_REF,
- * otherwise created named don't appear in the drop-down to the left of formula bar in Excel
- */
- @Test
- void testTypeOfRootPtg() throws Exception {
- HSSFWorkbook wb = new HSSFWorkbook();
- wb.createSheet("CSCO");
-
- Ptg[] ptgs = HSSFFormulaParser.parse("CSCO!$E$71", wb, FormulaType.NAMEDRANGE, 0);
- for (Ptg ptg : ptgs) {
- assertEquals('R', ptg.getRVAType());
- }
- wb.close();
- }
-
- @Test
- public final void testHSSFAddRemove() throws Exception {
- HSSFWorkbook wb = HSSFITestDataProvider.instance.createWorkbook();
- assertEquals(0, wb.getNumberOfNames());
- Name name1 = wb.createName();
- name1.setNameName("name1");
- assertEquals(1, wb.getNumberOfNames());
-
- Name name2 = wb.createName();
- name2.setNameName("name2");
- assertEquals(2, wb.getNumberOfNames());
-
- Name name3 = wb.createName();
- name3.setNameName("name3");
- assertEquals(3, wb.getNumberOfNames());
-
- wb.removeName(wb.getName("name2"));
- assertEquals(2, wb.getNumberOfNames());
-
- wb.removeName(0);
- assertEquals(1, wb.getNumberOfNames());
-
- wb.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java
deleted file mode 100644
index 95364a33c2..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java
+++ /dev/null
@@ -1,706 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-package org.apache.poi.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import org.apache.poi.ss.usermodel.BorderStyle;
-import org.apache.poi.ss.usermodel.CellStyle;
-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.Row;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.junit.jupiter.api.Test;
-
-final class TestHSSFOptimiser {
- @Test
- void testDoesNoHarmIfNothingToDo() {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- // New files start with 4 built in fonts, and 21 built in styles
- assertEquals(4, wb.getNumberOfFonts());
- assertEquals(21, wb.getNumCellStyles());
-
- // Create a test font and style, and use them
- HSSFFont f = wb.createFont();
- f.setFontName("Testing");
- HSSFCellStyle s = wb.createCellStyle();
- s.setFont(f);
-
- HSSFSheet sheet = wb.createSheet();
- HSSFRow row = sheet.createRow(0);
- row.createCell(0).setCellStyle(s);
-
- // Should have one more than the default of each
- assertEquals(5, wb.getNumberOfFonts());
- assertEquals(22, wb.getNumCellStyles());
-
- // Optimise fonts
- HSSFOptimiser.optimiseFonts(wb);
-
- assertEquals(5, wb.getNumberOfFonts());
- assertEquals(22, wb.getNumCellStyles());
-
- assertEquals(f, s.getFont(wb));
-
- // Optimise styles
- HSSFOptimiser.optimiseCellStyles(wb);
-
- assertEquals(5, wb.getNumberOfFonts());
- assertEquals(22, wb.getNumCellStyles());
-
- assertEquals(f, s.getFont(wb));
- }
-
- @Test
- void testOptimiseFonts() {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- // Add 6 fonts, some duplicates
- HSSFFont f1 = wb.createFont();
- f1.setFontHeight((short) 11);
- f1.setFontName("Testing");
-
- HSSFFont f2 = wb.createFont();
- f2.setFontHeight((short) 22);
- f2.setFontName("Also Testing");
-
- HSSFFont f3 = wb.createFont();
- f3.setFontHeight((short) 33);
- f3.setFontName("Unique");
-
- HSSFFont f4 = wb.createFont();
- f4.setFontHeight((short) 11);
- f4.setFontName("Testing");
-
- HSSFFont f5 = wb.createFont();
- f5.setFontHeight((short) 22);
- f5.setFontName("Also Testing");
-
- HSSFFont f6 = wb.createFont();
- f6.setFontHeight((short) 66);
- f6.setFontName("Also Unique");
-
- // Use all three of the four in cell styles
- assertEquals(21, wb.getNumCellStyles());
-
- HSSFCellStyle cs1 = wb.createCellStyle();
- cs1.setFont(f1);
- assertEquals(5, cs1.getFontIndex());
-
- HSSFCellStyle cs2 = wb.createCellStyle();
- cs2.setFont(f4);
- assertEquals(8, cs2.getFontIndex());
-
- HSSFCellStyle cs3 = wb.createCellStyle();
- cs3.setFont(f5);
- assertEquals(9, cs3.getFontIndex());
-
- HSSFCellStyle cs4 = wb.createCellStyle();
- cs4.setFont(f6);
- assertEquals(10, cs4.getFontIndex());
-
- assertEquals(25, wb.getNumCellStyles());
-
- // And three in rich text
- HSSFSheet s = wb.createSheet();
- HSSFRow r = s.createRow(0);
-
- HSSFRichTextString rtr1 = new HSSFRichTextString("Test");
- rtr1.applyFont(0, 2, f1);
- rtr1.applyFont(3, 4, f2);
- r.createCell(0).setCellValue(rtr1);
-
- HSSFRichTextString rtr2 = new HSSFRichTextString("AlsoTest");
- rtr2.applyFont(0, 2, f3);
- rtr2.applyFont(3, 5, f5);
- rtr2.applyFont(6, 8, f6);
- r.createCell(1).setCellValue(rtr2);
-
- // Check what we have now
- assertEquals(10, wb.getNumberOfFonts());
- assertEquals(25, wb.getNumCellStyles());
-
- // Optimise
- HSSFOptimiser.optimiseFonts(wb);
-
- // Check font count
- assertEquals(8, wb.getNumberOfFonts());
- assertEquals(25, wb.getNumCellStyles());
-
- // Check font use in cell styles
- assertEquals(5, cs1.getFontIndex());
- assertEquals(5, cs2.getFontIndex()); // duplicate of 1
- assertEquals(6, cs3.getFontIndex()); // duplicate of 2
- assertEquals(8, cs4.getFontIndex()); // two have gone
-
- // And in rich text
-
- // RTR 1 had f1 and f2, unchanged
- assertEquals(5, r.getCell(0).getRichStringCellValue().getFontAtIndex(0));
- assertEquals(5, r.getCell(0).getRichStringCellValue().getFontAtIndex(1));
- assertEquals(6, r.getCell(0).getRichStringCellValue().getFontAtIndex(3));
- assertEquals(6, r.getCell(0).getRichStringCellValue().getFontAtIndex(4));
-
- // RTR 2 had f3 (unchanged), f5 (=f2) and f6 (moved down)
- assertEquals(7, r.getCell(1).getRichStringCellValue().getFontAtIndex(0));
- assertEquals(7, r.getCell(1).getRichStringCellValue().getFontAtIndex(1));
- assertEquals(6, r.getCell(1).getRichStringCellValue().getFontAtIndex(3));
- assertEquals(6, r.getCell(1).getRichStringCellValue().getFontAtIndex(4));
- assertEquals(8, r.getCell(1).getRichStringCellValue().getFontAtIndex(6));
- assertEquals(8, r.getCell(1).getRichStringCellValue().getFontAtIndex(7));
- }
-
- @Test
- void testOptimiseStyles() {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- // Two fonts
- assertEquals(4, wb.getNumberOfFonts());
-
- HSSFFont f1 = wb.createFont();
- f1.setFontHeight((short) 11);
- f1.setFontName("Testing");
-
- HSSFFont f2 = wb.createFont();
- f2.setFontHeight((short) 22);
- f2.setFontName("Also Testing");
-
- assertEquals(6, wb.getNumberOfFonts());
-
- // Several styles
- assertEquals(21, wb.getNumCellStyles());
-
- HSSFCellStyle cs1 = wb.createCellStyle();
- cs1.setFont(f1);
-
- HSSFCellStyle cs2 = wb.createCellStyle();
- cs2.setFont(f2);
-
- HSSFCellStyle cs3 = wb.createCellStyle();
- cs3.setFont(f1);
-
- HSSFCellStyle cs4 = wb.createCellStyle();
- cs4.setFont(f1);
- cs4.setAlignment(HorizontalAlignment.CENTER);
-
- HSSFCellStyle cs5 = wb.createCellStyle();
- cs5.setFont(f2);
- cs5.setAlignment(HorizontalAlignment.FILL);
-
- HSSFCellStyle cs6 = wb.createCellStyle();
- cs6.setFont(f2);
-
- assertEquals(27, wb.getNumCellStyles());
-
- // Use them
- HSSFSheet s = wb.createSheet();
- HSSFRow r = s.createRow(0);
-
- r.createCell(0).setCellStyle(cs1);
- r.createCell(1).setCellStyle(cs2);
- r.createCell(2).setCellStyle(cs3);
- r.createCell(3).setCellStyle(cs4);
- r.createCell(4).setCellStyle(cs5);
- r.createCell(5).setCellStyle(cs6);
- r.createCell(6).setCellStyle(cs1);
- r.createCell(7).setCellStyle(cs2);
-
- assertEquals(21, r.getCell(0).getCellValueRecord().getXFIndex());
- assertEquals(26, r.getCell(5).getCellValueRecord().getXFIndex());
- assertEquals(21, r.getCell(6).getCellValueRecord().getXFIndex());
-
- // Optimise
- HSSFOptimiser.optimiseCellStyles(wb);
-
- // Check
- assertEquals(6, wb.getNumberOfFonts());
- assertEquals(25, wb.getNumCellStyles());
-
- // cs1 -> 21
- assertEquals(21, r.getCell(0).getCellValueRecord().getXFIndex());
- // cs2 -> 22
- assertEquals(22, r.getCell(1).getCellValueRecord().getXFIndex());
- assertEquals(22, r.getCell(1).getCellStyle().getFont(wb).getFontHeight());
- // cs3 = cs1 -> 21
- assertEquals(21, r.getCell(2).getCellValueRecord().getXFIndex());
- // cs4 --> 24 -> 23
- assertEquals(23, r.getCell(3).getCellValueRecord().getXFIndex());
- // cs5 --> 25 -> 24
- assertEquals(24, r.getCell(4).getCellValueRecord().getXFIndex());
- // cs6 = cs2 -> 22
- assertEquals(22, r.getCell(5).getCellValueRecord().getXFIndex());
- // cs1 -> 21
- assertEquals(21, r.getCell(6).getCellValueRecord().getXFIndex());
- // cs2 -> 22
- assertEquals(22, r.getCell(7).getCellValueRecord().getXFIndex());
-
-
- // Add a new duplicate, and two that aren't used
- HSSFCellStyle csD = wb.createCellStyle();
- csD.setFont(f1);
- r.createCell(8).setCellStyle(csD);
-
- HSSFFont f3 = wb.createFont();
- f3.setFontHeight((short) 23);
- f3.setFontName("Testing 3");
- HSSFFont f4 = wb.createFont();
- f4.setFontHeight((short) 24);
- f4.setFontName("Testing 4");
-
- HSSFCellStyle csU1 = wb.createCellStyle();
- csU1.setFont(f3);
- HSSFCellStyle csU2 = wb.createCellStyle();
- csU2.setFont(f4);
-
- // Check before the optimise
- assertEquals(8, wb.getNumberOfFonts());
- assertEquals(28, wb.getNumCellStyles());
-
- // Optimise, should remove the two un-used ones and the one duplicate
- HSSFOptimiser.optimiseCellStyles(wb);
-
- // Check
- assertEquals(8, wb.getNumberOfFonts());
- assertEquals(25, wb.getNumCellStyles());
-
- // csD -> cs1 -> 21
- assertEquals(21, r.getCell(8).getCellValueRecord().getXFIndex());
- }
-
- @Test
- void testOptimiseStylesCheckActualStyles() {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- // Several styles
- assertEquals(21, wb.getNumCellStyles());
-
- HSSFCellStyle cs1 = wb.createCellStyle();
- cs1.setBorderBottom(BorderStyle.THICK);
-
- HSSFCellStyle cs2 = wb.createCellStyle();
- cs2.setBorderBottom(BorderStyle.DASH_DOT);
-
- HSSFCellStyle cs3 = wb.createCellStyle(); // = cs1
- cs3.setBorderBottom(BorderStyle.THICK);
-
- assertEquals(24, wb.getNumCellStyles());
-
- // Use them
- HSSFSheet s = wb.createSheet();
- HSSFRow r = s.createRow(0);
-
- r.createCell(0).setCellStyle(cs1);
- r.createCell(1).setCellStyle(cs2);
- r.createCell(2).setCellStyle(cs3);
-
- assertEquals(21, r.getCell(0).getCellValueRecord().getXFIndex());
- assertEquals(22, r.getCell(1).getCellValueRecord().getXFIndex());
- assertEquals(23, r.getCell(2).getCellValueRecord().getXFIndex());
-
- // Optimise
- HSSFOptimiser.optimiseCellStyles(wb);
-
- // Check
- assertEquals(23, wb.getNumCellStyles());
-
- assertEquals(BorderStyle.THICK, r.getCell(0).getCellStyle().getBorderBottom());
- assertEquals(BorderStyle.DASH_DOT, r.getCell(1).getCellStyle().getBorderBottom());
- assertEquals(BorderStyle.THICK, r.getCell(2).getCellStyle().getBorderBottom());
- }
-
- @Test
- void testColumnAndRowStyles() {
- HSSFWorkbook wb = new HSSFWorkbook();
- assertEquals(21, wb.getNumCellStyles(),
- "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()");
-
- HSSFSheet sheet = wb.createSheet();
-
- Row row = sheet.createRow(0);
- row.createCell(0);
- row.createCell(1);
- row.setRowStyle(createColorStyle(wb, IndexedColors.RED));
-
- row = sheet.createRow(1);
- row.createCell(0);
- row.createCell(1);
- row.setRowStyle(createColorStyle(wb, IndexedColors.RED));
-
- sheet.setDefaultColumnStyle(0, createColorStyle(wb, IndexedColors.RED));
- sheet.setDefaultColumnStyle(1, createColorStyle(wb, IndexedColors.RED));
-
- // now the color should be equal for those two columns and rows
- checkColumnStyles(sheet, 0, 1, false);
- checkRowStyles(sheet, 0, 1, false);
-
- // Optimise styles
- HSSFOptimiser.optimiseCellStyles(wb);
-
- // We should have the same style-objects for these two columns and rows
- checkColumnStyles(sheet, 0, 1, true);
- checkRowStyles(sheet, 0, 1, true);
- }
-
- @Test
- void testUnusedStyle() {
- HSSFWorkbook wb = new HSSFWorkbook();
- assertEquals(21, wb.getNumCellStyles(),
- "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()");
-
- HSSFSheet sheet = wb.createSheet();
-
- Row row = sheet.createRow(0);
- row.createCell(0);
- row.createCell(1).setCellStyle(
- createColorStyle(wb, IndexedColors.GREEN));
-
-
- row = sheet.createRow(1);
- row.createCell(0);
- row.createCell(1).setCellStyle(
- createColorStyle(wb, IndexedColors.RED));
-
-
- // Create style. But don't use it.
- for (int i = 0; i < 3; i++) {
- // Set Cell Color : AQUA
- createColorStyle(wb, IndexedColors.AQUA);
- }
-
- assertEquals(21 + 2 + 3, wb.getNumCellStyles());
- assertEquals(IndexedColors.GREEN.getIndex(), sheet.getRow(0).getCell(1).getCellStyle().getFillForegroundColor());
- assertEquals(IndexedColors.RED.getIndex(), sheet.getRow(1).getCell(1).getCellStyle().getFillForegroundColor());
-
- // Optimise styles
- HSSFOptimiser.optimiseCellStyles(wb);
-
- assertEquals(21 + 2, wb.getNumCellStyles());
- assertEquals(IndexedColors.GREEN.getIndex(), sheet.getRow(0).getCell(1).getCellStyle().getFillForegroundColor());
- assertEquals(IndexedColors.RED.getIndex(), sheet.getRow(1).getCell(1).getCellStyle().getFillForegroundColor());
- }
-
- @Test
- void testUnusedStyleOneUsed() {
- HSSFWorkbook wb = new HSSFWorkbook();
- assertEquals(21, wb.getNumCellStyles(),
- "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()");
-
- HSSFSheet sheet = wb.createSheet();
-
- Row row = sheet.createRow(0);
- row.createCell(0);
- row.createCell(1).setCellStyle(
- createColorStyle(wb, IndexedColors.GREEN));
-
- // Create style. But don't use it.
- for (int i = 0; i < 3; i++) {
- // Set Cell Color : AQUA
- createColorStyle(wb, IndexedColors.AQUA);
- }
-
- row = sheet.createRow(1);
- row.createCell(0).setCellStyle(createColorStyle(wb, IndexedColors.AQUA));
- row.createCell(1).setCellStyle(
- createColorStyle(wb, IndexedColors.RED));
-
- assertEquals(21 + 3 + 3, wb.getNumCellStyles());
- assertEquals(IndexedColors.GREEN.getIndex(), sheet.getRow(0).getCell(1).getCellStyle().getFillForegroundColor());
- assertEquals(IndexedColors.AQUA.getIndex(), sheet.getRow(1).getCell(0).getCellStyle().getFillForegroundColor());
- assertEquals(IndexedColors.RED.getIndex(), sheet.getRow(1).getCell(1).getCellStyle().getFillForegroundColor());
-
- // Optimise styles
- HSSFOptimiser.optimiseCellStyles(wb);
-
- assertEquals(21 + 3, wb.getNumCellStyles());
- assertEquals(IndexedColors.GREEN.getIndex(), sheet.getRow(0).getCell(1).getCellStyle().getFillForegroundColor());
- assertEquals(IndexedColors.AQUA.getIndex(), sheet.getRow(1).getCell(0).getCellStyle().getFillForegroundColor());
- assertEquals(IndexedColors.RED.getIndex(), sheet.getRow(1).getCell(1).getCellStyle().getFillForegroundColor());
- }
-
- @Test
- void testDefaultColumnStyleWitoutCell() {
- HSSFWorkbook wb = new HSSFWorkbook();
- assertEquals(21, wb.getNumCellStyles(),
- "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()");
-
- HSSFSheet sheet = wb.createSheet();
-
- //Set CellStyle and RowStyle and ColumnStyle
- for (int i = 0; i < 2; i++) {
- sheet.createRow(i);
- }
-
- // Create a test font and style, and use them
- int obj_cnt = wb.getNumCellStyles();
- int cnt = wb.getNumCellStyles();
-
- // Set Column Color : Red
- sheet.setDefaultColumnStyle(3,
- createColorStyle(wb, IndexedColors.RED));
- obj_cnt++;
-
- // Set Column Color : Red
- sheet.setDefaultColumnStyle(4,
- createColorStyle(wb, IndexedColors.RED));
- obj_cnt++;
-
- assertEquals(obj_cnt, wb.getNumCellStyles());
-
- // now the color should be equal for those two columns and rows
- checkColumnStyles(sheet, 3, 4, false);
-
- // Optimise styles
- HSSFOptimiser.optimiseCellStyles(wb);
-
- // We should have the same style-objects for these two columns and rows
- checkColumnStyles(sheet, 3, 4, true);
-
- // (GREEN + RED + BLUE + CORAL) + YELLOW(2*2)
- assertEquals(cnt + 1, wb.getNumCellStyles());
- }
-
- @Test
- void testUserDefinedStylesAreNeverOptimizedAway() {
- HSSFWorkbook wb = new HSSFWorkbook();
- assertEquals(21, wb.getNumCellStyles(),
- "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()");
-
- HSSFSheet sheet = wb.createSheet();
-
- //Set CellStyle and RowStyle and ColumnStyle
- for (int i = 0; i < 2; i++) {
- sheet.createRow(i);
- }
-
- // Create a test font and style, and use them
- int obj_cnt = wb.getNumCellStyles();
- int cnt = wb.getNumCellStyles();
- for (int i = 0; i < 3; i++) {
- HSSFCellStyle s = null;
- if (i == 0) {
- // Set cell color : +2(user style + proxy of it)
- s = (HSSFCellStyle) createColorStyle(wb,
- IndexedColors.YELLOW);
- s.setUserStyleName("user define");
- obj_cnt += 2;
- }
-
- HSSFRow row = sheet.getRow(1);
- row.createCell(i).setCellStyle(s);
- }
-
- // Create style. But don't use it.
- for (int i = 3; i < 6; i++) {
- // Set Cell Color : AQUA
- createColorStyle(wb, IndexedColors.AQUA);
- obj_cnt++;
- }
-
- // Set cell color : +2(user style + proxy of it)
- HSSFCellStyle s = (HSSFCellStyle) createColorStyle(wb, IndexedColors.YELLOW);
- s.setUserStyleName("user define2");
- obj_cnt += 2;
-
- sheet.createRow(10).createCell(0).setCellStyle(s);
-
- assertEquals(obj_cnt, wb.getNumCellStyles());
-
- // Confirm user style name
- checkUserStyles(sheet);
-
- // Optimise styles
- HSSFOptimiser.optimiseCellStyles(wb);
-
- // Confirm user style name
- checkUserStyles(sheet);
-
- // (GREEN + RED + BLUE + CORAL) + YELLOW(2*2)
- assertEquals(cnt + 2 * 2, wb.getNumCellStyles());
- }
-
- @Test
- void testBug57517() {
- HSSFWorkbook wb = new HSSFWorkbook();
- assertEquals(21, wb.getNumCellStyles(),
- "Usually we have 21 pre-defined styles in a newly created Workbook, see InternalWorkbook.createWorkbook()");
-
- HSSFSheet sheet = wb.createSheet();
-
- //Set CellStyle and RowStyle and ColumnStyle
- for (int i = 0; i < 2; i++) {
- sheet.createRow(i);
- }
-
- // Create a test font and style, and use them
- int obj_cnt = wb.getNumCellStyles();
- int cnt = wb.getNumCellStyles();
- for (int i = 0; i < 3; i++) {
- // Set Cell Color : GREEN
- HSSFRow row = sheet.getRow(0);
- row.createCell(i).setCellStyle(
- createColorStyle(wb, IndexedColors.GREEN));
- obj_cnt++;
-
- // Set Column Color : Red
- sheet.setDefaultColumnStyle(i + 3,
- createColorStyle(wb, IndexedColors.RED));
- obj_cnt++;
-
- // Set Row Color : Blue
- row = sheet.createRow(i + 3);
- row.setRowStyle(createColorStyle(wb, IndexedColors.BLUE));
- obj_cnt++;
-
- HSSFCellStyle s = null;
- if (i == 0) {
- // Set cell color : +2(user style + proxy of it)
- s = (HSSFCellStyle) createColorStyle(wb,
- IndexedColors.YELLOW);
- s.setUserStyleName("user define");
- obj_cnt += 2;
- }
-
- row = sheet.getRow(1);
- row.createCell(i).setCellStyle(s);
-
- }
-
- // Create style. But don't use it.
- for (int i = 3; i < 6; i++) {
- // Set Cell Color : AQUA
- createColorStyle(wb, IndexedColors.AQUA);
- obj_cnt++;
- }
-
- // Set CellStyle and RowStyle and ColumnStyle
- for (int i = 9; i < 11; i++) {
- sheet.createRow(i);
- }
-
- //Set 0 or 255 index of ColumnStyle.
- HSSFCellStyle s = (HSSFCellStyle) createColorStyle(wb, IndexedColors.CORAL);
- obj_cnt++;
- sheet.setDefaultColumnStyle(0, s);
- sheet.setDefaultColumnStyle(255, s);
-
- // Create a test font and style, and use them
- for (int i = 3; i < 6; i++) {
- // Set Cell Color : GREEN
- HSSFRow row = sheet.getRow(9);
- row.createCell(i - 3).setCellStyle(
- createColorStyle(wb, IndexedColors.GREEN));
- obj_cnt++;
-
- // Set Column Color : Red
- sheet.setDefaultColumnStyle(i + 3,
- createColorStyle(wb, IndexedColors.RED));
- obj_cnt++;
-
- // Set Row Color : Blue
- row = sheet.createRow(i + 3);
- row.setRowStyle(createColorStyle(wb, IndexedColors.BLUE));
- obj_cnt++;
-
- if (i == 3) {
- // Set cell color : +2(user style + proxy of it)
- s = (HSSFCellStyle) createColorStyle(wb,
- IndexedColors.YELLOW);
- s.setUserStyleName("user define2");
- obj_cnt += 2;
- }
-
- row = sheet.getRow(1 + 9);
- row.createCell(i - 3).setCellStyle(s);
- }
-
- assertEquals(obj_cnt, wb.getNumCellStyles());
-
- // now the color should be equal for those two columns and rows
- checkColumnStyles(sheet, 3, 4, false);
- checkRowStyles(sheet, 3, 4, false);
-
- // Confirm user style name
- checkUserStyles(sheet);
-
-// out = new FileOutputStream(new File(tmpDirName, "out.xls"));
-// wb.write(out);
-// out.close();
-
- // Optimise styles
- HSSFOptimiser.optimiseCellStyles(wb);
-
-// out = new FileOutputStream(new File(tmpDirName, "out_optimised.xls"));
-// wb.write(out);
-// out.close();
-
- // We should have the same style-objects for these two columns and rows
- checkColumnStyles(sheet, 3, 4, true);
- checkRowStyles(sheet, 3, 4, true);
-
- // Confirm user style name
- checkUserStyles(sheet);
-
- // (GREEN + RED + BLUE + CORAL) + YELLOW(2*2)
- assertEquals(cnt + 4 + 2 * 2, wb.getNumCellStyles());
- }
-
- private void checkUserStyles(HSSFSheet sheet) {
- HSSFCellStyle parentStyle1 = sheet.getRow(1).getCell(0).getCellStyle().getParentStyle();
- assertNotNull(parentStyle1);
- assertEquals(parentStyle1.getUserStyleName(), "user define");
-
- HSSFCellStyle parentStyle10 = sheet.getRow(10).getCell(0).getCellStyle().getParentStyle();
- assertNotNull(parentStyle10);
- assertEquals(parentStyle10.getUserStyleName(), "user define2");
- }
-
- private void checkColumnStyles(HSSFSheet sheet, int col1, int col2, boolean checkEquals) {
- // we should have the same color for the column styles
- HSSFCellStyle columnStyle1 = sheet.getColumnStyle(col1);
- assertNotNull(columnStyle1);
- HSSFCellStyle columnStyle2 = sheet.getColumnStyle(col2);
- assertNotNull(columnStyle2);
- assertEquals(columnStyle1.getFillForegroundColor(), columnStyle2.getFillForegroundColor());
- if (checkEquals) {
- assertEquals(columnStyle1.getIndex(), columnStyle2.getIndex());
- assertEquals(columnStyle1, columnStyle2);
- }
- }
-
- private void checkRowStyles(HSSFSheet sheet, int row1, int row2, boolean checkEquals) {
- // we should have the same color for the row styles
- HSSFCellStyle rowStyle1 = sheet.getRow(row1).getRowStyle();
- assertNotNull(rowStyle1);
- HSSFCellStyle rowStyle2 = sheet.getRow(row2).getRowStyle();
- assertNotNull(rowStyle2);
- assertEquals(rowStyle1.getFillForegroundColor(), rowStyle2.getFillForegroundColor());
- if (checkEquals) {
- assertEquals(rowStyle1.getIndex(), rowStyle2.getIndex());
- assertEquals(rowStyle1, rowStyle2);
- }
- }
-
- private CellStyle createColorStyle(Workbook wb, IndexedColors c) {
- CellStyle cs = wb.createCellStyle();
- cs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
- cs.setFillForegroundColor(c.getIndex());
- return cs;
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java
deleted file mode 100644
index 1f6460e920..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java
+++ /dev/null
@@ -1,305 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.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.assertThrows;
-
-import java.awt.Color;
-import java.io.IOException;
-import java.util.Map;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.PaletteRecord;
-import org.apache.poi.hssf.util.HSSFColor;
-import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
-import org.apache.poi.ss.usermodel.FillPatternType;
-import org.apache.poi.ss.usermodel.Font;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-final class TestHSSFPalette {
- private HSSFPalette _hssfPalette;
-
-
- @BeforeEach
- void setUp() {
- PaletteRecord _palette = new PaletteRecord();
- _hssfPalette = new HSSFPalette(_palette);
- }
-
- /**
- * Verifies that a custom palette can be created, saved, and reloaded
- */
- @Test
- void testCustomPalette() {
- //reading sample xls
- HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("Simple.xls");
-
- //creating custom palette
- HSSFPalette palette = book.getCustomPalette();
- palette.setColorAtIndex((short) 0x12, (byte) 101, (byte) 230, (byte) 100);
- palette.setColorAtIndex((short) 0x3b, (byte) 0, (byte) 255, (byte) 52);
-
- //writing to disk; reading in and verifying palette
- book = HSSFTestDataSamples.writeOutAndReadBack(book);
-
- palette = book.getCustomPalette();
- HSSFColor color = palette.getColor(HSSFColorPredefined.CORAL.getIndex()); //unmodified
- assertNotNull(color, "Unexpected null in custom palette (unmodified index)");
- short[] expectedRGB = HSSFColorPredefined.CORAL.getTriplet();
- short[] actualRGB = color.getTriplet();
- String msg = "Expected palette position to remain unmodified";
- assertEquals(expectedRGB[0], actualRGB[0], msg);
- assertEquals(expectedRGB[1], actualRGB[1], msg);
- assertEquals(expectedRGB[2], actualRGB[2], msg);
-
- color = palette.getColor((short) 0x12);
- assertNotNull(color, "Unexpected null in custom palette (modified)");
- actualRGB = color.getTriplet();
- msg = "Expected palette modification to be preserved across save";
- assertEquals((short) 101, actualRGB[0], msg);
- assertEquals((short) 230, actualRGB[1], msg);
- assertEquals((short) 100, actualRGB[2], msg);
- }
-
- /**
- * Uses the palette from cell stylings
- */
- @SuppressWarnings("ConstantConditions")
- @Test
- void testPaletteFromCellColours() {
- HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("SimpleWithColours.xls");
-
- HSSFPalette p = book.getCustomPalette();
-
- HSSFCell cellA = book.getSheetAt(0).getRow(0).getCell(0);
- HSSFCell cellB = book.getSheetAt(0).getRow(1).getCell(0);
- HSSFCell cellC = book.getSheetAt(0).getRow(2).getCell(0);
- HSSFCell cellD = book.getSheetAt(0).getRow(3).getCell(0);
- HSSFCell cellE = book.getSheetAt(0).getRow(4).getCell(0);
-
- // Plain
- assertEquals("I'm plain", cellA.getStringCellValue());
- assertEquals(64, cellA.getCellStyle().getFillForegroundColor());
- assertEquals(64, cellA.getCellStyle().getFillBackgroundColor());
- assertEquals(Font.COLOR_NORMAL, cellA.getCellStyle().getFont(book).getColor());
- assertEquals(FillPatternType.NO_FILL, cellA.getCellStyle().getFillPattern());
- assertNotNull(p.getColor((short)64));
- assertEquals("0:0:0", p.getColor((short)64).getHexString());
- assertNull(p.getColor((short) 32767));
-
- // Red
- assertEquals("I'm red", cellB.getStringCellValue());
- assertEquals(64, cellB.getCellStyle().getFillForegroundColor());
- assertEquals(64, cellB.getCellStyle().getFillBackgroundColor());
- assertEquals(10, cellB.getCellStyle().getFont(book).getColor());
- assertEquals(FillPatternType.NO_FILL, cellB.getCellStyle().getFillPattern());
- assertEquals("0:0:0", p.getColor((short)64).getHexString());
- assertEquals("FFFF:0:0", p.getColor((short)10).getHexString());
-
- // Red + green bg
- assertEquals("I'm red with a green bg", cellC.getStringCellValue());
- assertEquals(11, cellC.getCellStyle().getFillForegroundColor());
- assertEquals(64, cellC.getCellStyle().getFillBackgroundColor());
- assertEquals(10, cellC.getCellStyle().getFont(book).getColor());
- assertEquals(FillPatternType.SOLID_FOREGROUND, cellC.getCellStyle().getFillPattern());
- assertEquals("0:FFFF:0", p.getColor((short)11).getHexString());
- assertEquals("FFFF:0:0", p.getColor((short)10).getHexString());
-
- // Pink with yellow
- assertEquals("I'm pink with a yellow pattern (none)", cellD.getStringCellValue());
- assertEquals(13, cellD.getCellStyle().getFillForegroundColor());
- assertEquals(64, cellD.getCellStyle().getFillBackgroundColor());
- assertEquals(14, cellD.getCellStyle().getFont(book).getColor());
- assertEquals(FillPatternType.NO_FILL, cellD.getCellStyle().getFillPattern());
- assertEquals("FFFF:FFFF:0", p.getColor((short)13).getHexString());
- assertEquals("FFFF:0:FFFF", p.getColor((short)14).getHexString());
-
- // Pink with yellow - full
- assertEquals("I'm pink with a yellow pattern (full)", cellE.getStringCellValue());
- assertEquals(13, cellE.getCellStyle().getFillForegroundColor());
- assertEquals(64, cellE.getCellStyle().getFillBackgroundColor());
- assertEquals(14, cellE.getCellStyle().getFont(book).getColor());
- assertEquals(FillPatternType.NO_FILL, cellE.getCellStyle().getFillPattern());
- assertEquals("FFFF:FFFF:0", p.getColor((short)13).getHexString());
- assertEquals("FFFF:0:FFFF", p.getColor((short)14).getHexString());
- }
-
- @SuppressWarnings("ConstantConditions")
- @Test
- void testFindSimilar() throws IOException {
- HSSFWorkbook book = new HSSFWorkbook();
- HSSFPalette p = book.getCustomPalette();
-
- /* first test the defaults */
- assertArrayEquals(
- new short[] {(short) 255, (short) 255, (short) 0}, // not [204, 255, 255]
- p.findSimilarColor((byte) 204, (byte) 255, (byte) 0).getTriplet()
- );
-
- assertArrayEquals(
- new short[] {(short) 153, (short) 204, (short) 0}, // not [128, 0, 0]
- p.findSimilarColor((byte) 128, (byte) 255, (byte) 0).getTriplet()
- );
-
- assertArrayEquals(
- new short[] {(short) 0, (short) 255, (short) 0}, // not [0, 51, 102]
- p.findSimilarColor((byte) 0, (byte) 255, (byte) 102).getTriplet()
- );
-
- assertArrayEquals(
- new short[] {(short) 0, (short) 102, (short) 204}, // not [255, 102, 0]
- p.findSimilarColor((byte) 0, (byte) 102, (byte) 255).getTriplet()
- );
-
- assertArrayEquals(
- new short[] {(short) 255, (short) 0, (short) 255}, // not [128, 0, 0]
- p.findSimilarColor((byte) 128, (byte) 0, (byte) 255).getTriplet()
- );
-
- assertArrayEquals(
- new short[] {(short) 255, (short) 0, (short) 255}, // not [255, 255, 153]
- p.findSimilarColor((byte) 255, (byte) 0, (byte) 153).getTriplet()
- );
-
-
- // Add a few edge colours in
- p.setColorAtIndex((short)8, (byte)-1, (byte)0, (byte)0);
- p.setColorAtIndex((short)9, (byte)0, (byte)-1, (byte)0);
- p.setColorAtIndex((short)10, (byte)0, (byte)0, (byte)-1);
-
- // And some near a few of them
- p.setColorAtIndex((short)11, (byte)-1, (byte)2, (byte)2);
- p.setColorAtIndex((short)12, (byte)-2, (byte)2, (byte)10);
- p.setColorAtIndex((short)13, (byte)-4, (byte)0, (byte)0);
- p.setColorAtIndex((short)14, (byte)-8, (byte)0, (byte)0);
-
- assertEquals(
- "FFFF:0:0", p.getColor((short)8).getHexString()
- );
-
- // Now check we get the right stuff back
- assertEquals(
- p.getColor((short)8).getHexString(),
- p.findSimilarColor((byte)-1, (byte)0, (byte)0).getHexString()
- );
- assertEquals(
- p.getColor((short)8).getHexString(),
- p.findSimilarColor((byte)-2, (byte)0, (byte)0).getHexString()
- );
- assertEquals(
- p.getColor((short)8).getHexString(),
- p.findSimilarColor((byte)-1, (byte)1, (byte)0).getHexString()
- );
- assertEquals(
- p.getColor((short)11).getHexString(),
- p.findSimilarColor((byte)-1, (byte)2, (byte)1).getHexString()
- );
- assertEquals(
- p.getColor((short)12).getHexString(),
- p.findSimilarColor((byte)-1, (byte)2, (byte)10).getHexString()
- );
-
- // And with ints not bytes
- assertEquals(
- p.getColor((short)11).getHexString(),
- p.findSimilarColor(255, 2, 1).getHexString()
- );
- assertEquals(
- p.getColor((short)12).getHexString(),
- p.findSimilarColor(255, 2, 10).getHexString()
- );
-
- book.close();
- }
-
- /**
- * Verifies that the generated gnumeric-format string values match the
- * hardcoded values in the HSSFColor default color palette
- */
- @Test
- void testGnumericStrings() {
- compareToDefaults((expected, palette) -> assertEquals(expected.getHexString(), palette.getHexString()));
- }
-
- /**
- * Verifies that the palette handles invalid palette indexes
- */
- @Test
- void testBadIndexes() {
- //too small
- _hssfPalette.setColorAtIndex((short) 2, (byte) 255, (byte) 255, (byte) 255);
- //too large
- _hssfPalette.setColorAtIndex((short) 0x45, (byte) 255, (byte) 255, (byte) 255);
-
- //should still match defaults;
- compareToDefaults((expected, palette) -> {
- short[] s1 = expected.getTriplet();
- short[] s2 = palette.getTriplet();
- assertEquals(s1[0], s2[0]);
- assertEquals(s1[1], s2[1]);
- assertEquals(s1[2], s2[2]);
- });
- }
-
- private void compareToDefaults(ColorComparator c) {
- Map colors = HSSFColor.getIndexHash();
- for (Integer index : colors.keySet()) {
- HSSFColor expectedColor = colors.get(index);
- HSSFColor paletteColor = _hssfPalette.getColor(index.shortValue());
- c.compare(expectedColor, paletteColor);
- }
- }
-
- @Test
- void testAddColor() {
- assertThrows(RuntimeException.class, () -> _hssfPalette.addColor((byte)10,(byte)10,(byte)10),
- "Failing because by default there are no colours left in the palette.");
- }
-
- private interface ColorComparator {
- void compare(HSSFColor expected, HSSFColor palette);
- }
-
- @Test
- void test48403() throws Exception {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- Color color = Color.decode("#006B6B");
- HSSFPalette palette = wb.getCustomPalette();
-
- HSSFColor hssfColor = palette.findColor((byte) color.getRed(),
- (byte) color.getGreen(), (byte) color.getBlue());
- assertNull(hssfColor);
-
- palette.setColorAtIndex(
- (short) (PaletteRecord.STANDARD_PALETTE_SIZE - 1),
- (byte) color.getRed(), (byte) color.getGreen(),
- (byte) color.getBlue());
- hssfColor = palette.getColor((short) (PaletteRecord.STANDARD_PALETTE_SIZE - 1));
- assertNotNull(hssfColor);
- assertEquals(55, hssfColor.getIndex());
- assertArrayEquals(new short[] {0, 107, 107}, hssfColor.getTriplet());
-
- wb.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.java
deleted file mode 100644
index 64b91fc516..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.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.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import java.io.IOException;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
-import org.junit.jupiter.api.Test;
-
-final class TestHSSFPatriarch {
-
- @Test
- void testBasic() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
-
- HSSFPatriarch patr = sheet.createDrawingPatriarch();
- assertNotNull(patr);
- }
- }
-
- @Test
- void test44916() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
-
- // 1. Create drawing patriarch
- HSSFPatriarch patr = sheet.createDrawingPatriarch();
-
- // 2. Try to re-get the patriarch
- // bug 44916 - NullPointerException
- HSSFPatriarch existingPatr = sheet.getDrawingPatriarch();
-
- // 3. Use patriarch
- HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 600, 245, (short) 1, 1, (short) 1, 2);
- anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
- byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png");
- int idx1 = wb.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG);
- patr.createPicture(anchor, idx1);
-
- // 4. Try to re-use patriarch later
- existingPatr = sheet.getDrawingPatriarch();
- assertNotNull(existingPatr);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java
deleted file mode 100644
index b2a793f972..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook;
-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 java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.ddf.EscherBSERecord;
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.InternalSheet;
-import org.apache.poi.ss.usermodel.BaseTestPicture;
-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.Picture;
-import org.apache.poi.ss.usermodel.PictureData;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.function.Executable;
-
-final class TestHSSFPicture extends BaseTestPicture {
-
- public TestHSSFPicture() {
- super(HSSFITestDataProvider.instance);
- }
-
- protected Picture getPictureShape(Drawing> pat, int picIdx) {
- return (Picture)((HSSFPatriarch)pat).getChildren().get(picIdx);
- }
-
- /**
- * Bug # 45829 reported ArithmeticException (/ by zero) when resizing png with zero DPI.
- */
- @Test
- void bug45829() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sh1 = wb.createSheet();
- HSSFPatriarch p1 = sh1.createDrawingPatriarch();
-
- byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("45829.png");
- int idx1 = wb.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG);
- HSSFPicture pic = p1.createPicture(new HSSFClientAnchor(), idx1);
- assertDoesNotThrow((Executable) pic::resize);
- }
- }
-
-
- @Test
- void addPictures() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
-
- HSSFSheet sh = wb1.createSheet("Pictures");
- HSSFPatriarch dr = sh.createDrawingPatriarch();
- assertEquals(0, dr.getChildren().size());
- HSSFClientAnchor anchor = wb1.getCreationHelper().createClientAnchor();
-
- //register a picture
- byte[] data1 = {1, 2, 3};
- int idx1 = wb1.addPicture(data1, Workbook.PICTURE_TYPE_JPEG);
- assertEquals(1, idx1);
- HSSFPicture p1 = dr.createPicture(anchor, idx1);
- assertArrayEquals(data1, p1.getPictureData().getData());
-
- // register another one
- byte[] data2 = {4, 5, 6};
- int idx2 = wb1.addPicture(data2, Workbook.PICTURE_TYPE_JPEG);
- assertEquals(2, idx2);
- HSSFPicture p2 = dr.createPicture(anchor, idx2);
- assertEquals(2, dr.getChildren().size());
- assertArrayEquals(data2, p2.getPictureData().getData());
-
- // confirm that HSSFPatriarch.getChildren() returns two picture shapes
- assertArrayEquals(data1, ((HSSFPicture) dr.getChildren().get(0)).getPictureData().getData());
- assertArrayEquals(data2, ((HSSFPicture) dr.getChildren().get(1)).getPictureData().getData());
-
- // write, read back and verify that our pictures are there
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
- List extends PictureData> lst2 = wb2.getAllPictures();
- assertEquals(2, lst2.size());
- assertArrayEquals(data1, lst2.get(0).getData());
- assertArrayEquals(data2, lst2.get(1).getData());
-
- // confirm that the pictures are in the Sheet's drawing
- sh = wb2.getSheet("Pictures");
- dr = sh.createDrawingPatriarch();
- assertEquals(2, dr.getChildren().size());
- assertArrayEquals(data1, ((HSSFPicture) dr.getChildren().get(0)).getPictureData().getData());
- assertArrayEquals(data2, ((HSSFPicture) dr.getChildren().get(1)).getPictureData().getData());
-
- // add a third picture
- byte[] data3 = {7, 8, 9};
- // picture index must increment across write-read
- int idx3 = wb2.addPicture(data3, Workbook.PICTURE_TYPE_JPEG);
- assertEquals(3, idx3);
- HSSFPicture p3 = dr.createPicture(anchor, idx3);
- assertArrayEquals(data3, p3.getPictureData().getData());
- assertEquals(3, dr.getChildren().size());
- assertArrayEquals(data1, ((HSSFPicture) dr.getChildren().get(0)).getPictureData().getData());
- assertArrayEquals(data2, ((HSSFPicture) dr.getChildren().get(1)).getPictureData().getData());
- assertArrayEquals(data3, ((HSSFPicture) dr.getChildren().get(2)).getPictureData().getData());
-
- // write and read again
- try (HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2)) {
- List extends PictureData> lst3 = wb3.getAllPictures();
- // all three should be there
- assertEquals(3, lst3.size());
- assertArrayEquals(data1, lst3.get(0).getData());
- assertArrayEquals(data2, lst3.get(1).getData());
- assertArrayEquals(data3, lst3.get(2).getData());
-
- sh = wb3.getSheet("Pictures");
- dr = sh.createDrawingPatriarch();
- assertEquals(3, dr.getChildren().size());
-
- // forth picture
- byte[] data4 = {10, 11, 12};
- int idx4 = wb3.addPicture(data4, Workbook.PICTURE_TYPE_JPEG);
- assertEquals(4, idx4);
- dr.createPicture(anchor, idx4);
- assertEquals(4, dr.getChildren().size());
- assertArrayEquals(data1, ((HSSFPicture) dr.getChildren().get(0)).getPictureData().getData());
- assertArrayEquals(data2, ((HSSFPicture) dr.getChildren().get(1)).getPictureData().getData());
- assertArrayEquals(data3, ((HSSFPicture) dr.getChildren().get(2)).getPictureData().getData());
- assertArrayEquals(data4, ((HSSFPicture) dr.getChildren().get(3)).getPictureData().getData());
-
- try (HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3)) {
- List extends PictureData> lst4 = wb4.getAllPictures();
- assertEquals(4, lst4.size());
- assertArrayEquals(data1, lst4.get(0).getData());
- assertArrayEquals(data2, lst4.get(1).getData());
- assertArrayEquals(data3, lst4.get(2).getData());
- assertArrayEquals(data4, lst4.get(3).getData());
- sh = wb4.getSheet("Pictures");
- dr = sh.createDrawingPatriarch();
- assertEquals(4, dr.getChildren().size());
- assertArrayEquals(data1, ((HSSFPicture) dr.getChildren().get(0)).getPictureData().getData());
- assertArrayEquals(data2, ((HSSFPicture) dr.getChildren().get(1)).getPictureData().getData());
- assertArrayEquals(data3, ((HSSFPicture) dr.getChildren().get(2)).getPictureData().getData());
- assertArrayEquals(data4, ((HSSFPicture) dr.getChildren().get(3)).getPictureData().getData());
- }
- }
- }
- }
- }
-
- @SuppressWarnings("unused")
- @Test
- void bsePictureRef() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sh = wb.createSheet("Pictures");
- HSSFPatriarch dr = sh.createDrawingPatriarch();
- HSSFClientAnchor anchor = new HSSFClientAnchor();
-
- InternalSheet ish = HSSFTestHelper.getSheetForTest(sh);
-
- //register a picture
- byte[] data1 = {1, 2, 3};
- int idx1 = wb.addPicture(data1, Workbook.PICTURE_TYPE_JPEG);
- assertEquals(1, idx1);
- HSSFPicture p1 = dr.createPicture(anchor, idx1);
-
- EscherBSERecord bse = wb.getWorkbook().getBSERecord(idx1);
-
- assertEquals(bse.getRef(), 1);
- dr.createPicture(new HSSFClientAnchor(), idx1);
- assertEquals(bse.getRef(), 2);
-
- HSSFShapeGroup gr = dr.createGroup(new HSSFClientAnchor());
- gr.createPicture(new HSSFChildAnchor(), idx1);
- assertEquals(bse.getRef(), 3);
- }
- }
-
- @Test
- void readExistingImage() throws IOException {
- try (HSSFWorkbook wb = openSampleWorkbook("drawings.xls")) {
- HSSFSheet sheet = wb.getSheet("picture");
- HSSFPatriarch drawing = sheet.getDrawingPatriarch();
- assertEquals(1, drawing.getChildren().size());
-
- HSSFPicture picture = (HSSFPicture) drawing.getChildren().get(0);
- assertEquals(picture.getFileName(), "test");
- }
- }
-
- @SuppressWarnings("resource")
- @Test
- void setGetProperties() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
-
- HSSFSheet sh = wb1.createSheet("Pictures");
- HSSFPatriarch dr = sh.createDrawingPatriarch();
- HSSFClientAnchor anchor = new HSSFClientAnchor();
-
- //register a picture
- byte[] data1 = {1, 2, 3};
- int idx1 = wb1.addPicture(data1, Workbook.PICTURE_TYPE_JPEG);
- HSSFPicture p1 = dr.createPicture(anchor, idx1);
-
- assertEquals(p1.getFileName(), "");
- p1.setFileName("aaa");
- assertEquals(p1.getFileName(), "aaa");
-
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
- sh = wb2.getSheet("Pictures");
- dr = sh.getDrawingPatriarch();
-
- p1 = (HSSFPicture) dr.getChildren().get(0);
- assertEquals(p1.getFileName(), "aaa");
- }
- }
- }
-
- @SuppressWarnings("resource")
- @Test
- void bug49658() throws IOException {
- // test if inserted EscherMetafileBlip will be read again
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
-
- byte[] pictureDataEmf = POIDataSamples.getDocumentInstance().readFile("vector_image.emf");
- int indexEmf = wb1.addPicture(pictureDataEmf, HSSFWorkbook.PICTURE_TYPE_EMF);
- byte[] pictureDataPng = POIDataSamples.getSpreadSheetInstance().readFile("logoKarmokar4.png");
- int indexPng = wb1.addPicture(pictureDataPng, HSSFWorkbook.PICTURE_TYPE_PNG);
- byte[] pictureDataWmf = POIDataSamples.getSlideShowInstance().readFile("santa.wmf");
- int indexWmf = wb1.addPicture(pictureDataWmf, HSSFWorkbook.PICTURE_TYPE_WMF);
-
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
- CreationHelper ch = wb1.getCreationHelper();
-
- ClientAnchor anchor = ch.createClientAnchor();
- anchor.setCol1(2);
- anchor.setCol2(5);
- anchor.setRow1(1);
- anchor.setRow2(6);
- patriarch.createPicture(anchor, indexEmf);
-
- anchor = ch.createClientAnchor();
- anchor.setCol1(2);
- anchor.setCol2(5);
- anchor.setRow1(10);
- anchor.setRow2(16);
- patriarch.createPicture(anchor, indexPng);
-
- anchor = ch.createClientAnchor();
- anchor.setCol1(6);
- anchor.setCol2(9);
- anchor.setRow1(1);
- anchor.setRow2(6);
- patriarch.createPicture(anchor, indexWmf);
-
-
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
- byte[] pictureDataOut = wb2.getAllPictures().get(0).getData();
- assertArrayEquals(pictureDataEmf, pictureDataOut);
-
- byte[] wmfNoHeader = Arrays.copyOfRange(pictureDataWmf, 22, pictureDataWmf.length);
- pictureDataOut = wb2.getAllPictures().get(2).getData();
- assertArrayEquals(wmfNoHeader, pictureDataOut);
- }
- }
- }
-
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java
deleted file mode 100644
index dd1de44da9..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.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.hssf.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.awt.image.BufferedImage;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-
-import javax.imageio.IIOException;
-import javax.imageio.ImageIO;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test HSSFPictureData .
- * The code to retrieve images from a workbook provided by Trejkaz (trejkaz at trypticon dot org) in Bug 41223.
- */
-final class TestHSSFPictureData {
- @BeforeAll
- public static void setUpClass() {
- final String tmpDirProperty = System.getProperty("java.io.tmpdir");
- if(tmpDirProperty == null || "".equals(tmpDirProperty)) {
- return;
- }
- // ensure that temp-dir exists because ImageIO requires it
- final File tmpDir = new File(tmpDirProperty);
- if(!tmpDir.exists() && !tmpDir.mkdirs()) {
- throw new IllegalStateException("Could not create temporary directory " + tmpDirProperty + ", full path " + tmpDir.getAbsolutePath());
- }
- ImageIO.setCacheDirectory(tmpDir);
- }
-
- @Test
- void testPictures() throws IOException {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithImages.xls");
-
- // TODO - add getFormat() to interface PictureData and genericise wb.getAllPictures()
- List lst = wb.getAllPictures();
- //assertEquals(2, lst.size());
-
- try {
- for (final HSSFPictureData pict : lst) {
- String ext = pict.suggestFileExtension();
- byte[] data = pict.getData();
- if (ext.equals("jpeg")) {
- //try to read image data using javax.imageio.* (JDK 1.4+)
- BufferedImage jpg = ImageIO.read(new ByteArrayInputStream(data));
- assertNotNull(jpg);
- assertEquals(192, jpg.getWidth());
- assertEquals(176, jpg.getHeight());
- assertEquals(HSSFWorkbook.PICTURE_TYPE_JPEG, pict.getFormat());
- assertEquals("image/jpeg", pict.getMimeType());
- } else if (ext.equals("png")) {
- //try to read image data using javax.imageio.* (JDK 1.4+)
- BufferedImage png = ImageIO.read(new ByteArrayInputStream(data));
- assertNotNull(png);
- assertEquals(300, png.getWidth());
- assertEquals(300, png.getHeight());
- assertEquals(HSSFWorkbook.PICTURE_TYPE_PNG, pict.getFormat());
- assertEquals("image/png", pict.getMimeType());
- /*} else {
- //TODO: test code for PICT, WMF and EMF*/
- }
- }
- } catch (IIOException e) {
- assertFalse(e.getMessage().contains("Can't create cache file"), e.getMessage());
- }
- }
-
- @Test
- void testMacPicture() throws IOException {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("53446.xls");
-
- try{
- List lst = wb.getAllPictures();
- assertEquals(1, lst.size());
-
- HSSFPictureData pict = lst.get(0);
- String ext = pict.suggestFileExtension();
- assertEquals("png", ext, "Expected a PNG.");
-
- //try to read image data using javax.imageio.* (JDK 1.4+)
- byte[] data = pict.getData();
- BufferedImage png = ImageIO.read(new ByteArrayInputStream(data));
- assertNotNull(png);
- assertEquals(78, png.getWidth());
- assertEquals(76, png.getHeight());
- assertEquals(HSSFWorkbook.PICTURE_TYPE_PNG, pict.getFormat());
- assertEquals("image/png", pict.getMimeType());
- } catch (IIOException e) {
- assertFalse(e.getMessage().contains("Can't create cache file"), e.getMessage());
- }
- }
-
- @Test
- void testNotNullPictures() {
-
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SheetWithDrawing.xls");
-
- // TODO - add getFormat() to interface PictureData and genericise wb.getAllPictures()
- List lst = wb.getAllPictures();
- for(HSSFPictureData pict : lst){
- assertNotNull(pict);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRangeCopier.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRangeCopier.java
deleted file mode 100644
index 4b17b77a8e..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRangeCopier.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ====================================================================
- */
-
-package org.apache.poi.hssf.usermodel;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.ss.usermodel.BaseTestRangeCopier;
-import org.junit.jupiter.api.BeforeEach;
-
-class TestHSSFRangeCopier extends BaseTestRangeCopier {
-
- public TestHSSFRangeCopier() {
- super();
- workbook = new HSSFWorkbook();
- testDataProvider = HSSFITestDataProvider.instance;
- }
-
- @BeforeEach
- void init() {
- workbook = HSSFTestDataSamples.openSampleWorkbook("tile-range-test.xls");
- initSheets();
- rangeCopier = new HSSFRangeCopier(sheet1, sheet1);
- transSheetRangeCopier = new HSSFRangeCopier(sheet1, sheet2);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java
deleted file mode 100644
index 44ae5b4fcf..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.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.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-final class TestHSSFRichTextString {
- @Test
- void testApplyFont() {
- HSSFRichTextString r = new HSSFRichTextString("testing");
- assertEquals(0,r.numFormattingRuns());
- r.applyFont(2,4, new HSSFFont((short)1, null));
- assertEquals(2,r.numFormattingRuns());
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(0));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(1));
- assertEquals(1, r.getFontAtIndex(2));
- assertEquals(1, r.getFontAtIndex(3));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(4));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(5));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(6));
-
- r.applyFont(6,7, new HSSFFont((short)2, null));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(0));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(1));
- assertEquals(1, r.getFontAtIndex(2));
- assertEquals(1, r.getFontAtIndex(3));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(4));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(5));
- assertEquals(2, r.getFontAtIndex(6));
-
- r.applyFont(HSSFRichTextString.NO_FONT);
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(0));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(1));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(2));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(3));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(4));
- assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(5));
-
- r.applyFont(new HSSFFont((short)1, null));
- assertEquals(1, r.getFontAtIndex(0));
- assertEquals(1, r.getFontAtIndex(1));
- assertEquals(1, r.getFontAtIndex(2));
- assertEquals(1, r.getFontAtIndex(3));
- assertEquals(1, r.getFontAtIndex(4));
- assertEquals(1, r.getFontAtIndex(5));
- assertEquals(1, r.getFontAtIndex(6));
- }
-
- @Test
- void testClearFormatting() {
- HSSFRichTextString r = new HSSFRichTextString("testing");
- assertEquals(0, r.numFormattingRuns());
- r.applyFont(2, 4, new HSSFFont( (short) 1, null));
- assertEquals(2, r.numFormattingRuns());
- r.clearFormatting();
- assertEquals(0, r.numFormattingRuns());
- }
-
-
- /**
- * Test case proposed in Bug 40520: formated twice => will format whole String
- */
- @Test
- void test40520_1() {
- short font = 3;
-
- HSSFRichTextString r = new HSSFRichTextString("f0_123456789012345678901234567890123456789012345678901234567890");
-
- r.applyFont(0,7,font);
- r.applyFont(5,9,font);
-
- for(int i=0; i < 7; i++) assertEquals(font, r.getFontAtIndex(i));
- for(int i=5; i < 9; i++) assertEquals(font, r.getFontAtIndex(i));
- for(int i=9; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i));
- }
-
- /**
- * Test case proposed in Bug 40520: overlapped range => will format whole String
- */
- @Test
- void test40520_2() {
- short font = 3;
- HSSFRichTextString r = new HSSFRichTextString("f0_123456789012345678901234567890123456789012345678901234567890");
-
- r.applyFont(0,2,font);
- for(int i=0; i < 2; i++) assertEquals(font, r.getFontAtIndex(i));
- for(int i=2; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i));
-
- r.applyFont(0,2,font);
- for(int i=0; i < 2; i++) assertEquals(font, r.getFontAtIndex(i));
- for(int i=2; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i));
- }
-
- /**
- * Test case proposed in Bug 40520: formated twice => will format whole String
- */
- @Test
- void test40520_3() {
- short font = 3;
- HSSFRichTextString r = new HSSFRichTextString("f0_123456789012345678901234567890123456789012345678901234567890");
-
- // wrong order => will format 0-6
- r.applyFont(0,2,font);
- r.applyFont(5,7,font);
- r.applyFont(0,2,font);
-
- r.applyFont(0,2,font);
- for(int i=0; i < 2; i++) assertEquals(font, r.getFontAtIndex(i));
- for(int i=2; i < 5; i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i));
- for(int i=5; i < 7; i++) assertEquals(font, r.getFontAtIndex(i));
- for(int i=7; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i));
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java
deleted file mode 100644
index b588f1375c..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.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.hssf.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.IOException;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.record.BlankRecord;
-import org.apache.poi.hssf.record.RowRecord;
-import org.apache.poi.ss.usermodel.BaseTestRow;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test HSSFRow is okay.
- *
- * @author Glen Stampoultzis (glens at apache.org)
- */
-final class TestHSSFRow extends BaseTestRow {
-
- public TestHSSFRow() {
- super(HSSFITestDataProvider.instance);
- }
-
- @Test
- void testLastAndFirstColumns_bug46654() throws IOException {
- int ROW_IX = 10;
- int COL_IX = 3;
- HSSFWorkbook workbook = new HSSFWorkbook();
- HSSFSheet sheet = workbook.createSheet("Sheet1");
- RowRecord rowRec = new RowRecord(ROW_IX);
- rowRec.setFirstCol((short)2);
- rowRec.setLastCol((short)5);
-
- BlankRecord br = new BlankRecord();
- br.setRow(ROW_IX);
- br.setColumn((short)COL_IX);
-
- sheet.getSheet().addValueRecord(ROW_IX, br);
- HSSFRow row = new HSSFRow(workbook, sheet, rowRec);
- HSSFCell cell = row.createCellFromRecord(br);
-
- assertFalse(row.getFirstCellNum() == 2 && row.getLastCellNum() == 5, "Identified bug 46654a");
-
- assertEquals(COL_IX, row.getFirstCellNum());
- assertEquals(COL_IX + 1, row.getLastCellNum());
- row.removeCell(cell);
- assertEquals(-1, row.getFirstCellNum());
- assertEquals(-1, row.getLastCellNum());
-
- workbook.close();
- }
-
- @Test
- void testMoveCell() throws IOException {
- HSSFWorkbook workbook = new HSSFWorkbook();
- HSSFSheet sheet = workbook.createSheet();
- HSSFRow row = sheet.createRow(0);
- HSSFRow rowB = sheet.createRow(1);
-
- HSSFCell cellA2 = rowB.createCell(0);
- assertEquals(0, rowB.getFirstCellNum());
- assertEquals(0, rowB.getFirstCellNum());
-
- assertEquals(-1, row.getLastCellNum());
- assertEquals(-1, row.getFirstCellNum());
- HSSFCell cellB2 = row.createCell(1);
- row.createCell(2); // C2
- row.createCell(3); // D2
-
- assertEquals(1, row.getFirstCellNum());
- assertEquals(4, row.getLastCellNum());
-
- // Try to move to somewhere else that's used
- assertThrows(IllegalArgumentException.class, () -> row.moveCell(cellB2, (short)3));
-
- // Try to move one off a different row
- assertThrows(IllegalArgumentException.class, () -> row.moveCell(cellA2, (short)3));
-
- // Move somewhere spare
- assertNotNull(row.getCell(1));
- row.moveCell(cellB2, (short)5);
- assertNull(row.getCell(1));
- assertNotNull(row.getCell(5));
-
- assertEquals(5, cellB2.getColumnIndex());
- assertEquals(2, row.getFirstCellNum());
- assertEquals(6, row.getLastCellNum());
-
- workbook.close();
- }
-
- @Override
- @Test
- protected void testRowHeight() throws IOException{
- HSSFWorkbook workbook = new HSSFWorkbook();
- HSSFSheet sheet = workbook.createSheet();
- HSSFRow row = sheet.createRow(0);
-
- assertEquals(row.getHeight(), sheet.getDefaultRowHeight());
- assertFalse(row.getRowRecord().getBadFontHeight());
-
- row.setHeight((short) 123);
- assertEquals(123, row.getHeight());
- assertTrue(row.getRowRecord().getBadFontHeight());
-
- row.setHeight((short) -1);
- assertEquals(row.getHeight(), sheet.getDefaultRowHeight());
- assertFalse(row.getRowRecord().getBadFontHeight());
-
- row.setHeight((short) 123);
- assertEquals(123, row.getHeight());
- assertTrue(row.getRowRecord().getBadFontHeight());
-
- row.setHeightInPoints(-1);
- assertEquals(row.getHeight(), sheet.getDefaultRowHeight());
- assertFalse(row.getRowRecord().getBadFontHeight());
-
- row.setHeightInPoints(432);
- assertEquals(432*20, row.getHeight());
- assertTrue(row.getRowRecord().getBadFontHeight());
-
- workbook.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java
deleted file mode 100644
index b6c9c918d2..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java
+++ /dev/null
@@ -1,1115 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack;
-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.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.ArrayList;
-import java.util.List;
-
-import org.apache.poi.ddf.EscherDgRecord;
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.DrawingManager2;
-import org.apache.poi.hssf.model.InternalSheet;
-import org.apache.poi.hssf.model.InternalWorkbook;
-import org.apache.poi.hssf.record.*;
-import org.apache.poi.hssf.record.aggregates.WorksheetProtectionBlock;
-import org.apache.poi.ss.formula.ptg.Area3DPtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.usermodel.AutoFilter;
-import org.apache.poi.ss.usermodel.BaseTestSheet;
-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.usermodel.Workbook;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.apache.poi.ss.util.CellRangeAddressList;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests HSSFSheet. This test case is very incomplete at the moment.
- */
-final class TestHSSFSheet extends BaseTestSheet {
-
- public TestHSSFSheet() {
- super(HSSFITestDataProvider.instance);
- }
-
- /**
- * Test for Bugzilla #29747.
- * Moved from TestHSSFWorkbook#testSetRepeatingRowsAndColumns().
- */
- @Test
- void setRepeatingRowsAndColumnsBug29747() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- wb.createSheet();
- wb.createSheet();
- HSSFSheet sheet2 = wb.createSheet();
- sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:2"));
- NameRecord nameRecord = wb.getWorkbook().getNameRecord(0);
- assertEquals(3, nameRecord.getSheetNumber());
- }
- }
-
- /**
- * Test the gridset field gets set as expected.
- */
- @Test
- void backupRecord() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- GridsetRecord gridsetRec = s.getSheet().getGridsetRecord();
- assertTrue(gridsetRec.getGridset());
- s.setGridsPrinted(true);
- assertFalse(gridsetRec.getGridset());
- }
- }
-
- /**
- * Test vertically centered output.
- */
- @Test
- void verticallyCenter() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- VCenterRecord record = s.getSheet().getPageSettings().getVCenter();
-
- assertFalse(record.getVCenter());
- assertFalse(s.getVerticallyCenter());
- s.setVerticallyCenter(true);
- assertTrue(record.getVCenter());
- assertTrue(s.getVerticallyCenter());
- }
- }
-
- /**
- * Test horizontally centered output.
- */
- @Test
- void horizontallyCenter() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- HCenterRecord record = s.getSheet().getPageSettings().getHCenter();
-
- assertFalse(record.getHCenter());
- assertFalse(s.getHorizontallyCenter());
- s.setHorizontallyCenter(true);
- assertTrue(record.getHCenter());
- assertTrue(s.getHorizontallyCenter());
- }
- }
-
-
- /**
- * Test WSBoolRecord fields get set in the user model.
- */
- @Test
- void wsBool() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- WSBoolRecord record = (WSBoolRecord) s.getSheet().findFirstRecordBySid(WSBoolRecord.sid);
-
- // Check defaults
- assertNotNull(record);
- assertTrue(record.getAlternateExpression());
- assertTrue(record.getAlternateFormula());
- assertFalse(record.getAutobreaks());
- assertFalse(record.getDialog());
- assertFalse(record.getDisplayGuts());
- assertTrue(record.getFitToPage());
- assertFalse(record.getRowSumsBelow());
- assertFalse(record.getRowSumsRight());
-
- // Alter
- s.setAlternativeExpression(false);
- s.setAlternativeFormula(false);
- s.setAutobreaks(true);
- s.setDialog(true);
- s.setDisplayGuts(true);
- s.setFitToPage(false);
- s.setRowSumsBelow(true);
- s.setRowSumsRight(true);
-
- // Check
- assertTrue(record.getAlternateExpression()); //sheet.setRowSumsBelow alters this field too
- assertFalse(record.getAlternateFormula());
- assertTrue(record.getAutobreaks());
- assertTrue(record.getDialog());
- assertTrue(record.getDisplayGuts());
- assertFalse(record.getFitToPage());
- assertTrue(record.getRowSumsBelow());
- assertTrue(record.getRowSumsRight());
- assertTrue(s.getAlternateExpression());
- assertFalse(s.getAlternateFormula());
- assertTrue(s.getAutobreaks());
- assertTrue(s.getDialog());
- assertTrue(s.getDisplayGuts());
- assertFalse(s.getFitToPage());
- assertTrue(s.getRowSumsBelow());
- assertTrue(s.getRowSumsRight());
- }
- }
-
- /**
- * Setting landscape and portrait stuff on existing sheets
- */
- @Test
- void printSetupLandscapeExisting() throws IOException {
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls")) {
-
- assertEquals(3, wb1.getNumberOfSheets());
-
- HSSFSheet sheetL = wb1.getSheetAt(0);
- HSSFSheet sheetPM = wb1.getSheetAt(1);
- HSSFSheet sheetLS = wb1.getSheetAt(2);
-
- // Check two aspects of the print setup
- assertFalse(sheetL.getPrintSetup().getLandscape());
- assertTrue(sheetPM.getPrintSetup().getLandscape());
- assertTrue(sheetLS.getPrintSetup().getLandscape());
- assertEquals(1, sheetL.getPrintSetup().getCopies());
- assertEquals(1, sheetPM.getPrintSetup().getCopies());
- assertEquals(1, sheetLS.getPrintSetup().getCopies());
-
- // Change one on each
- sheetL.getPrintSetup().setLandscape(true);
- sheetPM.getPrintSetup().setLandscape(false);
- sheetPM.getPrintSetup().setCopies((short) 3);
-
- // Check taken
- assertTrue(sheetL.getPrintSetup().getLandscape());
- assertFalse(sheetPM.getPrintSetup().getLandscape());
- assertTrue(sheetLS.getPrintSetup().getLandscape());
- assertEquals(1, sheetL.getPrintSetup().getCopies());
- assertEquals(3, sheetPM.getPrintSetup().getCopies());
- assertEquals(1, sheetLS.getPrintSetup().getCopies());
-
- // Save and re-load, and check still there
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- sheetL = wb2.getSheetAt(0);
- sheetPM = wb2.getSheetAt(1);
- sheetLS = wb2.getSheetAt(2);
-
- assertTrue(sheetL.getPrintSetup().getLandscape());
- assertFalse(sheetPM.getPrintSetup().getLandscape());
- assertTrue(sheetLS.getPrintSetup().getLandscape());
- assertEquals(1, sheetL.getPrintSetup().getCopies());
- assertEquals(3, sheetPM.getPrintSetup().getCopies());
- assertEquals(1, sheetLS.getPrintSetup().getCopies());
- }
- }
- }
-
- @Test
- void groupRows() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
- HSSFRow r1 = s.createRow(0);
- HSSFRow r2 = s.createRow(1);
- HSSFRow r3 = s.createRow(2);
- HSSFRow r4 = s.createRow(3);
- HSSFRow r5 = s.createRow(4);
-
- assertEquals(0, r1.getOutlineLevel());
- assertEquals(0, r2.getOutlineLevel());
- assertEquals(0, r3.getOutlineLevel());
- assertEquals(0, r4.getOutlineLevel());
- assertEquals(0, r5.getOutlineLevel());
-
- s.groupRow(2, 3);
-
- assertEquals(0, r1.getOutlineLevel());
- assertEquals(0, r2.getOutlineLevel());
- assertEquals(1, r3.getOutlineLevel());
- assertEquals(1, r4.getOutlineLevel());
- assertEquals(0, r5.getOutlineLevel());
-
- // Save and re-open
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- s = wb2.getSheetAt(0);
- r1 = s.getRow(0);
- r2 = s.getRow(1);
- r3 = s.getRow(2);
- r4 = s.getRow(3);
- r5 = s.getRow(4);
-
- assertEquals(0, r1.getOutlineLevel());
- assertEquals(0, r2.getOutlineLevel());
- assertEquals(1, r3.getOutlineLevel());
- assertEquals(1, r4.getOutlineLevel());
- assertEquals(0, r5.getOutlineLevel());
- }
- }
- }
-
- @Test
- void groupRowsExisting() throws IOException {
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("NoGutsRecords.xls")) {
-
- HSSFSheet s = wb1.getSheetAt(0);
- HSSFRow r1 = s.getRow(0);
- HSSFRow r2 = s.getRow(1);
- HSSFRow r3 = s.getRow(2);
- HSSFRow r4 = s.getRow(3);
- HSSFRow r5 = s.getRow(4);
- HSSFRow r6 = s.getRow(5);
-
- assertEquals(0, r1.getOutlineLevel());
- assertEquals(0, r2.getOutlineLevel());
- assertEquals(0, r3.getOutlineLevel());
- assertEquals(0, r4.getOutlineLevel());
- assertEquals(0, r5.getOutlineLevel());
- assertEquals(0, r6.getOutlineLevel());
-
- // This used to complain about lacking guts records
- s.groupRow(2, 4);
-
- assertEquals(0, r1.getOutlineLevel());
- assertEquals(0, r2.getOutlineLevel());
- assertEquals(1, r3.getOutlineLevel());
- assertEquals(1, r4.getOutlineLevel());
- assertEquals(1, r5.getOutlineLevel());
- assertEquals(0, r6.getOutlineLevel());
-
- // Save and re-open
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- // OutOfMemoryError -> Identified bug 39903
- s = wb2.getSheetAt(0);
- r1 = s.getRow(0);
- r2 = s.getRow(1);
- r3 = s.getRow(2);
- r4 = s.getRow(3);
- r5 = s.getRow(4);
- r6 = s.getRow(5);
-
- assertEquals(0, r1.getOutlineLevel());
- assertEquals(0, r2.getOutlineLevel());
- assertEquals(1, r3.getOutlineLevel());
- assertEquals(1, r4.getOutlineLevel());
- assertEquals(1, r5.getOutlineLevel());
- assertEquals(0, r6.getOutlineLevel());
- }
- }
- }
-
- @Test
- void createDrawings() throws IOException {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- HSSFSheet sheet = workbook.createSheet();
- HSSFPatriarch p1 = sheet.createDrawingPatriarch();
- HSSFPatriarch p2 = sheet.createDrawingPatriarch();
- assertSame(p1, p2);
- }
- }
-
- @Test
- void getDrawings() throws IOException {
- try (HSSFWorkbook wb1c = HSSFTestDataSamples.openSampleWorkbook("WithChart.xls");
- HSSFWorkbook wb2c = HSSFTestDataSamples.openSampleWorkbook("WithTwoCharts.xls")) {
-
- // 1 chart sheet -> data on 1st, chart on 2nd
- assertNotNull(wb1c.getSheetAt(0).getDrawingPatriarch());
- assertSame(wb1c.getSheetAt(0).getDrawingPatriarch(), wb1c.getSheetAt(0).getDrawingPatriarch());
- assertNotNull(wb1c.getSheetAt(1).getDrawingPatriarch());
- assertSame(wb1c.getSheetAt(1).getDrawingPatriarch(), wb1c.getSheetAt(1).getDrawingPatriarch());
- assertFalse(wb1c.getSheetAt(0).getDrawingPatriarch().containsChart());
- assertTrue(wb1c.getSheetAt(1).getDrawingPatriarch().containsChart());
-
- // 2 chart sheet -> data on 1st, chart on 2nd+3rd
- assertNotNull(wb2c.getSheetAt(0).getDrawingPatriarch());
- assertNotNull(wb2c.getSheetAt(1).getDrawingPatriarch());
- assertNotNull(wb2c.getSheetAt(2).getDrawingPatriarch());
- assertFalse(wb2c.getSheetAt(0).getDrawingPatriarch().containsChart());
- assertTrue(wb2c.getSheetAt(1).getDrawingPatriarch().containsChart());
- assertTrue(wb2c.getSheetAt(2).getDrawingPatriarch().containsChart());
- }
- }
-
- /**
- * Test that the ProtectRecord is included when creating or cloning a sheet
- */
- @Test
- void cloneWithProtect() throws IOException {
- String passwordA = "secrect";
- int expectedHashA = -6810;
- String passwordB = "admin";
- int expectedHashB = -14556;
-
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- HSSFSheet hssfSheet = workbook.createSheet();
- assertFalse(hssfSheet.getObjectProtect());
- hssfSheet.protectSheet(passwordA);
- assertTrue(hssfSheet.getObjectProtect());
- assertEquals(expectedHashA, hssfSheet.getPassword());
-
- assertEquals(expectedHashA, hssfSheet.getSheet().getProtectionBlock().getPasswordHash());
-
- // Clone the sheet, and make sure the password hash is preserved
- HSSFSheet sheet2 = workbook.cloneSheet(0);
- assertTrue(hssfSheet.getObjectProtect());
- assertEquals(expectedHashA, sheet2.getSheet().getProtectionBlock().getPasswordHash());
-
- // change the password on the first sheet
- hssfSheet.protectSheet(passwordB);
- assertTrue(hssfSheet.getObjectProtect());
- assertEquals(expectedHashB, hssfSheet.getSheet().getProtectionBlock().getPasswordHash());
- assertEquals(expectedHashB, hssfSheet.getPassword());
- // but the cloned sheet's password should remain unchanged
- assertEquals(expectedHashA, sheet2.getSheet().getProtectionBlock().getPasswordHash());
- }
- }
-
- @Test
- void protectSheetA() throws IOException {
- int expectedHash = (short)0xfef1;
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- s.protectSheet("abcdefghij");
- WorksheetProtectionBlock pb = s.getSheet().getProtectionBlock();
- assertTrue(pb.isSheetProtected(), "protection should be on");
- assertTrue(pb.isObjectProtected(), "object protection should be on");
- assertTrue(pb.isScenarioProtected(), "scenario protection should be on");
- assertEquals(expectedHash, pb.getPasswordHash(), "well known value for top secret hash should be " + Integer.toHexString(expectedHash).substring(4));
- }
- }
-
- /**
- * {@link PasswordRecord} belongs with the rest of the Worksheet Protection Block
- * (which should be before {@link DimensionsRecord}).
- */
- @Test
- void protectSheetRecordOrder_bug47363a() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- s.protectSheet("secret");
- List recs = new ArrayList<>();
- s.getSheet().visitContainedRecords(recs::add, 0);
- int nRecs = recs.size();
-
- // Check that protection block is together, and before DIMENSION
- // PASSWORD must be before DIMENSION
- Class>[] exp = {ProtectRecord.class, ObjectProtectRecord.class, ScenarioProtectRecord.class,
- PasswordRecord.class, DefaultColWidthRecord.class, DimensionsRecord.class, WindowTwoRecord.class,
- SelectionRecord.class, EOFRecord.class };
- Class>[] act = recs.subList(nRecs - 9, nRecs).stream().map(Object::getClass).toArray(Class[]::new);
- assertArrayEquals(exp, act);
- }
- }
-
- /**
- * There should be no problem with adding data validations after sheet protection
- */
- @Test
- void dvProtectionOrder_bug47363b() throws IOException {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- HSSFSheet sheet = workbook.createSheet("Sheet1");
- sheet.protectSheet("secret");
-
- DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
- DataValidationConstraint dvc = dataValidationHelper.createIntegerConstraint(DataValidationConstraint.OperatorType.BETWEEN, "10", "100");
- CellRangeAddressList numericCellAddressList = new CellRangeAddressList(0, 0, 1, 1);
- DataValidation dv = dataValidationHelper.createValidation(dvc, numericCellAddressList);
-
- // bug 47363b: Unexpected (org.apache.poi.hssf.record.PasswordRecord) while looking for DV Table insert pos
- sheet.addValidationData(dv);
-
- int[] nRecsWithProtection = { 0 };
- sheet.getSheet().visitContainedRecords(r -> nRecsWithProtection[0]++, 0);
-
- sheet.protectSheet(null);
- int[] nRecsWithoutProtection = { 0 };
- sheet.getSheet().visitContainedRecords(r -> nRecsWithoutProtection[0]++, 0);
-
- assertEquals(4, nRecsWithProtection[0] - nRecsWithoutProtection[0]);
- }
- }
-
- @Test
- void zoom() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- assertEquals(-1, sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid));
- sheet.setZoom(75);
- assertTrue(sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid) > 0);
- SCLRecord sclRecord = (SCLRecord) sheet.getSheet().findFirstRecordBySid(SCLRecord.sid);
- assertNotNull(sclRecord);
- short numerator = sclRecord.getNumerator();
- assertEquals(75, 100 * numerator / sclRecord.getDenominator());
-
- int sclLoc = sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid);
- int window2Loc = sheet.getSheet().findFirstRecordLocBySid(WindowTwoRecord.sid);
- assertEquals(sclLoc, window2Loc + 1);
-
- // verify limits
- IllegalArgumentException e;
- e = assertThrows(IllegalArgumentException.class, () -> sheet.setZoom(0));
- assertEquals("Numerator must be greater than 0 and less than 65536", e.getMessage());
-
- e = assertThrows(IllegalArgumentException.class, () -> sheet.setZoom(65536));
- assertEquals("Numerator must be greater than 0 and less than 65536", e.getMessage());
-
- e = assertThrows(IllegalArgumentException.class, () -> sheet.setZoom(2, 0));
- assertEquals("Denominator must be greater than 0 and less than 65536", e.getMessage());
-
- e = assertThrows(IllegalArgumentException.class, () -> sheet.setZoom(2, 65536));
- assertEquals("Denominator must be greater than 0 and less than 65536", e.getMessage());
- }
- }
-
-
- /**
- * When removing one merged region, it would break
- * Make sure the excel file loads work
- */
- @Test
- void pageBreakFiles() throws IOException {
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls")) {
-
- HSSFSheet sheet = wb1.getSheetAt(0);
- assertNotNull(sheet);
-
- assertEquals(1, sheet.getRowBreaks().length, "1 row page break");
- assertEquals(1, sheet.getColumnBreaks().length, "1 column page break");
-
- assertTrue(sheet.isRowBroken(22), "No row page break");
- assertTrue(sheet.isColumnBroken((short) 4), "No column page break");
-
- sheet.setRowBreak(10);
- sheet.setColumnBreak((short) 13);
-
- assertEquals(2, sheet.getRowBreaks().length, "row breaks number");
- assertEquals(2, sheet.getColumnBreaks().length, "column breaks number");
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- sheet = wb2.getSheetAt(0);
-
- assertTrue(sheet.isRowBroken(22), "No row page break");
- assertTrue(sheet.isColumnBroken((short) 4), "No column page break");
-
- assertEquals(2, sheet.getRowBreaks().length, "row breaks number");
- assertEquals(2, sheet.getColumnBreaks().length, "column breaks number");
- }
- }
- }
-
- @Test
- void dbcsName () throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DBCSSheetName.xls")) {
- wb.getSheetAt(1);
- assertEquals(wb.getSheetName(1), "\u090f\u0915", "DBCS Sheet Name 2");
- assertEquals(wb.getSheetName(0), "\u091c\u093e", "DBCS Sheet Name 1");
- }
- }
-
- /**
- * Testing newly added method that exposes the WINDOW2.toprow
- * parameter to allow setting the toprow in the visible view
- * of the sheet when it is first opened.
- */
- @Test
- void topRow() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls")) {
- HSSFSheet sheet = wb.getSheetAt(0);
- assertNotNull(sheet);
-
- short toprow = (short) 100;
- short leftcol = (short) 50;
- sheet.showInPane(toprow, leftcol);
- assertEquals(toprow, sheet.getTopRow(), "HSSFSheet.getTopRow()");
- assertEquals(leftcol, sheet.getLeftCol(), "HSSFSheet.getLeftCol()");
- }
- }
-
- @Test
- void addEmptyRow() throws IOException {
- //try to add 5 empty rows to a new sheet
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet sheet = wb1.createSheet();
- for (int i = 0; i < 5; i++) {
- sheet.createRow(i);
- }
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- HSSFSheet sheet2 = wb2.getSheetAt(0);
- assertNotNull(sheet2.getRow(4));
- }
- }
-
- //try adding empty rows in an existing worksheet
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls")) {
- HSSFSheet sheet = wb1.getSheetAt(0);
- for (int i = 3; i < 10; i++) {
- sheet.createRow(i);
- }
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- HSSFSheet sheet2 = wb2.getSheetAt(0);
- assertNotNull(sheet2.getRow(4));
- }
- }
- }
-
- @Test
- void autoSizeColumn() throws IOException {
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("43902.xls")) {
- String sheetName = "my sheet";
- HSSFSheet sheet = wb1.getSheet(sheetName);
-
- // Can't use literal numbers for column sizes, as
- // will come out with different values on different
- // machines based on the fonts available.
- // So, we use ranges, which are pretty large, but
- // thankfully don't overlap!
- int minWithRow1And2 = 6400;
- int maxWithRow1And2 = 7800;
- int minWithRow1Only = 2750;
- int maxWithRow1Only = 3400;
-
- // autoSize the first column and check its size before the merged region (1,0,1,1) is set:
- // it has to be based on the 2nd row width
- sheet.autoSizeColumn((short) 0);
- assertTrue(sheet.getColumnWidth(0) >= minWithRow1And2, "Column autosized with only one row: wrong width");
- assertTrue(sheet.getColumnWidth(0) <= maxWithRow1And2, "Column autosized with only one row: wrong width");
-
- //create a region over the 2nd row and auto size the first column
- assertEquals(1, sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 1)));
- assertNotNull(sheet.getMergedRegion(0));
- sheet.autoSizeColumn((short) 0);
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
-
- // check that the autoSized column width has ignored the 2nd row
- // because it is included in a merged region (Excel like behavior)
- HSSFSheet sheet2 = wb2.getSheet(sheetName);
- assertTrue(sheet2.getColumnWidth(0) >= minWithRow1Only);
- assertTrue(sheet2.getColumnWidth(0) <= maxWithRow1Only);
-
- // remove the 2nd row merged region and check that the 2nd row value is used to the autoSizeColumn width
- sheet2.removeMergedRegion(1);
- sheet2.autoSizeColumn((short) 0);
- try (HSSFWorkbook wb3 = writeOutAndReadBack(wb2)) {
- HSSFSheet sheet3 = wb3.getSheet(sheetName);
- assertTrue(sheet3.getColumnWidth(0) >= minWithRow1And2);
- assertTrue(sheet3.getColumnWidth(0) <= maxWithRow1And2);
- }
- }
- }
- }
-
- /**
- * Setting ForceFormulaRecalculation on sheets
- */
- @Test
- void forceRecalculation() throws IOException {
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("UncalcedRecord.xls")) {
-
- HSSFSheet sheet = wb1.getSheetAt(0);
- HSSFSheet sheet2 = wb1.getSheetAt(0);
- HSSFRow row = sheet.getRow(0);
- row.createCell(0).setCellValue(5);
- row.createCell(1).setCellValue(8);
- assertFalse(sheet.getForceFormulaRecalculation());
- assertFalse(sheet2.getForceFormulaRecalculation());
-
- // Save and manually verify that on column C we have 0, value in template
- writeOutAndReadBack(wb1).close();
- sheet.setForceFormulaRecalculation(true);
- assertTrue(sheet.getForceFormulaRecalculation());
-
- // Save and manually verify that on column C we have now 13, calculated value
- // Try it can be opened
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- // And check correct sheet settings found
- sheet = wb2.getSheetAt(0);
- sheet2 = wb2.getSheetAt(1);
- assertTrue(sheet.getForceFormulaRecalculation());
- assertFalse(sheet2.getForceFormulaRecalculation());
-
- // Now turn if back off again
- sheet.setForceFormulaRecalculation(false);
-
- try (HSSFWorkbook wb3 = writeOutAndReadBack(wb2)) {
- assertFalse(wb3.getSheetAt(0).getForceFormulaRecalculation());
- assertFalse(wb3.getSheetAt(1).getForceFormulaRecalculation());
- assertFalse(wb3.getSheetAt(2).getForceFormulaRecalculation());
-
- // Now add a new sheet, and check things work
- // with old ones unset, new one set
- HSSFSheet s4 = wb3.createSheet();
- s4.setForceFormulaRecalculation(true);
-
- assertFalse(sheet.getForceFormulaRecalculation());
- assertFalse(sheet2.getForceFormulaRecalculation());
- assertTrue(s4.getForceFormulaRecalculation());
-
- try (HSSFWorkbook wb4 = writeOutAndReadBack(wb3)) {
- assertFalse(wb4.getSheetAt(0).getForceFormulaRecalculation());
- assertFalse(wb4.getSheetAt(1).getForceFormulaRecalculation());
- assertFalse(wb4.getSheetAt(2).getForceFormulaRecalculation());
- assertTrue(wb4.getSheetAt(3).getForceFormulaRecalculation());
- }
- }
- }
- }
- }
-
- @Test
- void columnWidthA() throws IOException {
- // check we can correctly read column widths from a reference workbook
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("colwidth.xls")) {
-
- //reference values
- int[] ref = {365, 548, 731, 914, 1097, 1280, 1462, 1645, 1828, 2011, 2194, 2377, 2560, 2742, 2925, 3108, 3291, 3474, 3657};
-
- HSSFSheet sh = wb.getSheetAt(0);
- for (char i = 'A'; i <= 'S'; i++) {
- int idx = i - 'A';
- int w = sh.getColumnWidth(idx);
- assertEquals(ref[idx], w);
- }
-
- //the second sheet doesn't have overridden column widths
- sh = wb.getSheetAt(1);
- int def_width = sh.getDefaultColumnWidth();
- for (char i = 'A'; i <= 'S'; i++) {
- int idx = i - 'A';
- int w = sh.getColumnWidth(idx);
- //getDefaultColumnWidth returns width measured in characters
- //getColumnWidth returns width measured in 1/256th units
- assertEquals(def_width * 256, w);
- }
- }
-
- // test new workbook
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet sh = wb1.createSheet();
- sh.setDefaultColumnWidth(10);
- assertEquals(10, sh.getDefaultColumnWidth());
- assertEquals(256 * 10, sh.getColumnWidth(0));
- assertEquals(256 * 10, sh.getColumnWidth(1));
- assertEquals(256 * 10, sh.getColumnWidth(2));
- for (char i = 'D'; i <= 'F'; i++) {
- short w = (256 * 12);
- sh.setColumnWidth(i, w);
- assertEquals(w, sh.getColumnWidth(i));
- }
-
- //serialize and read again
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- sh = wb2.getSheetAt(0);
- assertEquals(10, sh.getDefaultColumnWidth());
- //columns A-C have default width
- assertEquals(256 * 10, sh.getColumnWidth(0));
- assertEquals(256 * 10, sh.getColumnWidth(1));
- assertEquals(256 * 10, sh.getColumnWidth(2));
- //columns D-F have custom width
- for (char i = 'D'; i <= 'F'; i++) {
- short w = (256 * 12);
- assertEquals(w, sh.getColumnWidth(i));
- }
-
- // check for 16-bit signed/unsigned error:
- sh.setColumnWidth(0, 40000);
- assertEquals(40000, sh.getColumnWidth(0));
- }
- }
- }
-
-
- @Test
- void defaultColumnWidth() throws IOException {
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook( "12843-1.xls" )) {
- HSSFSheet sheet = wb1.getSheetAt(7);
- // shall not be NPE
- assertEquals(8, sheet.getDefaultColumnWidth());
- assertEquals(8 * 256, sheet.getColumnWidth(0));
-
- assertEquals(0xFF, sheet.getDefaultRowHeight());
- }
-
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook( "34775.xls" )) {
- // second and third sheets miss DefaultColWidthRecord
- for (int i = 1; i <= 2; i++) {
- HSSFSheet sheet = wb2.getSheetAt(i);
- int dw = sheet.getDefaultColumnWidth();
- assertEquals(8, dw);
- int cw = sheet.getColumnWidth(0);
- assertEquals(8 * 256, cw);
-
- assertEquals(0xFF, sheet.getDefaultRowHeight());
- }
- }
- }
-
- /**
- * Some utilities write Excel files without the ROW records.
- * Excel, ooo, and google docs are OK with this.
- * Now POI is too.
- */
- @Test
- void missingRowRecords_bug41187() throws IOException {
- try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex41187-19267.xls")) {
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFRow row = sheet.getRow(0);
- assertNotNull(row, "Identified bug 41187 a");
-
- assertNotEquals((short) 0, row.getHeight(), "Identified bug 41187 b");
-
- assertEquals(row.getCell(0).getRichStringCellValue().getString(), "Hi Excel!");
- // check row height for 'default' flag
- assertEquals((short) 0xFF, row.getHeight());
-
- writeOutAndReadBack(wb).close();
- }
- }
-
- /**
- * If we clone a sheet containing drawings,
- * we must allocate a new ID of the drawing group and re-create shape IDs
- *
- * See bug #45720.
- */
- @Test
- void cloneSheetWithDrawings() throws IOException {
- try (HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("45720.xls")) {
- HSSFSheet sheet1 = wb1.getSheetAt(0);
-
- DrawingManager2 dm1 = wb1.getWorkbook().findDrawingGroup();
- int maxDrawingGroupId1 = dm1.getDgg().getMaxDrawingGroupId();
- wb1.cloneSheet(0);
-
- //check EscherDggRecord - a workbook-level registry of drawing objects
- assertEquals(maxDrawingGroupId1 + 1, dm1.getDgg().getMaxDrawingGroupId());
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- DrawingManager2 dm2 = wb2.getWorkbook().findDrawingGroup();
- assertEquals(maxDrawingGroupId1 + 1, dm2.getDgg().getMaxDrawingGroupId());
-
- HSSFSheet sheet2 = wb2.getSheetAt(1);
-
- //check that id of the drawing group was updated
- EscherDgRecord dg1 = (EscherDgRecord) sheet1.getDrawingPatriarch().getBoundAggregate().findFirstWithId(EscherDgRecord.RECORD_ID);
- EscherDgRecord dg2 = (EscherDgRecord) sheet2.getDrawingPatriarch().getBoundAggregate().findFirstWithId(EscherDgRecord.RECORD_ID);
- int dg_id_1 = dg1.getOptions() >> 4;
- int dg_id_2 = dg2.getOptions() >> 4;
- assertEquals(dg_id_1 + 1, dg_id_2);
-
- //TODO: check shapeId in the cloned sheet
- }
- }
- }
-
- /**
- * POI now (Sep 2008) allows sheet names longer than 31 chars (for other apps besides Excel).
- * Since Excel silently truncates to 31, make sure that POI enforces uniqueness on the first
- * 31 chars.
- */
- @Test
- void longSheetNames() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- final String SAME_PREFIX = "A123456789B123456789C123456789"; // 30 chars
-
- wb.createSheet(SAME_PREFIX + "Dxxxx");
- // identical up to the 32nd char
- IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> wb.createSheet(SAME_PREFIX + "Dyyyy"));
- assertEquals("The workbook already contains a sheet named 'A123456789B123456789C123456789Dyyyy'", e.getMessage());
-
- wb.createSheet(SAME_PREFIX + "Exxxx"); // OK - differs in the 31st char
- }
- }
-
- /**
- * Tests that we can read existing column styles
- */
- @Test
- void readColumnStyles() throws IOException {
- try (HSSFWorkbook wbNone = HSSFTestDataSamples.openSampleWorkbook("ColumnStyleNone.xls");
- HSSFWorkbook wbSimple = HSSFTestDataSamples.openSampleWorkbook("ColumnStyle1dp.xls");
- HSSFWorkbook wbComplex = HSSFTestDataSamples.openSampleWorkbook("ColumnStyle1dpColoured.xls")) {
-
- // Presence / absence checks
- assertNull(wbNone.getSheetAt(0).getColumnStyle(0));
- assertNull(wbNone.getSheetAt(0).getColumnStyle(1));
-
- assertNull(wbSimple.getSheetAt(0).getColumnStyle(0));
- assertNotNull(wbSimple.getSheetAt(0).getColumnStyle(1));
-
- assertNull(wbComplex.getSheetAt(0).getColumnStyle(0));
- assertNotNull(wbComplex.getSheetAt(0).getColumnStyle(1));
-
- // Details checks
- HSSFCellStyle bs = wbSimple.getSheetAt(0).getColumnStyle(1);
- assertNotNull(bs);
- assertEquals(62, bs.getIndex());
- assertEquals("#,##0.0_ ;\\-#,##0.0\\ ", bs.getDataFormatString());
- assertEquals("Calibri", bs.getFont(wbSimple).getFontName());
- assertEquals(11 * 20, bs.getFont(wbSimple).getFontHeight());
- assertEquals(8, bs.getFont(wbSimple).getColor());
- assertFalse(bs.getFont(wbSimple).getItalic());
- assertFalse(bs.getFont(wbSimple).getBold());
-
-
- HSSFCellStyle cs = wbComplex.getSheetAt(0).getColumnStyle(1);
- assertNotNull(cs);
- assertEquals(62, cs.getIndex());
- assertEquals("#,##0.0_ ;\\-#,##0.0\\ ", cs.getDataFormatString());
- assertEquals("Arial", cs.getFont(wbComplex).getFontName());
- assertEquals(8 * 20, cs.getFont(wbComplex).getFontHeight());
- assertEquals(10, cs.getFont(wbComplex).getColor());
- assertFalse(cs.getFont(wbComplex).getItalic());
- assertTrue(cs.getFont(wbComplex).getBold());
- }
- }
-
- /**
- * Tests the arabic setting
- */
- @Test
- void arabic() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
-
- assertFalse(s.isRightToLeft());
- s.setRightToLeft(true);
- assertTrue(s.isRightToLeft());
- }
- }
-
- @Test
- void autoFilter() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet sh = wb1.createSheet();
- InternalWorkbook iwb = wb1.getWorkbook();
- InternalSheet ish = sh.getSheet();
-
- assertNull(iwb.getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1));
- assertNull(ish.findFirstRecordBySid(AutoFilterInfoRecord.sid));
-
- CellRangeAddress range = CellRangeAddress.valueOf("A1:B10");
- sh.setAutoFilter(range);
-
- NameRecord name = iwb.getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1);
- assertNotNull(name);
-
- // The built-in name for auto-filter must consist of a single Area3d Ptg.
- Ptg[] ptg = name.getNameDefinition();
- assertEquals(1, ptg.length, "The built-in name for auto-filter must consist of a single Area3d Ptg");
- assertTrue(ptg[0] instanceof Area3DPtg, "The built-in name for auto-filter must consist of a single Area3d Ptg");
-
- Area3DPtg aref = (Area3DPtg) ptg[0];
- assertEquals(range.getFirstColumn(), aref.getFirstColumn());
- assertEquals(range.getFirstRow(), aref.getFirstRow());
- assertEquals(range.getLastColumn(), aref.getLastColumn());
- assertEquals(range.getLastRow(), aref.getLastRow());
-
- // verify AutoFilterInfoRecord
- AutoFilterInfoRecord afilter = (AutoFilterInfoRecord) ish.findFirstRecordBySid(AutoFilterInfoRecord.sid);
- assertNotNull(afilter);
- assertEquals(2, afilter.getNumEntries()); //filter covers two columns
-
- HSSFPatriarch dr = sh.getDrawingPatriarch();
- assertNotNull(dr);
- HSSFSimpleShape comboBoxShape = (HSSFSimpleShape) dr.getChildren().get(0);
- assertEquals(comboBoxShape.getShapeType(), HSSFSimpleShape.OBJECT_TYPE_COMBO_BOX);
-
- assertNull(ish.findFirstRecordBySid(ObjRecord.sid)); // ObjRecord will appear after serializetion
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- sh = wb2.getSheetAt(0);
- ish = sh.getSheet();
- ObjRecord objRecord = (ObjRecord) ish.findFirstRecordBySid(ObjRecord.sid);
- assertNotNull(objRecord);
- List subRecords = objRecord.getSubRecords();
- assertEquals(3, subRecords.size());
- assertTrue(subRecords.get(0) instanceof CommonObjectDataSubRecord);
- assertTrue(subRecords.get(1) instanceof FtCblsSubRecord); // must be present, see Bug 51481
- assertTrue(subRecords.get(2) instanceof LbsDataSubRecord);
- }
- }
- }
-
- @Test
- void getSetColumnHiddenShort() throws IOException {
- try (Workbook workbook = new HSSFWorkbook()) {
- Sheet sheet = workbook.createSheet("Sheet 1");
- sheet.setColumnHidden((short) 2, true);
- assertTrue(sheet.isColumnHidden((short) 2));
- }
- }
-
- @Test
- void columnWidthShort() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- Sheet sheet = wb1.createSheet();
-
- //default column width measured in characters
- sheet.setDefaultColumnWidth((short) 10);
- assertEquals(10, sheet.getDefaultColumnWidth());
- //columns A-C have default width
- assertEquals(256 * 10, sheet.getColumnWidth((short) 0));
- assertEquals(256 * 10, sheet.getColumnWidth((short) 1));
- assertEquals(256 * 10, sheet.getColumnWidth((short) 2));
-
- //set custom width for D-F
- for (char i = 'D'; i <= 'F'; i++) {
- //Sheet#setColumnWidth accepts the width in units of 1/256th of a character width
- int w = 256 * 12;
- sheet.setColumnWidth((short) i, w);
- assertEquals(w, sheet.getColumnWidth((short) i));
- }
- //reset the default column width, columns A-C change, D-F still have custom width
- sheet.setDefaultColumnWidth((short) 20);
- assertEquals(20, sheet.getDefaultColumnWidth());
- assertEquals(256 * 20, sheet.getColumnWidth((short) 0));
- assertEquals(256 * 20, sheet.getColumnWidth((short) 1));
- assertEquals(256 * 20, sheet.getColumnWidth((short) 2));
- for (char i = 'D'; i <= 'F'; i++) {
- int w = 256 * 12;
- assertEquals(w, sheet.getColumnWidth((short) i));
- }
-
- // check for 16-bit signed/unsigned error:
- sheet.setColumnWidth((short) 10, 40000);
- assertEquals(40000, sheet.getColumnWidth((short) 10));
-
- //The maximum column width for an individual cell is 255 characters
- Sheet sheet2 = sheet;
- IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () ->
- sheet2.setColumnWidth((short) 9, 256 * 256));
- assertEquals("The maximum column width for an individual cell is 255 characters.", e.getMessage());
-
- //serialize and read again
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
- sheet = wb2.getSheetAt(0);
- assertEquals(20, sheet.getDefaultColumnWidth());
- //columns A-C have default width
- assertEquals(256 * 20, sheet.getColumnWidth((short) 0));
- assertEquals(256 * 20, sheet.getColumnWidth((short) 1));
- assertEquals(256 * 20, sheet.getColumnWidth((short) 2));
- //columns D-F have custom width
- for (char i = 'D'; i <= 'F'; i++) {
- short w = (256 * 12);
- assertEquals(w, sheet.getColumnWidth((short) i));
- }
- assertEquals(40000, sheet.getColumnWidth((short) 10));
- }
- }
- }
-
- @Test
- void showInPane() throws IOException {
- try (Workbook wb = new HSSFWorkbook()) {
- Sheet sheet = wb.createSheet();
- sheet.showInPane(2, 3);
-
- IllegalArgumentException ex = assertThrows(
- IllegalArgumentException.class,
- () -> sheet.showInPane(Integer.MAX_VALUE, 3)
- );
- assertEquals("Maximum row number is 65535", ex.getMessage());
- }
- }
-
- @Test
- void drawingRecords() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
-
- /* TODO: NPE?
- sheet.dumpDrawingRecords(false);
- sheet.dumpDrawingRecords(true);*/
- assertNull(sheet.getDrawingEscherAggregate());
- }
- }
-
- @Test
- void bug55723b() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- Sheet sheet = wb.createSheet();
-
- // stored with a special name
- assertNull(wb.getWorkbook().getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1));
-
- CellRangeAddress range = CellRangeAddress.valueOf("A:B");
- AutoFilter filter = sheet.setAutoFilter(range);
- assertNotNull(filter);
-
- // stored with a special name
- NameRecord record = wb.getWorkbook().getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1);
- assertNotNull(record);
- }
- }
-
- @Test
- void test58746() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
-
- HSSFSheet first = wb.createSheet("first");
- first.createRow(0).createCell(0).setCellValue(1);
-
- HSSFSheet second = wb.createSheet("second");
- second.createRow(0).createCell(0).setCellValue(2);
-
- HSSFSheet third = wb.createSheet("third");
- HSSFRow row = third.createRow(0);
- row.createCell(0).setCellFormula("first!A1");
- row.createCell(1).setCellFormula("second!A1");
-
- // re-order for sheet "third"
- wb.setSheetOrder("third", 0);
-
- // verify results
- assertEquals("third", wb.getSheetAt(0).getSheetName());
- assertEquals("first", wb.getSheetAt(1).getSheetName());
- assertEquals("second", wb.getSheetAt(2).getSheetName());
-
- assertEquals("first!A1", wb.getSheetAt(0).getRow(0).getCell(0).getCellFormula());
- assertEquals("second!A1", wb.getSheetAt(0).getRow(0).getCell(1).getCellFormula());
- }
- }
-
- @Test
- void bug59135() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- wb1.createSheet().protectSheet("1111.2222.3333.1234");
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
-
- assertEquals((short) 0xb86b, wb2.getSheetAt(0).getPassword());
- }
- }
-
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- wb1.createSheet().protectSheet("1111.2222.3333.12345");
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
-
- assertEquals((short) 0xbecc, wb2.getSheetAt(0).getPassword());
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetAutosizeColumn.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetAutosizeColumn.java
deleted file mode 100644
index 340211560d..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetAutosizeColumn.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.hssf.usermodel;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.ss.usermodel.BaseTestSheetAutosizeColumn;
-
-/**
- * Test auto-sizing columns in HSSF
- */
-final class TestHSSFSheetAutosizeColumn extends BaseTestSheetAutosizeColumn {
-
- public TestHSSFSheetAutosizeColumn() {
- super(HSSFITestDataProvider.instance);
- }
-
-}
\ No newline at end of file
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftColumns.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftColumns.java
deleted file mode 100644
index 9333ac516a..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftColumns.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ====================================================================
- */
-package org.apache.poi.hssf.usermodel;
-
-import java.io.IOException;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.ss.usermodel.BaseTestSheetShiftColumns;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-class TestHSSFSheetShiftColumns extends BaseTestSheetShiftColumns {
- public TestHSSFSheetShiftColumns() {
- super();
- workbook = new HSSFWorkbook();
- _testDataProvider = HSSFITestDataProvider.instance;
- }
-
- protected Workbook openWorkbook(String spreadsheetFileName) {
- return HSSFTestDataSamples.openSampleWorkbook(spreadsheetFileName);
- }
-
- protected Workbook getReadBackWorkbook(Workbook wb) {
- return HSSFTestDataSamples.writeOutAndReadBack((HSSFWorkbook)wb);
- }
-
- @Override
- @Disabled("see ")
- protected void shiftMergedColumnsToMergedColumnsLeft() {
- // This override is used only in order to test failing for HSSF. Please remove method after code is fixed on hssf,
- // so that original method from BaseTestSheetShiftColumns can be executed.
- }
-
- @Override
- @Disabled("see ")
- protected void shiftMergedColumnsToMergedColumnsRight() {
- // This override is used only in order to test failing for HSSF. Please remove method after code is fixed on hssf,
- // so that original method from BaseTestSheetShiftColumns can be executed.
- }
-
- @Override
- @Disabled("see ")
- protected void testBug54524() {
- // This override is used only in order to test failing for HSSF. Please remove method after code is fixed on hssf,
- // so that original method from BaseTestSheetShiftColumns can be executed.
- }
-
- @Override
- @Disabled("see ")
- protected void testCommentsShifting() {
- // This override is used only in order to test failing for HSSF. Please remove method after code is fixed on hssf,
- // so that original method from BaseTestSheetShiftColumns can be executed.
- }
-
- @Override
- @Disabled("see ")
- protected void testShiftWithMergedRegions() {
- // This override is used only in order to test failing for HSSF. Please remove method after code is fixed on hssf,
- // so that original method from BaseTestSheetShiftColumns can be executed.
- // After removing, you can re-add 'final' keyword to specification of original method.
- }
-
- @Override
- @Disabled("see ")
- protected void testShiftHyperlinks() {}
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftRows.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftRows.java
deleted file mode 100644
index d78c3bf660..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftRows.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.hssf.usermodel;
-
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.ss.usermodel.BaseTestSheetShiftRows;
-
-/**
- * @author Yegor Kozlov
- */
-final class TestHSSFSheetShiftRows extends BaseTestSheetShiftRows {
-
- public TestHSSFSheetShiftRows() {
- super(HSSFITestDataProvider.instance);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java
deleted file mode 100644
index 33f6607988..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.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.hssf.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.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.POITestCase;
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.record.ArrayRecord;
-import org.apache.poi.hssf.record.FormulaRecord;
-import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate;
-import org.apache.poi.hssf.record.aggregates.RowRecordsAggregate;
-import org.apache.poi.hssf.record.aggregates.SharedValueManager;
-import org.apache.poi.ss.usermodel.BaseTestSheetUpdateArrayFormulas;
-import org.apache.poi.ss.usermodel.CellRange;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test array formulas in HSSF
- */
-final class TestHSSFSheetUpdateArrayFormulas extends BaseTestSheetUpdateArrayFormulas {
-
- public TestHSSFSheetUpdateArrayFormulas() {
- super(HSSFITestDataProvider.instance);
- }
-
- // Test methods common with XSSF are in superclass
- // Local methods here test HSSF-specific details of updating array formulas
- @Test
- void testHSSFSetArrayFormula_singleCell() throws IOException {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- HSSFSheet sheet = workbook.createSheet("Sheet1");
-
- CellRangeAddress range = new CellRangeAddress(2, 2, 2, 2);
- HSSFCell[] cells = sheet.setArrayFormula("SUM(C11:C12*D11:D12)", range).getFlattenedCells();
- assertEquals(1, cells.length);
-
- // sheet.setArrayFormula creates rows and cells for the designated range
- assertNotNull(sheet.getRow(2));
- HSSFCell cell = sheet.getRow(2).getCell(2);
- assertNotNull(cell);
-
- assertTrue(cell.isPartOfArrayFormulaGroup());
- //retrieve the range and check it is the same
- assertEquals(range.formatAsString(), cell.getArrayFormulaRange().formatAsString());
-
- FormulaRecordAggregate agg = (FormulaRecordAggregate) cell.getCellValueRecord();
- assertEquals(range.formatAsString(), agg.getArrayFormulaRange().formatAsString());
- assertTrue(agg.isPartOfArrayFormula());
- }
- }
-
- /**
- * Makes sure the internal state of HSSFSheet is consistent after removing array formulas
- */
- @Test
- void testAddRemoveArrayFormulas_recordUpdates() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet("Sheet1");
-
- CellRange cr = s.setArrayFormula("123", CellRangeAddress.valueOf("B5:C6"));
- List recs = new ArrayList<>();
- s.getSheet().visitContainedRecords(recs::add, 0);
-
- int ix = 0;
- for (org.apache.poi.hssf.record.Record r : recs) {
- if (r instanceof ArrayRecord) break;
- ix++;
- }
-
- assertNotEquals(ix, recs.size());
- Class>[] act = recs.subList(ix-1, ix+4).stream().map(Object::getClass).toArray(Class[]::new);
- Class>[] exp = { FormulaRecord.class, ArrayRecord.class, FormulaRecord.class, FormulaRecord.class, FormulaRecord.class };
- assertArrayEquals(exp, act);
-
- // just one array record
- assertFalse(recs.subList(ix + 1, recs.size()).stream().anyMatch(r -> r instanceof ArrayRecord));
-
- s.removeArrayFormula(cr.getTopLeftCell());
-
- // Make sure the array formula has been removed properly
- recs.clear();
- s.getSheet().visitContainedRecords(recs::add, 0);
-
- assertFalse(recs.stream().anyMatch(r -> r instanceof ArrayRecord || r instanceof FormulaRecord));
- RowRecordsAggregate rra = s.getSheet().getRowsAggregate();
-
- SharedValueManager svm = POITestCase.getFieldValue(RowRecordsAggregate.class, rra, SharedValueManager.class, "_sharedValueManager");
- assertNull(svm.getArrayRecord(4, 1), "Array record was not cleaned up properly.");
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFTextbox.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFTextbox.java
deleted file mode 100644
index 5d08d77e4c..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFTextbox.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.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.IOException;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Test HSSFTextbox .
- */
-final class TestHSSFTextbox {
-
- /**
- * Test that accessors to horizontal and vertical alignment work properly
- */
- @Test
- void testAlignment() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sh1 = wb.createSheet();
- HSSFPatriarch patriarch = sh1.createDrawingPatriarch();
-
- HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 6, 4));
- HSSFRichTextString str = new HSSFRichTextString("Hello, World");
- textbox.setString(str);
- textbox.setHorizontalAlignment(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED);
- textbox.setVerticalAlignment(HSSFTextbox.VERTICAL_ALIGNMENT_CENTER);
-
- assertEquals(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED, textbox.getHorizontalAlignment());
- assertEquals(HSSFTextbox.VERTICAL_ALIGNMENT_CENTER, textbox.getVerticalAlignment());
- }
- }
-
- /**
- * Excel requires at least one format run in HSSFTextbox.
- * When inserting text make sure that if font is not set we must set the default one.
- */
- @Test
- void testSetDeafultTextFormat() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet sheet = wb.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- HSSFTextbox textbox1 = patriarch.createTextbox(new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 3, 3));
- HSSFRichTextString rt1 = new HSSFRichTextString("Hello, World!");
- assertEquals(0, rt1.numFormattingRuns());
- textbox1.setString(rt1);
-
- HSSFRichTextString rt2 = textbox1.getString();
- assertEquals(1, rt2.numFormattingRuns());
- assertEquals(HSSFRichTextString.NO_FONT, rt2.getFontOfFormattingRun(0));
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java
deleted file mode 100644
index ac4f32cb0e..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java
+++ /dev/null
@@ -1,1189 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.apache.poi.POITestCase.assertContains;
-import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook;
-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.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.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Supplier;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.ddf.EscherBSERecord;
-import org.apache.poi.hpsf.ClassID;
-import org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.OldExcelFormatException;
-import org.apache.poi.hssf.model.HSSFFormulaParser;
-import org.apache.poi.hssf.model.InternalSheet;
-import org.apache.poi.hssf.model.InternalWorkbook;
-import org.apache.poi.hssf.record.CFRuleRecord;
-import org.apache.poi.hssf.record.HSSFRecordTypes;
-import org.apache.poi.hssf.record.NameRecord;
-import org.apache.poi.hssf.record.Record;
-import org.apache.poi.hssf.record.RecordBase;
-import org.apache.poi.hssf.record.WindowOneRecord;
-import org.apache.poi.poifs.filesystem.DirectoryEntry;
-import org.apache.poi.poifs.filesystem.DirectoryNode;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.ss.formula.ptg.Area3DPtg;
-import org.apache.poi.ss.usermodel.BaseTestWorkbook;
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.ConditionalFormatting;
-import org.apache.poi.ss.usermodel.ConditionalFormattingRule;
-import org.apache.poi.ss.usermodel.Name;
-import org.apache.poi.ss.usermodel.Row;
-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.util.IOUtils;
-import org.apache.poi.util.TempFile;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.CsvSource;
-
-/**
- * Tests for {@link HSSFWorkbook}
- */
-public final class TestHSSFWorkbook extends BaseTestWorkbook {
- private static final HSSFITestDataProvider _testDataProvider = HSSFITestDataProvider.instance;
- private static final POIDataSamples samples = POIDataSamples.getSpreadSheetInstance();
-
- public TestHSSFWorkbook() {
- super(_testDataProvider);
- }
-
- /**
- * gives test code access to the {@link InternalWorkbook} within {@link HSSFWorkbook}
- */
- public static InternalWorkbook getInternalWorkbook(HSSFWorkbook wb) {
- return wb.getWorkbook();
- }
-
- /**
- * Tests for {@link HSSFWorkbook#isHidden()} etc
- */
- @Test
- void hidden() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- WindowOneRecord w1 = wb.getWorkbook().getWindowOne();
-
- assertFalse(wb.isHidden());
- assertFalse(w1.getHidden());
-
- wb.setHidden(true);
- assertTrue(wb.isHidden());
- assertTrue(w1.getHidden());
-
- HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
- w1 = wbBack.getWorkbook().getWindowOne();
-
- wbBack.setHidden(true);
- assertTrue(wbBack.isHidden());
- assertTrue(w1.getHidden());
-
- wbBack.setHidden(false);
- assertFalse(wbBack.isHidden());
- assertFalse(w1.getHidden());
-
- wbBack.close();
- wb.close();
- }
-
- @Test
- void readWriteWithCharts() throws IOException {
- Sheet s;
-
- // Single chart, two sheets
- HSSFWorkbook b1 = openSampleWorkbook("44010-SingleChart.xls");
- assertEquals(2, b1.getNumberOfSheets());
- assertEquals("Graph2", b1.getSheetName(1));
- s = b1.getSheetAt(1);
- assertEquals(0, s.getFirstRowNum());
- assertEquals(8, s.getLastRowNum());
-
- // Has chart on 1st sheet??
- // FIXME
- assertNotNull(b1.getSheetAt(0).getDrawingPatriarch());
- assertNull(b1.getSheetAt(1).getDrawingPatriarch());
- assertFalse(b1.getSheetAt(0).getDrawingPatriarch().containsChart());
- b1.close();
-
- // We've now called getDrawingPatriarch() so
- // everything will be all screwy
- // So, start again
- HSSFWorkbook b2 = openSampleWorkbook("44010-SingleChart.xls");
-
- HSSFWorkbook b3 = HSSFTestDataSamples.writeOutAndReadBack(b2);
- b2.close();
-
- assertEquals(2, b3.getNumberOfSheets());
- s = b3.getSheetAt(1);
- assertEquals(0, s.getFirstRowNum());
- assertEquals(8, s.getLastRowNum());
- b3.close();
-
- // Two charts, three sheets
- HSSFWorkbook b4 = openSampleWorkbook("44010-TwoCharts.xls");
- assertEquals(3, b4.getNumberOfSheets());
-
- s = b4.getSheetAt(1);
- assertEquals(0, s.getFirstRowNum());
- assertEquals(8, s.getLastRowNum());
- s = b4.getSheetAt(2);
- assertEquals(0, s.getFirstRowNum());
- assertEquals(8, s.getLastRowNum());
-
- // Has chart on 1st sheet??
- // FIXME
- assertNotNull(b4.getSheetAt(0).getDrawingPatriarch());
- assertNull(b4.getSheetAt(1).getDrawingPatriarch());
- assertNull(b4.getSheetAt(2).getDrawingPatriarch());
- assertFalse(b4.getSheetAt(0).getDrawingPatriarch().containsChart());
- b4.close();
-
- // We've now called getDrawingPatriarch() so
- // everything will be all screwy
- // So, start again
- HSSFWorkbook b5 = openSampleWorkbook("44010-TwoCharts.xls");
-
- Workbook b6 = HSSFTestDataSamples.writeOutAndReadBack(b5);
- b5.close();
- assertEquals(3, b6.getNumberOfSheets());
-
- s = b6.getSheetAt(1);
- assertEquals(0, s.getFirstRowNum());
- assertEquals(8, s.getLastRowNum());
- s = b6.getSheetAt(2);
- assertEquals(0, s.getFirstRowNum());
- assertEquals(8, s.getLastRowNum());
- b6.close();
- }
-
- @Test
- void selectedSheet_bug44523() throws IOException {
- HSSFWorkbook wb=new HSSFWorkbook();
- HSSFSheet sheet1 = wb.createSheet("Sheet1");
- HSSFSheet sheet2 = wb.createSheet("Sheet2");
- HSSFSheet sheet3 = wb.createSheet("Sheet3");
- HSSFSheet sheet4 = wb.createSheet("Sheet4");
-
- confirmActiveSelected(sheet1, true);
- confirmActiveSelected(sheet2, false);
- confirmActiveSelected(sheet3, false);
- confirmActiveSelected(sheet4, false);
-
- wb.setSelectedTab(1);
-
- // Demonstrate bug 44525:
- // Well... not quite, since isActive + isSelected were also added in the same bug fix
- assertFalse(sheet1.isSelected(), "Identified bug 44523 a");
- wb.setActiveSheet(1);
- assertFalse(sheet1.isActive(), "Identified bug 44523 b");
-
- confirmActiveSelected(sheet1, false);
- confirmActiveSelected(sheet2, true);
- confirmActiveSelected(sheet3, false);
- confirmActiveSelected(sheet4, false);
-
- wb.close();
- }
-
- private static List arrayToList(int[] array) {
- List list = new ArrayList<>(array.length);
- for ( Integer element : array ) {
- list.add(element);
- }
- return list;
- }
-
- private static void assertCollectionsEquals(Collection expected, Collection actual) {
- assertEquals(expected.size(), actual.size());
- for (int e : expected) {
- assertTrue(actual.contains(e));
- }
- for (int a : actual) {
- assertTrue(expected.contains(a));
- }
- }
-
- @Test
- void selectMultiple() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet0 = wb.createSheet("Sheet0");
- HSSFSheet sheet1 = wb.createSheet("Sheet1");
- HSSFSheet sheet2 = wb.createSheet("Sheet2");
- HSSFSheet sheet3 = wb.createSheet("Sheet3");
- HSSFSheet sheet4 = wb.createSheet("Sheet4");
- HSSFSheet sheet5 = wb.createSheet("Sheet5");
-
-
- List selected = arrayToList(new int[] { 0, 2, 3 });
- wb.setSelectedTabs(selected);
-
- assertCollectionsEquals(selected, wb.getSelectedTabs());
- assertTrue(sheet0.isSelected());
- assertFalse(sheet1.isSelected());
- assertTrue(sheet2.isSelected());
- assertTrue(sheet3.isSelected());
- assertFalse(sheet4.isSelected());
- assertFalse(sheet5.isSelected());
-
- selected = arrayToList(new int[] { 1, 3, 5 });
- wb.setSelectedTabs(selected);
-
- // previous selection should be cleared
- assertCollectionsEquals(selected, wb.getSelectedTabs());
- assertFalse(sheet0.isSelected());
- assertTrue(sheet1.isSelected());
- assertFalse(sheet2.isSelected());
- assertTrue(sheet3.isSelected());
- assertFalse(sheet4.isSelected());
- assertTrue(sheet5.isSelected());
-
- assertTrue(sheet0.isActive());
- assertFalse(sheet2.isActive());
- wb.setActiveSheet(2);
- assertFalse(sheet0.isActive());
- assertTrue(sheet2.isActive());
-
- wb.close();
- }
-
-
- @Test
- void activeSheetAfterDelete_bug40414() throws IOException {
- HSSFWorkbook wb=new HSSFWorkbook();
- HSSFSheet sheet0 = wb.createSheet("Sheet0");
- HSSFSheet sheet1 = wb.createSheet("Sheet1");
- HSSFSheet sheet2 = wb.createSheet("Sheet2");
- HSSFSheet sheet3 = wb.createSheet("Sheet3");
- HSSFSheet sheet4 = wb.createSheet("Sheet4");
-
- // confirm default activation/selection
- confirmActiveSelected(sheet0, true);
- confirmActiveSelected(sheet1, false);
- confirmActiveSelected(sheet2, false);
- confirmActiveSelected(sheet3, false);
- confirmActiveSelected(sheet4, false);
-
- wb.setActiveSheet(3);
- wb.setSelectedTab(3);
-
- confirmActiveSelected(sheet0, false);
- confirmActiveSelected(sheet1, false);
- confirmActiveSelected(sheet2, false);
- confirmActiveSelected(sheet3, true);
- confirmActiveSelected(sheet4, false);
-
- wb.removeSheetAt(3);
- // after removing the only active/selected sheet, another should be active/selected in its place
- assertTrue(sheet4.isSelected(), "identified bug 40414 a");
- assertTrue(sheet4.isActive(), "identified bug 40414 b");
-
- confirmActiveSelected(sheet0, false);
- confirmActiveSelected(sheet1, false);
- confirmActiveSelected(sheet2, false);
- confirmActiveSelected(sheet4, true);
-
- sheet3 = sheet4; // re-align local vars in this test case
-
- // Some more cases of removing sheets
-
- // Starting with a multiple selection, and different active sheet
- wb.setSelectedTabs(new int[] { 1, 3, });
- wb.setActiveSheet(2);
- confirmActiveSelected(sheet0, false, false);
- confirmActiveSelected(sheet1, false, true);
- confirmActiveSelected(sheet2, true, false);
- confirmActiveSelected(sheet3, false, true);
-
- // removing a sheet that is not active, and not the only selected sheet
- wb.removeSheetAt(3);
- confirmActiveSelected(sheet0, false, false);
- confirmActiveSelected(sheet1, false, true);
- confirmActiveSelected(sheet2, true, false);
-
- // removing the only selected sheet
- wb.removeSheetAt(1);
- confirmActiveSelected(sheet0, false, false);
- confirmActiveSelected(sheet2, true, true);
-
- // The last remaining sheet should always be active+selected
- wb.removeSheetAt(1);
- confirmActiveSelected(sheet0, true, true);
-
- wb.close();
- }
-
- private static void confirmActiveSelected(HSSFSheet sheet, boolean expected) {
- confirmActiveSelected(sheet, expected, expected);
- }
-
-
- private static void confirmActiveSelected(HSSFSheet sheet,
- boolean expectedActive, boolean expectedSelected) {
- assertEquals(expectedActive, sheet.isActive(), "active");
- assertEquals(expectedSelected, sheet.isSelected(), "selected");
- }
-
- /**
- * If Sheet.getSize() returns a different result to Sheet.serialize(), this will cause the BOF
- * records to be written with invalid offset indexes. Excel does not like this, and such
- * errors are particularly hard to track down. This test ensures that HSSFWorkbook throws
- * a specific exception as soon as the situation is detected. See bugzilla 45066
- */
- @Test
- void sheetSerializeSizeMismatch_bug45066() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- InternalSheet sheet = wb.createSheet("Sheet1").getSheet();
- List sheetRecords = sheet.getRecords();
- // one way (of many) to cause the discrepancy is with a badly behaved record:
- sheetRecords.add(new BadlyBehavedRecord());
- // There is also much logic inside Sheet that (if buggy) might also cause the discrepancy
- IllegalStateException e = assertThrows(IllegalStateException.class, wb::getBytes, "Identified bug 45066 a");
- assertTrue(e.getMessage().startsWith("Actual serialized sheet size"));
- }
- }
-
- /**
- * Checks that us and HSSFName play nicely with named ranges
- * that point to deleted sheets
- */
- @Test
- void namesToDeleteSheets() throws IOException {
- HSSFWorkbook b = openSampleWorkbook("30978-deleted.xls");
- assertEquals(3, b.getNumberOfNames());
-
- // Sheet 2 is deleted
- assertEquals("Sheet1", b.getSheetName(0));
- assertEquals("Sheet3", b.getSheetName(1));
-
- Area3DPtg ptg;
- NameRecord nr;
- HSSFName n;
-
- /* ======= Name pointing to deleted sheet ====== */
-
- // First at low level
- nr = b.getWorkbook().getNameRecord(0);
- assertEquals("On2", nr.getNameText());
- assertEquals(0, nr.getSheetNumber());
- assertEquals(1, nr.getExternSheetNumber());
- assertEquals(1, nr.getNameDefinition().length);
-
- ptg = (Area3DPtg)nr.getNameDefinition()[0];
- assertEquals(1, ptg.getExternSheetIndex());
- assertEquals(0, ptg.getFirstColumn());
- assertEquals(0, ptg.getFirstRow());
- assertEquals(0, ptg.getLastColumn());
- assertEquals(2, ptg.getLastRow());
-
- // Now at high level
- n = b.getNameAt(0);
- assertEquals("On2", n.getNameName());
- assertEquals("", n.getSheetName());
- assertEquals("#REF!$A$1:$A$3", n.getRefersToFormula());
-
-
- /* ======= Name pointing to 1st sheet ====== */
-
- // First at low level
- nr = b.getWorkbook().getNameRecord(1);
- assertEquals("OnOne", nr.getNameText());
- assertEquals(0, nr.getSheetNumber());
- assertEquals(0, nr.getExternSheetNumber());
- assertEquals(1, nr.getNameDefinition().length);
-
- ptg = (Area3DPtg)nr.getNameDefinition()[0];
- assertEquals(0, ptg.getExternSheetIndex());
- assertEquals(0, ptg.getFirstColumn());
- assertEquals(2, ptg.getFirstRow());
- assertEquals(0, ptg.getLastColumn());
- assertEquals(3, ptg.getLastRow());
-
- // Now at high level
- n = b.getNameAt(1);
- assertEquals("OnOne", n.getNameName());
- assertEquals("Sheet1", n.getSheetName());
- assertEquals("Sheet1!$A$3:$A$4", n.getRefersToFormula());
-
-
- /* ======= Name pointing to 3rd sheet ====== */
-
- // First at low level
- nr = b.getWorkbook().getNameRecord(2);
- assertEquals("OnSheet3", nr.getNameText());
- assertEquals(0, nr.getSheetNumber());
- assertEquals(2, nr.getExternSheetNumber());
- assertEquals(1, nr.getNameDefinition().length);
-
- ptg = (Area3DPtg)nr.getNameDefinition()[0];
- assertEquals(2, ptg.getExternSheetIndex());
- assertEquals(0, ptg.getFirstColumn());
- assertEquals(0, ptg.getFirstRow());
- assertEquals(0, ptg.getLastColumn());
- assertEquals(1, ptg.getLastRow());
-
- // Now at high level
- n = b.getNameAt(2);
- assertEquals("OnSheet3", n.getNameName());
- assertEquals("Sheet3", n.getSheetName());
- assertEquals("Sheet3!$A$1:$A$2", n.getRefersToFormula());
-
- b.close();
- }
-
- /**
- * result returned by getRecordSize() differs from result returned by serialize()
- */
- private static final class BadlyBehavedRecord extends Record {
- BadlyBehavedRecord() {
- //
- }
- @Override
- public short getSid() {
- return 0x777;
- }
- @Override
- public int serialize(int offset, byte[] data) {
- return 4;
- }
- @Override
- public int getRecordSize() {
- return 8;
- }
- @Override
- public BadlyBehavedRecord copy() {
- return null;
- }
-
- @Override
- public HSSFRecordTypes getGenericRecordType() {
- return null;
- }
-
- @Override
- public Map> getGenericProperties() {
- return null;
- }
- }
-
- /**
- * The sample file provided with bug 45582 seems to have one extra byte after the EOFRecord
- */
- @Test
- void extraDataAfterEOFRecord() throws IOException {
- // bug 45582 - RecordFormatException - getCause() instanceof LittleEndian.BufferUnderrunException
- try (HSSFWorkbook wb = openSampleWorkbook("ex45582-22397.xls")) {
- assertNotNull(wb);
- }
- }
-
- /**
- * Test to make sure that NameRecord.getSheetNumber() is interpreted as a
- * 1-based sheet tab index (not a 1-based extern sheet index)
- */
- @Test
- void findBuiltInNameRecord() throws IOException {
- // testRRaC has multiple (3) built-in name records
- // The second print titles name record has getSheetNumber()==4
- HSSFWorkbook wb1 = openSampleWorkbook("testRRaC.xls");
- NameRecord nr;
- assertEquals(3, wb1.getWorkbook().getNumNames());
- nr = wb1.getWorkbook().getNameRecord(2);
- // TODO - render full row and full column refs properly
- assertEquals("Sheet2!$A$1:$IV$1", HSSFFormulaParser.toFormulaString(wb1, nr.getNameDefinition())); // 1:1
-
- try {
- wb1.getSheetAt(3).setRepeatingRows(CellRangeAddress.valueOf("9:12"));
- wb1.getSheetAt(3).setRepeatingColumns(CellRangeAddress.valueOf("E:F"));
- } catch (RuntimeException e) {
- if (e.getMessage().equals("Builtin (7) already exists for sheet (4)")) {
- // there was a problem in the code which locates the existing print titles name record
- fail("Identified bug 45720b");
- }
- wb1.close();
- throw e;
- }
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- assertEquals(3, wb2.getWorkbook().getNumNames());
- nr = wb2.getWorkbook().getNameRecord(2);
- assertEquals("Sheet2!E:F,Sheet2!$A$9:$IV$12", HSSFFormulaParser.toFormulaString(wb2, nr.getNameDefinition())); // E:F,9:12
- wb2.close();
- }
-
- /**
- * Test that the storage clsid property is preserved
- */
- @Test
- void bug47920() throws IOException {
- POIFSFileSystem fs1 = new POIFSFileSystem(samples.openResourceAsStream("47920.xls"));
- HSSFWorkbook wb = new HSSFWorkbook(fs1);
- ClassID clsid1 = fs1.getRoot().getStorageClsid();
-
- ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
- wb.write(out);
- byte[] bytes = out.toByteArray();
- POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes));
- ClassID clsid2 = fs2.getRoot().getStorageClsid();
-
- assertEquals(clsid1, clsid2);
-
- fs2.close();
- wb.close();
- fs1.close();
- }
-
- /**
- * If we try to open an old (pre-97) workbook, we get a helpful
- * Exception give to explain what we've done wrong
- */
- @ParameterizedTest
- @CsvSource({
- "testEXCEL_4.xls,BIFF4",
- "testEXCEL_5.xls,BIFF5",
- "testEXCEL_95.xls,BIFF5"
- })
- void helpfulExceptionOnOldFiles(String file, String format) throws Exception {
- POIDataSamples xlsData = samples;
- try (InputStream is = xlsData.openResourceAsStream(file)) {
- OldExcelFormatException e = assertThrows(OldExcelFormatException.class, () -> new HSSFWorkbook(is),
- "Shouldn't be able to load an Excel " + format + " file");
- assertContains(e.getMessage(), format);
- }
- }
-
- /**
- * Tests that we can work with both {@link POIFSFileSystem}
- * and {@link POIFSFileSystem}
- */
- @Test
- void differentPOIFS() throws Exception {
- // Open the two filesystems
- DirectoryNode[] files = new DirectoryNode[2];
- try (POIFSFileSystem poifsFileSystem = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("Simple.xls"))) {
- files[0] = poifsFileSystem.getRoot();
- try (POIFSFileSystem poifsFileSystem2 = new POIFSFileSystem(HSSFTestDataSamples.getSampleFile("Simple.xls"))) {
- files[1] = poifsFileSystem2.getRoot();
-
- // Open without preserving nodes
- for (DirectoryNode dir : files) {
- HSSFWorkbook workbook = new HSSFWorkbook(dir, false);
- HSSFSheet sheet = workbook.getSheetAt(0);
- HSSFCell cell = sheet.getRow(0).getCell(0);
- assertEquals("replaceMe", cell.getRichStringCellValue().getString());
-
- workbook.close();
- }
-
- // Now re-check with preserving
- for (DirectoryNode dir : files) {
- HSSFWorkbook workbook = new HSSFWorkbook(dir, true);
- HSSFSheet sheet = workbook.getSheetAt(0);
- HSSFCell cell = sheet.getRow(0).getCell(0);
- assertEquals("replaceMe", cell.getRichStringCellValue().getString());
-
- workbook.close();
- }
- }
- }
- }
-
- @Test
- void wordDocEmbeddedInXls() throws IOException {
- // Open the two filesystems
- DirectoryNode[] files = new DirectoryNode[2];
- try (POIFSFileSystem poifsFileSystem = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("WithEmbeddedObjects.xls"))) {
- files[0] = poifsFileSystem.getRoot();
- try (POIFSFileSystem poifsFileSystem2 = new POIFSFileSystem(HSSFTestDataSamples.getSampleFile("WithEmbeddedObjects.xls"))) {
- files[1] = poifsFileSystem2.getRoot();
-
- // Check the embedded parts
- for (DirectoryNode root : files) {
- HSSFWorkbook hw = new HSSFWorkbook(root, true);
- List objects = hw.getAllEmbeddedObjects();
- boolean found = false;
- for (HSSFObjectData embeddedObject : objects) {
- if (embeddedObject.hasDirectoryEntry()) {
- DirectoryEntry dir = embeddedObject.getDirectory();
- if (dir instanceof DirectoryNode) {
- DirectoryNode dNode = (DirectoryNode) dir;
- if (dNode.hasEntry("WordDocument")) {
- found = true;
- break;
- }
- }
- }
- }
- assertTrue(found);
-
- hw.close();
- }
- }
- }
- }
-
- /**
- * Checks that we can open a workbook with POIFS, and write it out
- * again (via POIFS) and have it be valid
- */
- @Test
- void writeWorkbookFromPOIFS() throws IOException {
- try (InputStream is = HSSFTestDataSamples.openSampleFileStream("WithEmbeddedObjects.xls");
- POIFSFileSystem fs = new POIFSFileSystem(is)) {
-
- HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot(), true);
- assertEquals(3, wb.getNumberOfSheets());
- assertEquals("Root xls", wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
-
- HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
- assertEquals(3, wbBack.getNumberOfSheets());
- assertEquals("Root xls", wbBack.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
- wbBack.close();
-
- wb.close();
- }
- }
-
- @Test
- void cellStylesLimit() throws IOException {
- try (Workbook wb = new HSSFWorkbook()) {
- int numBuiltInStyles = wb.getNumCellStyles();
- int MAX_STYLES = 4030;
- int limit = MAX_STYLES - numBuiltInStyles;
- for (int i = 0; i < limit; i++) {
- wb.createCellStyle();
- }
-
- assertEquals(MAX_STYLES, wb.getNumCellStyles());
- IllegalStateException e = assertThrows(IllegalStateException.class, wb::createCellStyle);
- assertEquals("The maximum number of cell styles was exceeded. " +
- "You can define up to 4000 styles in a .xls workbook", e.getMessage());
- assertEquals(MAX_STYLES, wb.getNumCellStyles());
- }
- }
-
- @Test
- void setSheetOrderHSSF() throws IOException{
- Workbook wb = new HSSFWorkbook();
- Sheet s1 = wb.createSheet("first sheet");
- Sheet s2 = wb.createSheet("other sheet");
-
- Name name1 = wb.createName();
- name1.setNameName("name1");
- name1.setRefersToFormula("'first sheet'!D1");
-
- Name name2 = wb.createName();
- name2.setNameName("name2");
- name2.setRefersToFormula("'other sheet'!C1");
-
-
- Row s1r1 = s1.createRow(2);
- Cell c1 = s1r1.createCell(3);
- c1.setCellValue(30);
- Cell c2 = s1r1.createCell(2);
- c2.setCellFormula("SUM('other sheet'!C1,'first sheet'!C1)");
-
- Row s2r1 = s2.createRow(0);
- Cell c3 = s2r1.createCell(1);
- c3.setCellFormula("'first sheet'!D3");
- Cell c4 = s2r1.createCell(2);
- c4.setCellFormula("'other sheet'!D3");
-
- // conditional formatting
- SheetConditionalFormatting sheetCF = s1.getSheetConditionalFormatting();
-
- ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(
- CFRuleRecord.ComparisonOperator.BETWEEN, "'first sheet'!D1", "'other sheet'!D1");
-
- ConditionalFormattingRule [] cfRules = { rule1 };
-
- CellRangeAddress[] regions = {
- new CellRangeAddress(2, 4, 0, 0), // A3:A5
- };
- sheetCF.addConditionalFormatting(regions, cfRules);
-
- wb.setSheetOrder("other sheet", 0);
-
- // names
- //noinspection ConstantConditions
- assertEquals("'first sheet'!D1", wb.getName("name1").getRefersToFormula());
- //noinspection ConstantConditions
- assertEquals("'other sheet'!C1", wb.getName("name2").getRefersToFormula());
-
- // cells
- assertEquals("SUM('other sheet'!C1,'first sheet'!C1)", c2.getCellFormula());
- assertEquals("'first sheet'!D3", c3.getCellFormula());
- assertEquals("'other sheet'!D3", c4.getCellFormula());
-
- // conditional formatting
- ConditionalFormatting cf = sheetCF.getConditionalFormattingAt(0);
- assertEquals("'first sheet'!D1", cf.getRule(0).getFormula1());
- assertEquals("'other sheet'!D1", cf.getRule(0).getFormula2());
-
- wb.close();
- }
-
- @Test
- void clonePictures() throws IOException {
- HSSFWorkbook wb = openSampleWorkbook("SimpleWithImages.xls");
- InternalWorkbook iwb = wb.getWorkbook();
- iwb.findDrawingGroup();
-
- for(int pictureIndex=1; pictureIndex <= 4; pictureIndex++){
- EscherBSERecord bse = iwb.getBSERecord(pictureIndex);
- assertEquals(1, bse.getRef());
- }
-
- wb.cloneSheet(0);
- for(int pictureIndex=1; pictureIndex <= 4; pictureIndex++){
- EscherBSERecord bse = iwb.getBSERecord(pictureIndex);
- assertEquals(2, bse.getRef());
- }
-
- wb.cloneSheet(0);
- for(int pictureIndex=1; pictureIndex <= 4; pictureIndex++){
- EscherBSERecord bse = iwb.getBSERecord(pictureIndex);
- assertEquals(3, bse.getRef());
- }
-
- wb.close();
- }
-
- // Should throw exception about invalid POIFSFileSystem
- @Test
- void emptyDirectoryNode() throws IOException {
- try (POIFSFileSystem fs = new POIFSFileSystem()) {
- assertThrows(IllegalArgumentException.class, () -> new HSSFWorkbook(fs).close());
- }
- }
-
- @Test
- void selectedSheetShort() throws IOException {
- HSSFWorkbook wb=new HSSFWorkbook();
-
- HSSFSheet sheet1 = wb.createSheet("Sheet1");
- HSSFSheet sheet2 = wb.createSheet("Sheet2");
- HSSFSheet sheet3 = wb.createSheet("Sheet3");
- HSSFSheet sheet4 = wb.createSheet("Sheet4");
-
- confirmActiveSelected(sheet1, true);
- confirmActiveSelected(sheet2, false);
- confirmActiveSelected(sheet3, false);
- confirmActiveSelected(sheet4, false);
-
- wb.setSelectedTab((short)1);
-
- // Demonstrate bug 44525:
- // Well... not quite, since isActive + isSelected were also added in the same bug fix
- assertFalse(sheet1.isSelected(), "Identified bug 44523 a");
- wb.setActiveSheet(1);
- assertFalse(sheet1.isActive(), "Identified bug 44523 b");
-
- confirmActiveSelected(sheet1, false);
- confirmActiveSelected(sheet2, true);
- confirmActiveSelected(sheet3, false);
- confirmActiveSelected(sheet4, false);
-
- assertEquals(0, wb.getFirstVisibleTab());
- wb.setFirstVisibleTab((short)2);
- assertEquals(2, wb.getFirstVisibleTab());
-
- wb.close();
- }
-
- @Test
- void names() throws IOException {
- HSSFWorkbook wb=new HSSFWorkbook();
-
- IllegalStateException ex1 = assertThrows(IllegalStateException.class, () -> wb.getNameAt(0));
- assertTrue(ex1.getMessage().contains("no defined names"));
-
- HSSFName name = wb.createName();
- assertNotNull(name);
-
- assertNull(wb.getName("somename"));
-
- name.setNameName("myname");
- assertNotNull(wb.getName("myname"));
-
- assertEquals(0, wb.getNameIndex(name));
- assertEquals(0, wb.getNameIndex("myname"));
-
- IllegalArgumentException ex2 = assertThrows(IllegalArgumentException.class, () -> wb.getNameAt(5));
- assertTrue(ex2.getMessage().contains("outside the allowable range"));
-
- IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> wb.getNameAt(-3));
- assertTrue(ex.getMessage().contains("outside the allowable range"));
-
- wb.close();
- }
-
- @Test
- void testMethods() throws IOException {
- try (HSSFWorkbook wb=new HSSFWorkbook()) {
- assertDoesNotThrow(wb::insertChartRecord);
- //wb.dumpDrawingGroupRecords(true);
- //wb.dumpDrawingGroupRecords(false);
- }
- }
-
- @Test
- void writeProtection() throws IOException {
- HSSFWorkbook wb=new HSSFWorkbook();
-
- assertFalse(wb.isWriteProtected());
-
- wb.writeProtectWorkbook("mypassword", "myuser");
- assertTrue(wb.isWriteProtected());
-
- wb.unwriteProtectWorkbook();
- assertFalse(wb.isWriteProtected());
-
- wb.close();
- }
-
- @Test
- void bug50298() throws Exception {
- HSSFWorkbook wb = openSampleWorkbook("50298.xls");
-
- assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received");
-
- HSSFSheet sheet = wb.cloneSheet(0);
-
- assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "Invoice (2)");
-
- wb.setSheetName(wb.getSheetIndex(sheet), "copy");
-
- assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "copy");
-
- wb.setSheetOrder("copy", 0);
-
- assertSheetOrder(wb, "copy", "Invoice", "Invoice1", "Digest", "Deferred", "Received");
-
- wb.removeSheetAt(0);
-
- assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received");
-
- // check that the overall workbook serializes with its correct size
- int expected = wb.getWorkbook().getSize();
- int written = wb.getWorkbook().serialize(0, new byte[expected*2]);
-
- assertEquals(expected, written, "Did not have the expected size when writing the workbook");
-
- HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb);
- assertSheetOrder(read, "Invoice", "Invoice1", "Digest", "Deferred", "Received");
- read.close();
- wb.close();
- }
-
- @Test
- void bug50298a() throws Exception {
- HSSFWorkbook wb = openSampleWorkbook("50298.xls");
-
- assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received");
-
- HSSFSheet sheet = wb.cloneSheet(0);
-
- assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "Invoice (2)");
-
- wb.setSheetName(wb.getSheetIndex(sheet), "copy");
-
- assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "copy");
-
- wb.setSheetOrder("copy", 0);
-
- assertSheetOrder(wb, "copy", "Invoice", "Invoice1", "Digest", "Deferred", "Received");
-
- wb.removeSheetAt(0);
-
- assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received");
-
- wb.removeSheetAt(1);
-
- assertSheetOrder(wb, "Invoice", "Digest", "Deferred", "Received");
-
- wb.setSheetOrder("Digest", 3);
-
- assertSheetOrder(wb, "Invoice", "Deferred", "Received", "Digest");
-
- // check that the overall workbook serializes with its correct size
- int expected = wb.getWorkbook().getSize();
- int written = wb.getWorkbook().serialize(0, new byte[expected*2]);
-
- assertEquals(expected, written, "Did not have the expected size when writing the workbook");
-
- HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb);
- assertSheetOrder(read, "Invoice", "Deferred", "Received", "Digest");
- read.close();
- wb.close();
- }
-
- @Test
- void bug54500() throws Exception {
- String nameName = "AName";
- String sheetName = "ASheet";
- HSSFWorkbook wb = openSampleWorkbook("54500.xls");
-
- assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3");
-
- wb.createSheet(sheetName);
-
- assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet");
-
- Name n = wb.createName();
- n.setNameName(nameName);
- n.setSheetIndex(3);
- n.setRefersToFormula(sheetName + "!A1");
-
- assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet");
- final HSSFName name = wb.getName(nameName);
- assertNotNull(name);
- assertEquals("ASheet!A1", name.getRefersToFormula());
-
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- wb.write(stream);
-
- assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet");
- assertEquals("ASheet!A1", name.getRefersToFormula());
-
- wb.removeSheetAt(1);
-
- assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet");
- assertEquals("ASheet!A1", name.getRefersToFormula());
-
- ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
- wb.write(stream2);
-
- assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet");
- assertEquals("ASheet!A1", name.getRefersToFormula());
-
- HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(stream.toByteArray()));
- expectName(wb2, nameName, "ASheet!A1");
- HSSFWorkbook wb3 = new HSSFWorkbook(new ByteArrayInputStream(stream2.toByteArray()));
- expectName(wb3, nameName, "ASheet!A1");
- wb3.close();
- wb2.close();
- wb.close();
- }
-
- @SuppressWarnings("SameParameterValue")
- private void expectName(HSSFWorkbook wb, String name, String expect) {
- final HSSFName hssfName = wb.getName(name);
- assertNotNull(hssfName);
- assertEquals(expect, hssfName.getRefersToFormula());
- }
-
- @Test
- void test49423() throws Exception
- {
- HSSFWorkbook workbook = openSampleWorkbook("49423.xls");
-
- boolean found = false;
- int numSheets = workbook.getNumberOfSheets();
- for (int i = 0; i < numSheets; i++) {
- HSSFSheet sheet = workbook.getSheetAt(i);
- List shapes = sheet.getDrawingPatriarch().getChildren();
- for(HSSFShape shape : shapes){
- HSSFAnchor anchor = shape.getAnchor();
-
- if(anchor instanceof HSSFClientAnchor){
- // absolute coordinates
- HSSFClientAnchor clientAnchor = (HSSFClientAnchor)anchor;
- assertNotNull(clientAnchor);
- //System.out.println(clientAnchor.getRow1() + "," + clientAnchor.getRow2());
- found = true;
- } else if (anchor instanceof HSSFChildAnchor){
- // shape is grouped and the anchor is expressed in the coordinate system of the group
- HSSFChildAnchor childAnchor = (HSSFChildAnchor)anchor;
- assertNotNull(childAnchor);
- //System.out.println(childAnchor.getDy1() + "," + childAnchor.getDy2());
- found = true;
- }
- }
- }
-
- assertTrue(found, "Should find some images via Client or Child anchors, but did not find any at all");
- workbook.close();
- }
-
- @Test
- void testRewriteFileBug58480() throws IOException {
- final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls");
-
- try {
- // create new workbook
- {
- final Workbook workbook = new HSSFWorkbook();
- final Sheet sheet = workbook.createSheet("foo");
- final Row row = sheet.createRow(1);
- row.createCell(1).setCellValue("bar");
-
- writeAndCloseWorkbook(workbook, file);
- }
-
- // edit the workbook
- {
- try (POIFSFileSystem fs = new POIFSFileSystem(file, false)) {
- DirectoryNode root = fs.getRoot();
- final Workbook workbook = new HSSFWorkbook(root, true);
- final Sheet sheet = workbook.getSheet("foo");
- sheet.getRow(1).createCell(2).setCellValue("baz");
-
- writeAndCloseWorkbook(workbook, file);
- }
- }
- } finally {
- assertTrue(file.exists());
- assertTrue(file.delete());
- }
- }
-
- private void writeAndCloseWorkbook(Workbook workbook, File file)
- throws IOException {
- final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
- workbook.write(bytesOut);
- workbook.close();
-
- final byte[] byteArray = bytesOut.toByteArray();
- bytesOut.close();
-
- final FileOutputStream fileOut = new FileOutputStream(file);
- fileOut.write(byteArray);
- fileOut.close();
-
- }
-
- @Test
- void closeDoesNotModifyWorkbook() throws IOException {
- final String filename = "SampleSS.xls";
- final File file = samples.getFile(filename);
- Workbook wb;
-
- // File via POIFileStream (java.nio)
- wb = new HSSFWorkbook(new POIFSFileSystem(file));
- assertCloseDoesNotModifyFile(filename, wb);
-
- // InputStream
- wb = new HSSFWorkbook(new FileInputStream(file));
- assertCloseDoesNotModifyFile(filename, wb);
- }
-
- @Test
- void setSheetOrderToEnd() throws Exception {
- try (HSSFWorkbook workbook = new HSSFWorkbook()) {
- workbook.createSheet("A");
- workbook.createSheet("B");
- assertEquals("A", workbook.getSheetName(0));
- workbook.setSheetOrder("A", 1);
- assertEquals("A", workbook.getSheetName(1));
- }
- }
-
- @Test
- void invalidInPlaceWrite() throws Exception {
- // Can't work for new files
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- assertThrows(IllegalStateException.class, wb::write, "Shouldn't work for new files");
- }
-
- // Can't work for InputStream opened files
- try (InputStream is = samples.openResourceAsStream("SampleSS.xls");
- HSSFWorkbook wb = new HSSFWorkbook(is)) {
- assertThrows(IllegalStateException.class, wb::write, "Shouldn't work for InputStream");
- }
-
- // Can't work for Read-Only files
- try (POIFSFileSystem fs = new POIFSFileSystem(samples.getFile("SampleSS.xls"), true);
- HSSFWorkbook wb = new HSSFWorkbook(fs)) {
- assertThrows(IllegalStateException.class, wb::write, "Shouldn't work for Read Only");
- }
- }
-
- @Test
- void inPlaceWrite() throws Exception {
- // Setup as a copy of a known-good file
- final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls");
- try (InputStream inputStream = samples.openResourceAsStream("SampleSS.xls");
- FileOutputStream outputStream = new FileOutputStream(file)) {
- IOUtils.copy(inputStream, outputStream);
- }
-
- // Open from the temp file in read-write mode
- HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(file, false));
- assertEquals(3, wb.getNumberOfSheets());
-
- // Change
- wb.removeSheetAt(2);
- wb.removeSheetAt(1);
- wb.getSheetAt(0).getRow(0).getCell(0).setCellValue("Changed!");
-
- // Save in-place, close, re-open and check
- wb.write();
- wb.close();
-
- wb = new HSSFWorkbook(new POIFSFileSystem(file));
- assertEquals(1, wb.getNumberOfSheets());
- assertEquals("Changed!", wb.getSheetAt(0).getRow(0).getCell(0).toString());
-
- wb.close();
- }
-
- @Test
- void testWriteToNewFile() throws Exception {
- // Save to a new temp file
- final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls");
-
- // Open from a Stream
- try (HSSFWorkbook wb = new HSSFWorkbook(
- samples.openResourceAsStream("SampleSS.xls"))) {
- wb.write(file);
- }
-
- // Read and check
- try (HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(file))) {
- assertEquals(3, wb.getNumberOfSheets());
- }
- }
-
- void createDrawing() throws Exception {
- // the dimensions for this image are different than for XSSF and SXSSF
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestMatrixFormulasFromBinarySpreadsheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestMatrixFormulasFromBinarySpreadsheet.java
deleted file mode 100644
index d56c3d6134..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestMatrixFormulasFromBinarySpreadsheet.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.hssf.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.hssf.HSSFTestDataSamples;
-import org.apache.poi.ss.formula.eval.ErrorEval;
-import org.apache.poi.ss.formula.functions.TestMathX;
-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;
-
-final class TestMatrixFormulasFromBinarySpreadsheet {
-
- private static final Logger LOG = LogManager.getLogger(TestMatrixFormulasFromBinarySpreadsheet.class);
-
-
- private static HSSFWorkbook 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.xls";
- /**
- * 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 = "";
-
- }
-
- /* Parameters for test case */
-
- @AfterAll
- public static void closeResource() throws Exception {
- LocaleUtil.setUserLocale(userLocale);
- workbook.close();
- }
-
- /* generating parameter instances */
- public static Stream 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 = HSSFTestDataSamples.openSampleWorkbook(Navigator.FILENAME);
- sheet = workbook.getSheetAt(0);
- evaluator = new HSSFFormulaEvaluator(workbook);
-
- List data = new ArrayList<>();
-
- processFunctionGroup(data);
-
- return data.stream();
- }
-
- private static void processFunctionGroup(List data) {
- int startRowIndex = Navigator.START_OPERATORS_ROW_INDEX;
- 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;
- }
- 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);
- break;
- case NUMERIC:
- assertEquals(CellType.NUMERIC, actValue.getCellType(), msg);
- TestMathX.assertDouble(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.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 null if cell is missing, empty or blank
- */
- private static String getTargetFunctionName(Row r) {
- if(r == null) {
- LOG.atWarn().log("Warning - given null row, can't figure out function name");
- return null;
- }
- Cell cell = r.getCell(Navigator.START_OPERATORS_COL_INDEX);
- LOG.atInfo().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/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java b/src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java
deleted file mode 100644
index 6f8bc8dfbb..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements. See the NOTICE file distributed with
-* this work for additional information regarding copyright ownership.
-* The ASF licenses this file to You under the Apache License, Version 2.0
-* (the "License"); you may not use this file except in compliance with
-* the License. You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.poi.hpsf.SummaryInformation;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.poifs.filesystem.DirectoryNode;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for how HSSFWorkbook behaves with XLS files
- * with a WORKBOOK or BOOK directory entry (instead of
- * the more usual, Workbook)
- */
-final class TestNonStandardWorkbookStreamNames {
- private final String xlsA = "WORKBOOK_in_capitals.xls";
- private final String xlsB = "BOOK_in_capitals.xls";
-
- /**
- * Test that we can open a file with WORKBOOK
- */
- @Test
- void testOpenWORKBOOK() throws IOException {
- // Try to open the workbook
- InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA);
- HSSFWorkbook wb = new HSSFWorkbook(is);
- is.close();
- DirectoryNode root = wb.getDirectory();
-
- // Ensure that we have a WORKBOOK entry and a summary
- assertTrue(root.hasEntry("WORKBOOK"));
- assertTrue(root.hasEntry(SummaryInformation.DEFAULT_STREAM_NAME));
-
- // But not a Workbook one
- assertFalse(root.hasEntry("Workbook"));
-
- wb.close();
- }
-
- /**
- * Test that we can open a file with BOOK
- */
- @Test
- void testOpenBOOK() throws IOException {
- // Try to open the workbook
- InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsB);
- HSSFWorkbook wb = new HSSFWorkbook(is);
- is.close();
- DirectoryNode root = wb.getDirectory();
-
- // Ensure that we have a BOOK entry
- assertTrue(root.hasEntry("BOOK"));
-
- // But not a Workbook one and not a Summary one
- assertFalse(root.hasEntry("Workbook"));
- assertFalse(root.hasEntry(SummaryInformation.DEFAULT_STREAM_NAME));
-
- wb.close();
- }
-
- /**
- * Test that when we write out, we go back to the correct case
- */
- @Test
- void testWrite() throws IOException {
- for (String file : new String[] {xlsA, xlsB}) {
- // Open the workbook, not preserving nodes
- InputStream is = HSSFTestDataSamples.openSampleFileStream(file);
- HSSFWorkbook wb = new HSSFWorkbook(is, false);
- is.close();
-
- // Check now it can be opened
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb);
- wb.close();
-
- DirectoryNode root = wb2.getDirectory();
-
- // Check that we have the new entries
- assertTrue(root.hasEntry("Workbook"));
- assertFalse(root.hasEntry("BOOK"));
- assertFalse(root.hasEntry("WORKBOOK"));
-
- wb2.close();
- }
- }
-
- /**
- * Test that when we write out preserving nodes, we go back to the
- * correct case
- */
- @Test
- void testWritePreserve() throws IOException {
- // Open the workbook, not preserving nodes
- InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA);
- HSSFWorkbook wb = new HSSFWorkbook(is,true);
- is.close();
-
- // Check now it can be opened
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb);
- wb.close();
-
- DirectoryNode root = wb2.getDirectory();
-
- // Check that we have the new entries
- assertTrue(root.hasEntry("Workbook"));
- assertFalse(root.hasEntry("BOOK"));
- assertFalse(root.hasEntry("WORKBOOK"));
-
- // As we preserved, should also have a few other streams
- assertTrue(root.hasEntry(SummaryInformation.DEFAULT_STREAM_NAME));
- wb2.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java b/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java
deleted file mode 100644
index 1183c5f6b5..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.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.hssf.usermodel;
-
-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 java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.poifs.filesystem.DirectoryNode;
-import org.apache.poi.poifs.filesystem.Ole10Native;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
-import org.apache.poi.ss.usermodel.CreationHelper;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.Test;
-
-final class TestOLE2Embeding {
-
- @Test
- void testEmbeding() throws Exception {
- // This used to break, until bug #43116 was fixed
- try (HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls")) {
- // Check we can get at the Escher layer still
- assertDoesNotThrow(workbook::getAllPictures);
- }
- }
-
- @Test
- void testEmbeddedObjects() throws Exception {
- try (HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls")) {
- List objects = workbook.getAllEmbeddedObjects();
- assertEquals(2, objects.size(), "Wrong number of objects");
- assertEquals("MBD06CAB431", objects.get(0).getDirectory().getName(), "Wrong name for first object");
- assertEquals("MBD06CAC85A", objects.get(1).getDirectory().getName(), "Wrong name for second object");
- }
- }
-
- @Test
- void testReallyEmbedSomething() throws Exception {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png");
- byte[] picturePPT = POIDataSamples.getSlideShowInstance().readFile("clock.jpg");
- int imgIdx = wb1.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG);
- POIFSFileSystem pptPoifs = getSamplePPT();
- int pptIdx = wb1.addOlePackage(pptPoifs, "Sample-PPT", "sample.ppt", "sample.ppt");
- POIFSFileSystem xlsPoifs = getSampleXLS();
- int imgPPT = wb1.addPicture(picturePPT, HSSFWorkbook.PICTURE_TYPE_JPEG);
- int xlsIdx = wb1.addOlePackage(xlsPoifs, "Sample-XLS", "sample.xls", "sample.xls");
- int txtIdx = wb1.addOlePackage(getSampleTXT(), "Sample-TXT", "sample.txt", "sample.txt");
-
- int rowoffset = 5;
- int coloffset = 5;
-
- CreationHelper ch = wb1.getCreationHelper();
- HSSFClientAnchor anchor = (HSSFClientAnchor)ch.createClientAnchor();
- anchor.setAnchor((short)(2+coloffset), 1+rowoffset, 0, 0, (short)(3+coloffset), 5+rowoffset, 0, 0);
- anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
-
- patriarch.createObjectData(anchor, pptIdx, imgPPT);
-
- anchor = (HSSFClientAnchor)ch.createClientAnchor();
- anchor.setAnchor((short)(5+coloffset), 1+rowoffset, 0, 0, (short)(6+coloffset), 5+rowoffset, 0, 0);
- anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
-
- patriarch.createObjectData(anchor, xlsIdx, imgIdx);
-
- anchor = (HSSFClientAnchor)ch.createClientAnchor();
- anchor.setAnchor((short)(3+coloffset), 10+rowoffset, 0, 0, (short)(5+coloffset), 11+rowoffset, 0, 0);
- anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
-
- patriarch.createObjectData(anchor, txtIdx, imgIdx);
-
- anchor = (HSSFClientAnchor)ch.createClientAnchor();
- anchor.setAnchor((short)(1+coloffset), -2+rowoffset, 0, 0, (short)(7+coloffset), 14+rowoffset, 0, 0);
- anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
-
- HSSFSimpleShape circle = patriarch.createSimpleShape(anchor);
- circle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL);
- circle.setNoFill(true);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- HSSFObjectData od = wb2.getAllEmbeddedObjects().get(0);
- Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory());
- bos.reset();
- pptPoifs.writeFilesystem(bos);
- assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray());
-
- od = wb2.getAllEmbeddedObjects().get(1);
- ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory());
- bos.reset();
- xlsPoifs.writeFilesystem(bos);
- assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray());
-
- od = wb2.getAllEmbeddedObjects().get(2);
- ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory());
- assertArrayEquals(ole10.getDataBuffer(), getSampleTXT());
-
- xlsPoifs.close();
- pptPoifs.close();
- wb2.close();
- }
-
- static POIFSFileSystem getSamplePPT() throws IOException {
- // scratchpad classes are not available, so we use something pre-cooked
- InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream("with_textbox.ppt");
- POIFSFileSystem poifs = new POIFSFileSystem(is);
- is.close();
-
- return poifs;
- }
-
- static POIFSFileSystem getSampleXLS() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet();
- sheet.createRow(5).createCell(2).setCellValue("yo dawg i herd you like embeddet objekts, so we put a ole in your ole so you can save a file while you save a file");
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- wb.write(bos);
- wb.close();
-
- return new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
- }
-
- static byte[] getSampleTXT() {
- return "All your base are belong to us".getBytes(LocaleUtil.CHARSET_1252);
- }
-}
\ No newline at end of file
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java
deleted file mode 100644
index 6d62955f0c..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.poi.hpsf.*;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.util.HexDump;
-import org.junit.jupiter.api.Test;
-
-/**
- * Old-style setting of POIFS properties doesn't work with POI 3.0.2
- */
-class TestPOIFSProperties {
- private static final String title = "Testing POIFS properties";
-
- @Test
- void testFail() throws Exception {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- { // read the workbook, adjust the SummaryInformation and write the data to a byte array
- POIFSFileSystem fs = openFileSystem();
-
- HSSFWorkbook wb = new HSSFWorkbook(fs);
-
- //set POIFS properties after constructing HSSFWorkbook
- //(a piece of code that used to work up to POI 3.0.2)
- setTitle(fs);
-
- //save the workbook and read the property
- wb.write(out);
- out.close();
- wb.close();
- }
-
- // process the byte array
- checkFromByteArray(out.toByteArray());
- }
-
- @Test
- void testOK() throws Exception {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- { // read the workbook, adjust the SummaryInformation and write the data to a byte array
- POIFSFileSystem fs = openFileSystem();
-
- //set POIFS properties before constructing HSSFWorkbook
- setTitle(fs);
-
- HSSFWorkbook wb = new HSSFWorkbook(fs);
-
- wb.write(out);
- out.close();
- wb.close();
- }
-
- // process the byte array
- checkFromByteArray(out.toByteArray());
- }
-
- private POIFSFileSystem openFileSystem() throws IOException {
- InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls");
- POIFSFileSystem fs = new POIFSFileSystem(is);
- is.close();
- return fs;
- }
-
- private void setTitle(POIFSFileSystem fs) throws NoPropertySetStreamException, MarkUnsupportedException, IOException, WritingNotSupportedException {
- SummaryInformation summary1 = (SummaryInformation) PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
- assertNotNull(summary1);
-
- summary1.setTitle(title);
- //write the modified property back to POIFS
- fs.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME).delete();
- fs.createDocument(summary1.toInputStream(), SummaryInformation.DEFAULT_STREAM_NAME);
-
- // check that the information was added successfully to the filesystem object
- SummaryInformation summaryCheck = (SummaryInformation) PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
- assertNotNull(summaryCheck);
- }
-
- private void checkFromByteArray(byte[] bytes) throws IOException, NoPropertySetStreamException, MarkUnsupportedException {
- // on some environments in CI we see strange failures, let's verify that the size is exactly right
- // this can be removed again after the problem is identified
- assertEquals(5120, bytes.length, "Had: " + HexDump.toHex(bytes));
-
- POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes));
- SummaryInformation summary2 = (SummaryInformation) PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
- assertNotNull(summary2);
-
- assertEquals(title, summary2.getTitle());
- fs2.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java
deleted file mode 100644
index 341be15819..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.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.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertSame;
-
-import org.apache.poi.ddf.EscherDgRecord;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.EscherAggregate;
-import org.junit.jupiter.api.Test;
-
-class TestPatriarch {
- @Test
- void testGetPatriarch(){
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
- assertNull(sh.getDrawingPatriarch());
-
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
- assertNotNull(patriarch);
- patriarch.createSimpleShape(new HSSFClientAnchor());
- patriarch.createSimpleShape(new HSSFClientAnchor());
-
- assertSame(patriarch, sh.getDrawingPatriarch());
-
- EscherAggregate agg = patriarch.getBoundAggregate();
-
- EscherDgRecord dg = agg.getEscherContainer().getChildById(EscherDgRecord.RECORD_ID);
- assertNotNull(dg);
- int lastId = dg.getLastMSOSPID();
-
- assertSame(patriarch, sh.createDrawingPatriarch());
-
- wb = HSSFTestDataSamples.writeOutAndReadBack(wb);
- sh = wb.getSheetAt(0);
- patriarch = sh.createDrawingPatriarch();
- dg = patriarch.getBoundAggregate().getEscherContainer().getChildById(EscherDgRecord.RECORD_ID);
-
- assertNotNull(dg);
- assertEquals(lastId, dg.getLastMSOSPID());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java
deleted file mode 100644
index 759e790a6f..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java
+++ /dev/null
@@ -1,283 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.apache.poi.poifs.storage.RawDataUtil.decompress;
-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 java.io.IOException;
-
-import org.apache.poi.ddf.EscherArrayProperty;
-import org.apache.poi.ddf.EscherPropertyTypes;
-import org.apache.poi.ddf.EscherSpRecord;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.ObjRecord;
-import org.junit.jupiter.api.Test;
-
-class TestPolygon {
- @Test
- void testResultEqualsToAbstractShape() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
-
- HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor());
- polygon.setPolygonDrawArea( 100, 100 );
- polygon.setPoints( new int[]{0, 90, 50}, new int[]{5, 5, 44} );
- polygon.setShapeId(1024);
-
- assertEquals(polygon.getEscherContainer().getChildCount(), 4);
-
- //sp record
- byte[] expected = decompress("H4sIAAAAAAAAAGNi4PrAwQAELEDMxcAAAAU6ZlwQAAAA");
- byte[] actual = polygon.getEscherContainer().getChild(0).serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- expected = decompress("H4sIAAAAAAAAAGNgEPggxIANAABK4+laGgAAAA==");
- actual = polygon.getEscherContainer().getChild(2).serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- expected = decompress("H4sIAAAAAAAAAGNgEPzAAAQACl6c5QgAAAA=");
- actual = polygon.getEscherContainer().getChild(3).serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- ObjRecord obj = polygon.getObjRecord();
-
- expected = decompress("H4sIAAAAAAAAAItlkGIQZRBikGNgYBBMYEADAOAV/ZkeAAAA");
- actual = obj.serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- wb.close();
- }
-
- @Test
- void testPolygonPoints() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
-
- HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor());
- polygon.setPolygonDrawArea( 100, 100 );
- polygon.setPoints( new int[]{0, 90, 50, 90}, new int[]{5, 5, 44, 88} );
-
- EscherArrayProperty verticesProp1 = polygon.getOptRecord().lookup(EscherPropertyTypes.GEOMETRY__VERTICES);
-
- String expected =
- "" +
- "" +
- "BQAFAPD/AAAFAFoABQAyACwAWgBYAAAABQA=" +
- "" +
- "- AAAFAA==
" +
- "- WgAFAA==
" +
- "- MgAsAA==
" +
- "- WgBYAA==
" +
- "- AAAFAA==
" +
- "" +
- "";
- String actual = verticesProp1.toXml("").replaceAll("[\r\n\t]","");
-
- assertEquals(verticesProp1.getNumberOfElementsInArray(), 5);
- assertEquals(expected, actual);
-
- polygon.setPoints(new int[]{1,2,3}, new int[] {4,5,6});
- assertArrayEquals(polygon.getXPoints(), new int[]{1, 2, 3});
- assertArrayEquals(polygon.getYPoints(), new int[]{4, 5, 6});
-
- verticesProp1 = polygon.getOptRecord().lookup(EscherPropertyTypes.GEOMETRY__VERTICES);
-
- expected =
- "" +
- "" +
- "BAAEAPD/AQAEAAIABQADAAYAAQAEAA==" +
- "" +
- "- AQAEAA==
" +
- "- AgAFAA==
" +
- "- AwAGAA==
" +
- "- AQAEAA==
" +
- "";
- actual = verticesProp1.toXml("").replaceAll("[\r\n\t]","");
-
- assertEquals(verticesProp1.getNumberOfElementsInArray(), 4);
- assertEquals(expected, actual);
-
- wb.close();
- }
-
- @Test
- void testSetGetProperties() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sh = wb1.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
-
- HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor());
- polygon.setPolygonDrawArea( 102, 101 );
- polygon.setPoints( new int[]{1,2,3}, new int[]{4,5,6} );
-
- assertArrayEquals(polygon.getXPoints(), new int[]{1,2,3});
- assertArrayEquals(polygon.getYPoints(), new int[]{4, 5, 6});
- assertEquals(polygon.getDrawAreaHeight(), 101);
- assertEquals(polygon.getDrawAreaWidth(), 102);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sh = wb2.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- polygon = (HSSFPolygon) patriarch.getChildren().get(0);
- assertArrayEquals(polygon.getXPoints(), new int[]{1, 2, 3});
- assertArrayEquals(polygon.getYPoints(), new int[]{4, 5, 6});
- assertEquals(polygon.getDrawAreaHeight(), 101);
- assertEquals(polygon.getDrawAreaWidth(), 102);
-
- polygon.setPolygonDrawArea( 1021, 1011 );
- polygon.setPoints( new int[]{11,21,31}, new int[]{41,51,61} );
-
- assertArrayEquals(polygon.getXPoints(), new int[]{11, 21, 31});
- assertArrayEquals(polygon.getYPoints(), new int[]{41, 51, 61});
- assertEquals(polygon.getDrawAreaHeight(), 1011);
- assertEquals(polygon.getDrawAreaWidth(), 1021);
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sh = wb3.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- polygon = (HSSFPolygon) patriarch.getChildren().get(0);
-
- assertArrayEquals(polygon.getXPoints(), new int[]{11, 21, 31});
- assertArrayEquals(polygon.getYPoints(), new int[]{41, 51, 61});
- assertEquals(polygon.getDrawAreaHeight(), 1011);
- assertEquals(polygon.getDrawAreaWidth(), 1021);
-
- wb3.close();
- }
-
- @Test
- void testAddToExistingFile() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sh = wb1.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
-
- HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor());
- polygon.setPolygonDrawArea( 102, 101 );
- polygon.setPoints( new int[]{1,2,3}, new int[]{4,5,6} );
-
- HSSFPolygon polygon1 = patriarch.createPolygon(new HSSFClientAnchor());
- polygon1.setPolygonDrawArea( 103, 104 );
- polygon1.setPoints( new int[]{11,12,13}, new int[]{14,15,16} );
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sh = wb2.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- assertEquals(patriarch.getChildren().size(), 2);
-
- HSSFPolygon polygon2 = patriarch.createPolygon(new HSSFClientAnchor());
- polygon2.setPolygonDrawArea( 203, 204 );
- polygon2.setPoints( new int[]{21,22,23}, new int[]{24,25,26} );
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sh = wb3.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- assertEquals(patriarch.getChildren().size(), 3);
-
- polygon = (HSSFPolygon) patriarch.getChildren().get(0);
- polygon1 = (HSSFPolygon) patriarch.getChildren().get(1);
- polygon2 = (HSSFPolygon) patriarch.getChildren().get(2);
-
- assertArrayEquals(polygon.getXPoints(), new int[]{1, 2, 3});
- assertArrayEquals(polygon.getYPoints(), new int[]{4,5,6});
- assertEquals(polygon.getDrawAreaHeight(), 101);
- assertEquals(polygon.getDrawAreaWidth(), 102);
-
- assertArrayEquals(polygon1.getXPoints(), new int[]{11,12,13});
- assertArrayEquals(polygon1.getYPoints(), new int[]{14,15,16});
- assertEquals(polygon1.getDrawAreaHeight(), 104);
- assertEquals(polygon1.getDrawAreaWidth(), 103);
-
- assertArrayEquals(polygon2.getXPoints(), new int[]{21,22,23});
- assertArrayEquals(polygon2.getYPoints(), new int[]{24,25,26});
- assertEquals(polygon2.getDrawAreaHeight(), 204);
- assertEquals(polygon2.getDrawAreaWidth(), 203);
-
- wb3.close();
- }
-
- @Test
- void testExistingFile() throws IOException {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls");
- HSSFSheet sheet = wb.getSheet("polygon");
- HSSFPatriarch drawing = sheet.getDrawingPatriarch();
- assertEquals(1, drawing.getChildren().size());
-
- HSSFPolygon polygon = (HSSFPolygon) drawing.getChildren().get(0);
- assertEquals(polygon.getDrawAreaHeight(), 2466975);
- assertEquals(polygon.getDrawAreaWidth(), 3686175);
- assertArrayEquals(polygon.getXPoints(), new int[]{0, 0, 31479, 16159, 19676, 20502});
- assertArrayEquals(polygon.getYPoints(), new int[]{0, 0, 36, 56, 34, 18});
-
- wb.close();
- }
-
- @Test
- void testPolygonType() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sh = wb1.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
-
- HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor());
- polygon.setPolygonDrawArea( 102, 101 );
- polygon.setPoints( new int[]{1,2,3}, new int[]{4,5,6} );
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sh = wb2.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- HSSFPolygon polygon1 = patriarch.createPolygon(new HSSFClientAnchor());
- polygon1.setPolygonDrawArea( 102, 101 );
- polygon1.setPoints( new int[]{1,2,3}, new int[]{4,5,6} );
-
- EscherSpRecord spRecord = polygon1.getEscherContainer().getChildById(EscherSpRecord.RECORD_ID);
-
- spRecord.setShapeType((short)77/*RANDOM*/);
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sh = wb3.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- assertEquals(patriarch.getChildren().size(), 2);
- assertTrue(patriarch.getChildren().get(0) instanceof HSSFPolygon);
- assertTrue(patriarch.getChildren().get(1) instanceof HSSFPolygon);
- wb3.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java b/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java
deleted file mode 100644
index f1e9f0ef1f..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.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.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.InternalSheet;
-import org.apache.poi.hssf.record.BOFRecord;
-import org.apache.poi.hssf.record.EOFRecord;
-import org.apache.poi.hssf.record.RecordBase;
-import org.apache.poi.ss.usermodel.DateUtil;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- * @author Glen Stampoultzis (glens at apache.org)
- */
-final class TestReadWriteChart {
-
- /**
- * In the presence of a chart we need to make sure BOF/EOF records still exist.
- */
- @Test
- void testBOFandEOFRecords() throws Exception {
- HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleChart.xls");
- HSSFSheet sheet = workbook.getSheetAt(0);
- HSSFRow firstRow = sheet.getRow(0);
- HSSFCell firstCell = firstRow.getCell(0);
-
- //System.out.println("first assertion for date");
- Calendar calExp = LocaleUtil.getLocaleCalendar(2000, 0, 1, 10, 51, 2);
- Date dateAct = DateUtil.getJavaDate(firstCell.getNumericCellValue(), false);
- assertEquals(calExp.getTime(), dateAct);
- HSSFRow row = sheet.createRow(15);
- HSSFCell cell = row.createCell(1);
-
- cell.setCellValue(22);
- InternalSheet newSheet = workbook.getSheetAt(0).getSheet();
- List records = newSheet.getRecords();
-
- assertTrue(records.get(0) instanceof BOFRecord);
- assertTrue(records.get(records.size() - 1) instanceof EOFRecord);
-
- workbook.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.java b/src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.java
deleted file mode 100644
index 5bde759a5c..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.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.hssf.usermodel;
-
-import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack;
-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.BorderStyle;
-import org.apache.poi.ss.usermodel.FillPatternType;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test row styling functionality
- */
-final class TestRowStyle {
-
- /**
- * TEST NAME: Test Write Sheet Font
- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with fonts.
- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects
- * Last row, first row is tested against the correct values (99,0).
- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good.
- * HSSFSheet last row or first row is incorrect.
- */
- @Test
- void testWriteSheetFont() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- HSSFFont fnt = wb.createFont();
- HSSFCellStyle cs = wb.createCellStyle();
-
- fnt.setColor(HSSFFont.COLOR_RED);
- fnt.setBold(true);
- cs.setFont(fnt);
- for (int rownum = 0; rownum < 100; rownum++) {
- HSSFRow r = s.createRow(rownum);
- r.setRowStyle(cs);
- r.createCell(0);
- }
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) {
- SanityChecker sanityChecker = new SanityChecker();
- sanityChecker.checkHSSFWorkbook(wb2);
- assertEquals(99, s.getLastRowNum(), "LAST ROW == 99");
- assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0");
- }
- }
- }
-
- /**
- * Tests that is creating a file with a date or an calendar works correctly.
- */
- @Test
- void testDataStyle() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- HSSFCellStyle cs = wb.createCellStyle();
- HSSFRow row = s.createRow(0);
-
- // with Date:
- cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
- row.setRowStyle(cs);
- row.createCell(0);
-
-
- // with Calendar:
- row = s.createRow(1);
- cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
- row.setRowStyle(cs);
- row.createCell(0);
-
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) {
- SanityChecker sanityChecker = new SanityChecker();
- sanityChecker.checkHSSFWorkbook(wb2);
-
- assertEquals(1, s.getLastRowNum(), "LAST ROW");
- assertEquals(0, s.getFirstRowNum(), "FIRST ROW");
- }
- }
- }
-
- /**
- * TEST NAME: Test Write Sheet Style
- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with colors
- * and borders.
- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects
- * Last row, first row is tested against the correct values (99,0).
- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good.
- * HSSFSheet last row or first row is incorrect.
- */
- @Test
- void testWriteSheetStyle() throws IOException {
- try (HSSFWorkbook wb = new HSSFWorkbook()) {
- HSSFSheet s = wb.createSheet();
- HSSFFont fnt = wb.createFont();
- HSSFCellStyle cs = wb.createCellStyle();
- HSSFCellStyle cs2 = wb.createCellStyle();
-
- cs.setBorderBottom(BorderStyle.THIN);
- cs.setBorderLeft(BorderStyle.THIN);
- cs.setBorderRight(BorderStyle.THIN);
- cs.setBorderTop(BorderStyle.THIN);
- cs.setFillForegroundColor((short) 0xA);
- cs.setFillPattern(FillPatternType.BRICKS);
- fnt.setColor((short) 0xf);
- fnt.setItalic(true);
- cs2.setFillForegroundColor((short) 0x0);
- cs2.setFillPattern(FillPatternType.BRICKS);
- cs2.setFont(fnt);
- for (int rownum = 0; rownum < 100; rownum++) {
- HSSFRow r = s.createRow(rownum);
- r.setRowStyle(cs);
- r.createCell(0);
-
- rownum++;
- if (rownum >= 100) break; // I feel too lazy to check if this isreqd :-/
-
- r = s.createRow(rownum);
- r.setRowStyle(cs2);
- r.createCell(0);
- }
- try (HSSFWorkbook wb2 = writeOutAndReadBack(wb)) {
- SanityChecker sanityChecker = new SanityChecker();
- sanityChecker.checkHSSFWorkbook(wb2);
- assertEquals(99, s.getLastRowNum(), "LAST ROW == 99");
- assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0");
-
- s = wb2.getSheetAt(0);
- assertNotNull(s, "Sheet is not null");
-
- for (int rownum = 0; rownum < 100; rownum++) {
- HSSFRow r = s.getRow(rownum);
- assertNotNull(r, "Row is not null");
-
- cs = r.getRowStyle();
- assertNotNull(cs);
- assertEquals(BorderStyle.THIN, cs.getBorderBottom(), "Bottom Border Style for row:");
- assertEquals(BorderStyle.THIN, cs.getBorderLeft(), "Left Border Style for row:");
- assertEquals(BorderStyle.THIN, cs.getBorderRight(), "Right Border Style for row:");
- assertEquals(BorderStyle.THIN, cs.getBorderTop(), "Top Border Style for row:");
- assertEquals(0xA, cs.getFillForegroundColor(), "FillForegroundColor for row:");
- assertEquals(FillPatternType.BRICKS, cs.getFillPattern(), "FillPattern for row:");
-
- rownum++;
- if (rownum >= 100) break; // I feel too lazy to check if this isreqd :-/
-
- r = s.getRow(rownum);
- assertNotNull(r, "Row is not null");
- cs2 = r.getRowStyle();
- assertNotNull(cs2);
- assertEquals(cs2.getFillForegroundColor(), (short) 0x0, "FillForegroundColor for row:");
- assertEquals(cs2.getFillPattern(), FillPatternType.BRICKS, "FillPattern for row:");
- }
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java b/src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java
deleted file mode 100644
index 428fb3030e..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.poi.hssf.record.BOFRecord;
-import org.apache.poi.hssf.record.BoundSheetRecord;
-import org.apache.poi.hssf.record.EOFRecord;
-import org.apache.poi.hssf.record.InterfaceHdrRecord;
-import org.apache.poi.hssf.record.NameRecord;
-import org.apache.poi.hssf.record.Record;
-import org.apache.poi.hssf.usermodel.SanityChecker.CheckRecord;
-import org.junit.jupiter.api.Test;
-
-/**
- * A Test case for a test utility class.
- * Okay, this may seem strange but I need to test my test logic.
- *
- * @author Glen Stampoultzis (glens at apache.org)
- */
-final class TestSanityChecker {
- private static final Record INTERFACEHDR = new InterfaceHdrRecord(InterfaceHdrRecord.CODEPAGE);
- private static BoundSheetRecord createBoundSheetRec() {
- return new BoundSheetRecord("Sheet1");
- }
-
- @Test
- void testCheckRecordOrder() {
- final SanityChecker c = new SanityChecker();
- List records = new ArrayList<>();
- records.add(new BOFRecord());
- records.add(INTERFACEHDR);
- records.add(createBoundSheetRec());
- records.add(EOFRecord.instance);
- CheckRecord[] check = {
- new CheckRecord(BOFRecord.class, '1'),
- new CheckRecord(InterfaceHdrRecord.class, '0'),
- new CheckRecord(BoundSheetRecord.class, 'M'),
- new CheckRecord(NameRecord.class, '*'),
- new CheckRecord(EOFRecord.class, '1'),
- };
- // check pass
- c.checkRecordOrder(records, check);
- records.add(2, createBoundSheetRec());
- c.checkRecordOrder(records, check);
- records.remove(1); // optional record missing
- c.checkRecordOrder(records, check);
- records.add(3, new NameRecord());
- records.add(3, new NameRecord()); // optional multiple record occurs more than one time
- c.checkRecordOrder(records, check);
-
- // check fail
- confirmBadRecordOrder(check, new Record[] {
- new BOFRecord(),
- createBoundSheetRec(),
- INTERFACEHDR,
- EOFRecord.instance,
- });
-
- confirmBadRecordOrder(check, new Record[] {
- new BOFRecord(),
- INTERFACEHDR,
- createBoundSheetRec(),
- INTERFACEHDR,
- EOFRecord.instance,
- });
-
- confirmBadRecordOrder(check, new Record[] {
- new BOFRecord(),
- createBoundSheetRec(),
- new NameRecord(),
- EOFRecord.instance,
- new NameRecord(),
- });
-
- confirmBadRecordOrder(check, new Record[] {
- INTERFACEHDR,
- createBoundSheetRec(),
- EOFRecord.instance,
- });
-
- confirmBadRecordOrder(check, new Record[] {
- new BOFRecord(),
- INTERFACEHDR,
- EOFRecord.instance,
- });
-
- confirmBadRecordOrder(check, new Record[] {
- INTERFACEHDR,
- createBoundSheetRec(),
- new BOFRecord(),
- EOFRecord.instance,
- });
-
- confirmBadRecordOrder(check, new Record[] {
- new BOFRecord(),
- createBoundSheetRec(),
- INTERFACEHDR,
- EOFRecord.instance,
- });
- }
-
- private static void confirmBadRecordOrder(final SanityChecker.CheckRecord[] check, Record[] recs) {
- final SanityChecker c = new SanityChecker();
- final List records = Arrays.asList(recs);
- assertThrows(AssertionError.class, () -> c.checkRecordOrder(records, check));
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java b/src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java
deleted file mode 100644
index b02fa4fc7a..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.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 org.apache.poi.POITestCase;
-import org.apache.poi.ddf.EscherContainerRecord;
-import org.apache.poi.ddf.EscherSpgrRecord;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.EscherAggregate;
-import org.junit.jupiter.api.Test;
-
-class TestShapeGroup {
-
- @Test
- void testSetGetCoordinates() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sh = wb1.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
- HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor());
- assertEquals(group.getX1(), 0);
- assertEquals(group.getY1(), 0);
- assertEquals(group.getX2(), 1023);
- assertEquals(group.getY2(), 255);
-
- group.setCoordinates(1,2,3,4);
-
- assertEquals(group.getX1(), 1);
- assertEquals(group.getY1(), 2);
- assertEquals(group.getX2(), 3);
- assertEquals(group.getY2(), 4);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sh = wb2.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- group = (HSSFShapeGroup) patriarch.getChildren().get(0);
- assertEquals(group.getX1(), 1);
- assertEquals(group.getY1(), 2);
- assertEquals(group.getX2(), 3);
- assertEquals(group.getY2(), 4);
- wb2.close();
- }
-
- @Test
- void testAddToExistingFile() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sh = wb1.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
- HSSFShapeGroup group1 = patriarch.createGroup(new HSSFClientAnchor());
- HSSFShapeGroup group2 = patriarch.createGroup(new HSSFClientAnchor());
-
- group1.setCoordinates(1,2,3,4);
- group2.setCoordinates(5,6,7,8);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sh = wb2.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- assertEquals(patriarch.getChildren().size(), 2);
-
- HSSFShapeGroup group3 = patriarch.createGroup(new HSSFClientAnchor());
- group3.setCoordinates(9,10,11,12);
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sh = wb3.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- assertEquals(patriarch.getChildren().size(), 3);
- wb3.close();
- }
-
- @Test
- void testModify() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
-
- // create a sheet with a text box
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- HSSFShapeGroup group1 = patriarch.createGroup(new
- HSSFClientAnchor(0,0,0,0,
- (short)0, 0, (short)15, 25));
- group1.setCoordinates(0, 0, 792, 612);
-
- HSSFTextbox textbox1 = group1.createTextbox(new
- HSSFChildAnchor(100, 100, 300, 300));
- HSSFRichTextString rt1 = new HSSFRichTextString("Hello, World!");
- textbox1.setString(rt1);
-
- // write, read back and check that our text box is there
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
- assertEquals(1, patriarch.getChildren().size());
-
- group1 = (HSSFShapeGroup)patriarch.getChildren().get(0);
- assertEquals(1, group1.getChildren().size());
- textbox1 = (HSSFTextbox)group1.getChildren().get(0);
- assertEquals("Hello, World!", textbox1.getString().getString());
-
- // modify anchor
- assertEquals(new HSSFChildAnchor(100, 100, 300, 300),
- textbox1.getAnchor());
- HSSFChildAnchor newAnchor = new HSSFChildAnchor(200,200, 400, 400);
- textbox1.setAnchor(newAnchor);
- // modify text
- textbox1.setString(new HSSFRichTextString("Hello, World! (modified)"));
-
- // add a new text box
- HSSFTextbox textbox2 = group1.createTextbox(new
- HSSFChildAnchor(400, 400, 600, 600));
- HSSFRichTextString rt2 = new HSSFRichTextString("Hello, World-2");
- textbox2.setString(rt2);
- assertEquals(2, group1.getChildren().size());
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sheet = wb3.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
- assertEquals(1, patriarch.getChildren().size());
-
- group1 = (HSSFShapeGroup)patriarch.getChildren().get(0);
- assertEquals(2, group1.getChildren().size());
- textbox1 = (HSSFTextbox)group1.getChildren().get(0);
- assertEquals("Hello, World! (modified)",
- textbox1.getString().getString());
- assertEquals(new HSSFChildAnchor(200,200, 400, 400),
- textbox1.getAnchor());
-
- textbox2 = (HSSFTextbox)group1.getChildren().get(1);
- assertEquals("Hello, World-2", textbox2.getString().getString());
- assertEquals(new HSSFChildAnchor(400, 400, 600, 600),
- textbox2.getAnchor());
-
- HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3);
- wb3.close();
- sheet = wb4.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
- group1 = (HSSFShapeGroup)patriarch.getChildren().get(0);
- textbox1 = (HSSFTextbox)group1.getChildren().get(0);
- textbox2 = (HSSFTextbox)group1.getChildren().get(1);
- HSSFTextbox textbox3 = group1.createTextbox(new
- HSSFChildAnchor(400,200, 600, 400));
- HSSFRichTextString rt3 = new HSSFRichTextString("Hello, World-3");
- textbox3.setString(rt3);
- wb4.close();
- }
-
- @Test
- void testAddShapesToGroup() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
-
- // create a sheet with a text box
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor());
- int index = wb1.addPicture(new byte[]{1,2,3}, HSSFWorkbook.PICTURE_TYPE_JPEG);
- group.createPicture(new HSSFChildAnchor(), index);
- HSSFPolygon polygon = group.createPolygon(new HSSFChildAnchor());
- polygon.setPoints(new int[]{1,100, 1}, new int[]{1, 50, 100});
- group.createTextbox(new HSSFChildAnchor());
- group.createShape(new HSSFChildAnchor());
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
- assertEquals(1, patriarch.getChildren().size());
-
- assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup);
- group = (HSSFShapeGroup) patriarch.getChildren().get(0);
-
- assertEquals(group.getChildren().size(), 4);
-
- assertTrue(group.getChildren().get(0) instanceof HSSFPicture);
- assertTrue(group.getChildren().get(1) instanceof HSSFPolygon);
- assertTrue(group.getChildren().get(2) instanceof HSSFTextbox);
- assertTrue(group.getChildren().get(3) instanceof HSSFSimpleShape);
-
- HSSFShapeGroup group2 = patriarch.createGroup(new HSSFClientAnchor());
-
- index = wb2.addPicture(new byte[]{2,2,2}, HSSFWorkbook.PICTURE_TYPE_JPEG);
- group2.createPicture(new HSSFChildAnchor(), index);
- polygon = group2.createPolygon(new HSSFChildAnchor());
- polygon.setPoints(new int[]{1,100, 1}, new int[]{1, 50, 100});
- group2.createTextbox(new HSSFChildAnchor());
- group2.createShape(new HSSFChildAnchor());
- group2.createShape(new HSSFChildAnchor());
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sheet = wb3.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
- assertEquals(2, patriarch.getChildren().size());
-
- group = (HSSFShapeGroup) patriarch.getChildren().get(1);
-
- assertEquals(group.getChildren().size(), 5);
-
- assertTrue(group.getChildren().get(0) instanceof HSSFPicture);
- assertTrue(group.getChildren().get(1) instanceof HSSFPolygon);
- assertTrue(group.getChildren().get(2) instanceof HSSFTextbox);
- assertTrue(group.getChildren().get(3) instanceof HSSFSimpleShape);
- assertTrue(group.getChildren().get(4) instanceof HSSFSimpleShape);
-
- group.getShapeId();
- wb3.close();
- }
-
- @Test
- void testSpgrRecord() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
-
- // create a sheet with a text box
- HSSFSheet sheet = wb.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor());
- assertSame(((EscherContainerRecord)group.getEscherContainer().getChild(0)).getChildById(EscherSpgrRecord.RECORD_ID), getSpgrRecord(group));
- wb.close();
- }
-
- private static EscherSpgrRecord getSpgrRecord(HSSFShapeGroup group) {
- return POITestCase.getFieldValue(HSSFShapeGroup.class, group, EscherSpgrRecord.class, "_spgrRecord");
- }
-
- @Test
- void testClearShapes() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
- HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor());
-
- group.createShape(new HSSFChildAnchor());
- group.createShape(new HSSFChildAnchor());
-
- EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch);
-
- assertEquals(agg.getShapeToObjMapping().size(), 5);
- assertEquals(agg.getTailRecords().size(), 0);
- assertEquals(group.getChildren().size(), 2);
-
- group.clear();
-
- assertEquals(agg.getShapeToObjMapping().size(), 1);
- assertEquals(agg.getTailRecords().size(), 0);
- assertEquals(group.getChildren().size(), 0);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
-
- group = (HSSFShapeGroup) patriarch.getChildren().get(0);
-
- assertEquals(agg.getShapeToObjMapping().size(), 1);
- assertEquals(agg.getTailRecords().size(), 0);
- assertEquals(group.getChildren().size(), 0);
- wb2.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java b/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java
deleted file mode 100644
index 2bda96ce2c..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.usermodel;
-
-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 org.apache.poi.hssf.HSSFITestDataProvider;
-import org.apache.poi.hssf.model.InternalWorkbook;
-import org.apache.poi.ss.usermodel.BaseTestSheetHiding;
-import org.apache.poi.ss.usermodel.SheetVisibility;
-import org.junit.jupiter.api.Test;
-
-final class TestSheetHiding extends BaseTestSheetHiding {
- public TestSheetHiding() {
- super(HSSFITestDataProvider.instance,
- "TwoSheetsOneHidden.xls", "TwoSheetsNoneHidden.xls");
- }
-
- @Test
- void testInternalWorkbookHidden() {
- HSSFWorkbook wb = new HSSFWorkbook();
- wb.createSheet("MySheet");
- InternalWorkbook intWb = wb.getWorkbook();
-
- assertFalse(intWb.isSheetHidden(0));
- assertFalse(intWb.isSheetVeryHidden(0));
- assertEquals(SheetVisibility.VISIBLE, intWb.getSheetVisibility(0));
-
- intWb.setSheetHidden(0, SheetVisibility.HIDDEN);
- assertTrue(intWb.isSheetHidden(0));
- assertFalse(intWb.isSheetVeryHidden(0));
- assertEquals(SheetVisibility.HIDDEN, intWb.getSheetVisibility(0));
-
- // InternalWorkbook currently behaves slightly different
- // than HSSFWorkbook, but it should not have effect in normal usage
- // as checked limits are more strict in HSSFWorkbook
-
- // check sheet-index with one more will work and add the sheet
- intWb.setSheetHidden(1, SheetVisibility.HIDDEN);
- assertTrue(intWb.isSheetHidden(1));
- assertFalse(intWb.isSheetVeryHidden(1));
- assertEquals(SheetVisibility.HIDDEN, intWb.getSheetVisibility(1));
-
- // check sheet-index with index out of bounds => throws exception
- assertThrows(RuntimeException.class, () -> wb.setSheetVisibility(10, SheetVisibility.HIDDEN));
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestText.java b/src/testcases/org/apache/poi/hssf/usermodel/TestText.java
deleted file mode 100644
index a7065cda2e..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestText.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.hssf.usermodel;
-
-import static org.apache.poi.poifs.storage.RawDataUtil.decompress;
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.IOException;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.ObjRecord;
-import org.apache.poi.hssf.record.TextObjectRecord;
-import org.junit.jupiter.api.Test;
-
-/**
- * @author Evgeniy Berlog
- * @date 25.06.12
- */
-class TestText {
-
- @Test
- void testResultEqualsToNonExistingAbstractShape() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sh = wb.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
- HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor());
-
- assertEquals(textbox.getEscherContainer().getChildCount(), 5);
-
- //sp record
- byte[] expected = decompress("H4sIAAAAAAAAAFvEw/WBg4GBgZEFSHAxMAAA9gX7nhAAAAA=");
- byte[] actual = textbox.getEscherContainer().getChild(0).serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- expected = decompress("H4sIAAAAAAAAAGNgEPggxIANAABK4+laGgAAAA==");
- actual = textbox.getEscherContainer().getChild(2).serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- expected = decompress("H4sIAAAAAAAAAGNgEPzAAAQACl6c5QgAAAA=");
- actual = textbox.getEscherContainer().getChild(3).serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- expected = decompress("H4sIAAAAAAAAAGNg4P3AAAQA6pyIkQgAAAA=");
- actual = textbox.getEscherContainer().getChild(4).serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- ObjRecord obj = textbox.getObjRecord();
-
- expected = decompress("H4sIAAAAAAAAAItlkGIQZRBiYGNgZBBMYEADAOdCLuweAAAA");
- actual = obj.serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- TextObjectRecord tor = textbox.getTextObjectRecord();
-
- expected = decompress("H4sIAAAAAAAAANvGKMQgxMSABgBGi8T+FgAAAA==");
- actual = tor.serialize();
-
- assertEquals(expected.length, actual.length);
- assertArrayEquals(expected, actual);
-
- wb.close();
- }
-
- @Test
- void testAddTextToExistingFile() throws Exception {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sh = wb1.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
- HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor());
- textbox.setString(new HSSFRichTextString("just for test"));
- HSSFTextbox textbox2 = patriarch.createTextbox(new HSSFClientAnchor());
- textbox2.setString(new HSSFRichTextString("just for test2"));
-
- assertEquals(patriarch.getChildren().size(), 2);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sh = wb2.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- assertEquals(patriarch.getChildren().size(), 2);
- HSSFTextbox text3 = patriarch.createTextbox(new HSSFClientAnchor());
- text3.setString(new HSSFRichTextString("text3"));
- assertEquals(patriarch.getChildren().size(), 3);
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sh = wb3.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
-
- assertEquals(patriarch.getChildren().size(), 3);
- assertEquals(((HSSFTextbox) patriarch.getChildren().get(0)).getString().getString(), "just for test");
- assertEquals(((HSSFTextbox) patriarch.getChildren().get(1)).getString().getString(), "just for test2");
- assertEquals(((HSSFTextbox) patriarch.getChildren().get(2)).getString().getString(), "text3");
-
- wb3.close();
- }
-
- @Test
- void testSetGetProperties() throws Exception {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sh = wb1.createSheet();
- HSSFPatriarch patriarch = sh.createDrawingPatriarch();
- HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor());
- textbox.setString(new HSSFRichTextString("test"));
- assertEquals(textbox.getString().getString(), "test");
-
- textbox.setHorizontalAlignment((short) 5);
- assertEquals(textbox.getHorizontalAlignment(), 5);
-
- textbox.setVerticalAlignment((short) 6);
- assertEquals(textbox.getVerticalAlignment(), (short) 6);
-
- textbox.setMarginBottom(7);
- assertEquals(textbox.getMarginBottom(), 7);
-
- textbox.setMarginLeft(8);
- assertEquals(textbox.getMarginLeft(), 8);
-
- textbox.setMarginRight(9);
- assertEquals(textbox.getMarginRight(), 9);
-
- textbox.setMarginTop(10);
- assertEquals(textbox.getMarginTop(), 10);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sh = wb2.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
- textbox = (HSSFTextbox) patriarch.getChildren().get(0);
- assertEquals(textbox.getString().getString(), "test");
- assertEquals(textbox.getHorizontalAlignment(), 5);
- assertEquals(textbox.getVerticalAlignment(), (short) 6);
- assertEquals(textbox.getMarginBottom(), 7);
- assertEquals(textbox.getMarginLeft(), 8);
- assertEquals(textbox.getMarginRight(), 9);
- assertEquals(textbox.getMarginTop(), 10);
-
- textbox.setString(new HSSFRichTextString("test1"));
- textbox.setHorizontalAlignment(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED);
- textbox.setVerticalAlignment(HSSFTextbox.VERTICAL_ALIGNMENT_TOP);
- textbox.setMarginBottom(71);
- textbox.setMarginLeft(81);
- textbox.setMarginRight(91);
- textbox.setMarginTop(101);
-
- assertEquals(textbox.getString().getString(), "test1");
- assertEquals(textbox.getHorizontalAlignment(), HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED);
- assertEquals(textbox.getVerticalAlignment(), HSSFTextbox.VERTICAL_ALIGNMENT_TOP);
- assertEquals(textbox.getMarginBottom(), 71);
- assertEquals(textbox.getMarginLeft(), 81);
- assertEquals(textbox.getMarginRight(), 91);
- assertEquals(textbox.getMarginTop(), 101);
-
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sh = wb3.getSheetAt(0);
- patriarch = sh.getDrawingPatriarch();
- textbox = (HSSFTextbox) patriarch.getChildren().get(0);
-
- assertEquals(textbox.getString().getString(), "test1");
- assertEquals(textbox.getHorizontalAlignment(), HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED);
- assertEquals(textbox.getVerticalAlignment(), HSSFTextbox.VERTICAL_ALIGNMENT_TOP);
- assertEquals(textbox.getMarginBottom(), 71);
- assertEquals(textbox.getMarginLeft(), 81);
- assertEquals(textbox.getMarginRight(), 91);
- assertEquals(textbox.getMarginTop(), 101);
-
- wb3.close();
- }
-
- @Test
- void testExistingFileWithText() throws Exception {
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls");
- HSSFSheet sheet = wb.getSheet("text");
- HSSFPatriarch drawing = sheet.getDrawingPatriarch();
- assertEquals(1, drawing.getChildren().size());
- HSSFTextbox textbox = (HSSFTextbox) drawing.getChildren().get(0);
- assertEquals(textbox.getHorizontalAlignment(), HSSFTextbox.HORIZONTAL_ALIGNMENT_LEFT);
- assertEquals(textbox.getVerticalAlignment(), HSSFTextbox.VERTICAL_ALIGNMENT_TOP);
- assertEquals(textbox.getMarginTop(), 0);
- assertEquals(textbox.getMarginBottom(), 3600000);
- assertEquals(textbox.getMarginLeft(), 3600000);
- assertEquals(textbox.getMarginRight(), 0);
- assertEquals(textbox.getString().getString(), "teeeeesssstttt");
- wb.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java
deleted file mode 100644
index 76701fd1dd..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.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.hssf.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.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.util.HSSFColor;
-import org.apache.poi.ss.format.CellFormat;
-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.junit.jupiter.api.Test;
-
-/**
- * @author aviks
- *
- * 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.
- */
-final class TestUnfixedBugs {
- @Test
- void testFormulaRecordAggregate_1() throws Exception {
- // fails at formula "=MEHRFACH.OPERATIONEN(E$3;$B$5;$D4)"
- try (Workbook wb = HSSFTestDataSamples.openSampleWorkbook("44958_1.xls")) {
- for (int i = 0; i < wb.getNumberOfSheets(); i++) {
- Sheet sheet = wb.getSheetAt(i);
- assertNotNull(wb.getSheet(sheet.getSheetName()));
- sheet.groupColumn((short) 4, (short) 5);
- sheet.setColumnGroupCollapsed(4, true);
- sheet.setColumnGroupCollapsed(4, false);
-
- for (Row row : sheet) {
- for (Cell cell : row) {
- try {
- assertNotNull(cell.toString());
- } catch (Exception e) {
- throw new Exception("While handling: " + sheet.getSheetName() + "/" + row.getRowNum() + "/" + cell.getColumnIndex(), e);
- }
- }
- }
- }
- }
- }
-
- @Test
- void testFormulaRecordAggregate() throws Exception {
- // fails at formula "=MEHRFACH.OPERATIONEN(E$3;$B$5;$D4)"
- try (Workbook wb = HSSFTestDataSamples.openSampleWorkbook("44958.xls")) {
- for (int i = 0; i < wb.getNumberOfSheets(); i++) {
- Sheet sheet = wb.getSheetAt(i);
- assertNotNull(wb.getSheet(sheet.getSheetName()));
- sheet.groupColumn((short) 4, (short) 5);
- sheet.setColumnGroupCollapsed(4, true);
- sheet.setColumnGroupCollapsed(4, false);
-
- for (Row row : sheet) {
- for (Cell cell : row) {
- try {
- assertNotNull(cell.toString());
- } catch (Exception e) {
- throw new Exception("While handling: " + sheet.getSheetName() + "/" + row.getRowNum() + "/" + cell.getColumnIndex(), e);
- }
- }
- }
- }
- }
- }
-
- @Test
- void testBug57074() throws IOException {
- Workbook wb = HSSFTestDataSamples.openSampleWorkbook("57074.xls");
- Sheet sheet = wb.getSheet("Sheet1");
- Row row = sheet.getRow(0);
- Cell cell = row.getCell(0);
-
- HSSFColor bgColor = (HSSFColor) cell.getCellStyle().getFillBackgroundColorColor();
- String bgColorStr = bgColor.getTriplet()[0]+", "+bgColor.getTriplet()[1]+", "+bgColor.getTriplet()[2];
- //System.out.println(bgColorStr);
- assertEquals("215, 228, 188", bgColorStr);
-
- HSSFColor fontColor = (HSSFColor) cell.getCellStyle().getFillForegroundColorColor();
- String fontColorStr = fontColor.getTriplet()[0]+", "+fontColor.getTriplet()[1]+", "+fontColor.getTriplet()[2];
- //System.out.println(fontColorStr);
- assertEquals("0, 128, 128", fontColorStr);
- wb.close();
- }
-
- @Test
- void testBug62242() {
- CellFormat cfUK = CellFormat.getInstance("_ * #,##0.00_ ;_ * \\-#,##0.00_ ;_ * \"-\"??_ ;_ @_");
- assertEquals(" - ", cfUK.apply((double) 0).text);
- }
-
- @Test
- void testDataFormattingWithQuestionMarkBug62242() {
- // The question mark in the format should be replaced by blanks, but
- // this is currently not handled when producing the Java formatting and
- // so we end up with a trailing zero here
- CellFormat cfUK = CellFormat.getInstance("??");
- assertEquals(" ", cfUK.apply((double) 0).text);
- }
-
- @Test
- void testDataFormattingWithQuestionMarkAndPoundBug62242() {
- char pound = '\u00A3';
-
- // The question mark in the format should be replaced by blanks, but
- // this is currently not handled when producing the Java formatting and
- // so we end up with a trailing zero here
- CellFormat cfUK = CellFormat.getInstance("_-[$£-809]* \"-\"??_-");
- assertEquals(" "+pound+" - ", cfUK.apply((double) 0).text);
-
- cfUK = CellFormat.getInstance("_-[$£-809]* \"-\"??_-a");
- assertEquals(" "+pound+" - a", cfUK.apply((double) 0).text);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java
deleted file mode 100644
index 1ced954a27..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.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.hssf.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.hssf.HSSFTestDataSamples;
-import org.junit.jupiter.api.Test;
-
-final class TestUnicodeWorkbook {
-
- /**
- * Tests Bug38230
- * That a Umlat is written and then read back.
- * It should have been written as a compressed unicode.
- */
- @Test
- void testUmlatReadWrite() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
-
- //Create a unicode sheet name (euro symbol)
- HSSFSheet s = wb1.createSheet("test");
-
- HSSFRow r = s.createRow(0);
- HSSFCell c = r.createCell(1);
- c.setCellValue(new HSSFRichTextString("\u00e4"));
-
- //Confirm that the sring will be compressed
- assertEquals(c.getRichStringCellValue().getUnicodeString().getOptionFlags(), 0);
-
- try (HSSFWorkbook wb = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
-
- //Test the sheetname
- s = wb.getSheet("test");
- assertNotNull(s);
-
- c = r.getCell(1);
- assertEquals(c.getRichStringCellValue().getString(), "\u00e4");
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java
deleted file mode 100644
index e3ca2f4247..0000000000
--- a/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java
+++ /dev/null
@@ -1,632 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.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.IOException;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.InternalWorkbook;
-import org.apache.poi.hssf.record.BackupRecord;
-import org.apache.poi.hssf.record.LabelSSTRecord;
-import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor;
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.CellType;
-import org.apache.poi.ss.usermodel.Name;
-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.junit.jupiter.api.Test;
-
-/**
- * Class to test Workbook functionality
- */
-final class TestWorkbook {
- private static final String LAST_NAME_KEY = "lastName";
- private static final String FIRST_NAME_KEY = "firstName";
- private static final String SSN_KEY = "ssn";
- private static final String REPLACE_ME = "replaceMe";
- private static final String REPLACED = "replaced";
- private static final String DO_NOT_REPLACE = "doNotReplace";
- private static final String EMPLOYEE_INFORMATION = "Employee Info";
- private static final String LAST_NAME_VALUE = "Bush";
- private static final String FIRST_NAME_VALUE = "George";
- private static final String SSN_VALUE = "555555555";
- private final SanityChecker sanityChecker = new SanityChecker();
-
-
- private static HSSFWorkbook openSample(String sampleFileName) {
- return HSSFTestDataSamples.openSampleWorkbook(sampleFileName);
- }
-
- /**
- * TEST NAME: Test Write Sheet Simple
- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values.
- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects
- * Last row, first row is tested against the correct values (99,0).
- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good.
- * HSSFSheet last row or first row is incorrect.
- */
- @Test
- void testWriteSheetSimple() throws IOException {
- try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
- HSSFSheet s = wb1.createSheet();
-
- populateSheet(s);
-
- try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
- sanityChecker.checkHSSFWorkbook(wb1);
- assertEquals(99, s.getLastRowNum(), "LAST ROW == 99");
- assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0");
-
- sanityChecker.checkHSSFWorkbook(wb2);
- s = wb2.getSheetAt(0);
- assertEquals(99, s.getLastRowNum(), "LAST ROW == 99");
- assertEquals(0, s.getFirstRowNum(), "FIRST ROW == 0");
- }
- }
- }
-
- /**
- * TEST NAME: Test Write/Modify Sheet Simple
- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values,
- * remove some rows, yet still have a valid file/data.
- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects
- * Last row, first row is tested against the correct values (74,25).
- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good.
- * HSSFSheet last row or first row is incorrect.
- */
- @Test
- void testWriteModifySheetSimple() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet s = wb1.createSheet();
-
- populateSheet(s);
-
- for (int rownum = 0; rownum < 25; rownum++) {
- HSSFRow r = s.getRow(rownum);
- s.removeRow(r);
- }
- for (int rownum = 75; rownum < 100; rownum++) {
- HSSFRow r = s.getRow(rownum);
- s.removeRow(r);
- }
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
-
- sanityChecker.checkHSSFWorkbook(wb1);
- assertEquals(74, s.getLastRowNum(), "LAST ROW == 74");
- assertEquals(25, s.getFirstRowNum(), "FIRST ROW == 25");
-
- sanityChecker.checkHSSFWorkbook(wb2);
- s = wb2.getSheetAt(0);
- assertEquals(74, s.getLastRowNum(), "LAST ROW == 74");
- assertEquals(25, s.getFirstRowNum(), "FIRST ROW == 25");
-
- wb2.close();
- wb1.close();
- }
-
- /**
- * TEST NAME: Test Read Simple
- * OBJECTIVE: Test that HSSF can read a simple spreadsheet (Simple.xls).
- * SUCCESS: HSSF reads the sheet. Matches values in their particular positions.
- * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values
- * in the sheet in their known positions.
- */
- @Test
- void testReadSimple() throws IOException {
- HSSFWorkbook wb = openSample("Simple.xls");
- HSSFSheet sheet = wb.getSheetAt(0);
-
- HSSFCell cell = sheet.getRow(0).getCell(0);
- assertEquals(REPLACE_ME, cell .getRichStringCellValue().getString());
- wb.close();
- }
-
- /**
- * TEST NAME: Test Read Simple w/ Data Format
- * OBJECTIVE: Test that HSSF can read a simple spreadsheet (SimpleWithDataFormat.xls).
- * SUCCESS: HSSF reads the sheet. Matches values in their particular positions and format is correct
- * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values
- * in the sheet in their known positions.
- */
- @Test
- void testReadSimpleWithDataFormat() throws IOException {
- HSSFWorkbook wb = openSample("SimpleWithDataFormat.xls");
- HSSFSheet sheet = wb.getSheetAt(0);
- HSSFDataFormat format = wb.createDataFormat();
- HSSFCell cell = sheet.getRow(0).getCell(0);
-
- assertEquals(1.25,cell.getNumericCellValue(), 1e-10);
-
- assertEquals(format.getFormat(cell.getCellStyle().getDataFormat()), "0.0");
-
- wb.close();
- }
-
-/**
- * TEST NAME: Test Read/Write Simple w/ Data Format
- * OBJECTIVE: Test that HSSF can write a sheet with custom data formats and then read it and get the proper formats.
- * SUCCESS: HSSF reads the sheet. Matches values in their particular positions and format is correct
- * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values
- * in the sheet in their known positions.
- */
- @Test
- void testWriteDataFormat() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet s1 = wb1.createSheet();
- HSSFDataFormat format = wb1.createDataFormat();
- HSSFCellStyle cs = wb1.createCellStyle();
-
- short df = format.getFormat("0.0");
- cs.setDataFormat(df);
-
- HSSFCell c1 = s1.createRow(0).createCell(0);
- c1.setCellStyle(cs);
- c1.setCellValue(1.25);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
-
- HSSFSheet s2 = wb2.getSheetAt(0);
- HSSFCell c2 = s2.getRow(0).getCell(0);
- format = wb2.createDataFormat();
-
- assertEquals(1.25, c2.getNumericCellValue(), 1e-10);
-
- assertEquals(format.getFormat(df), "0.0");
-
- assertEquals(format, wb2.createDataFormat());
-
- wb2.close();
- wb1.close();
- }
-
- /**
- * TEST NAME: Test Read Employee Simple
- * OBJECTIVE: Test that HSSF can read a simple spreadsheet (Employee.xls).
- * SUCCESS: HSSF reads the sheet. Matches values in their particular positions.
- * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values
- * in the sheet in their known positions.
- *
- */
- @Test
- void testReadEmployeeSimple() throws IOException {
- HSSFWorkbook wb = openSample("Employee.xls");
- HSSFSheet sheet = wb.getSheetAt(0);
-
- assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getRichStringCellValue().getString());
- assertEquals(LAST_NAME_KEY, sheet.getRow(3).getCell(2).getRichStringCellValue().getString());
- assertEquals(FIRST_NAME_KEY, sheet.getRow(4).getCell(2).getRichStringCellValue().getString());
- assertEquals(SSN_KEY, sheet.getRow(5).getCell(2).getRichStringCellValue().getString());
-
- wb.close();
- }
-
- /**
- * TEST NAME: Test Modify Sheet Simple
- * OBJECTIVE: Test that HSSF can read a simple spreadsheet with a string value and replace
- * it with another string value.
- * SUCCESS: HSSF reads a sheet. HSSF replaces the cell value with another cell value. HSSF
- * writes the sheet out to another file. HSSF reads the result and ensures the value
- * has been properly replaced.
- * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts.
- * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value
- * is incorrect or has not been replaced.
- */
- @Test
- void testModifySimple() throws IOException {
- HSSFWorkbook wb1 = openSample("Simple.xls");
- HSSFSheet sheet = wb1.getSheetAt(0);
- HSSFCell cell = sheet.getRow(0).getCell(0);
-
- cell.setCellValue(new HSSFRichTextString(REPLACED));
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- sheet = wb2.getSheetAt(0);
- cell = sheet.getRow(0).getCell(0);
- assertEquals(REPLACED, cell.getRichStringCellValue().getString());
-
- wb2.close();
- wb1.close();
- }
-
- /**
- * TEST NAME: Test Modify Sheet Simple With Skipped cells
- * OBJECTIVE: Test that HSSF can read a simple spreadsheet with string values and replace
- * them with other string values while not replacing other cells.
- * SUCCESS: HSSF reads a sheet. HSSF replaces the cell value with another cell value. HSSF
- * writes the sheet out to another file. HSSF reads the result and ensures the value
- * has been properly replaced and unreplaced values are still unreplaced.
- * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts.
- * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value
- * is incorrect or has not been replaced or the incorrect cell has its value replaced
- * or is incorrect.
- */
- @Test
- void testModifySimpleWithSkip() throws IOException {
- HSSFWorkbook wb1 = openSample("SimpleWithSkip.xls");
- HSSFSheet sheet = wb1.getSheetAt(0);
- HSSFCell cell = sheet.getRow(0).getCell(1);
-
- cell.setCellValue(new HSSFRichTextString(REPLACED));
- cell = sheet.getRow(1).getCell(0);
- cell.setCellValue(new HSSFRichTextString(REPLACED));
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
-
- sheet = wb2.getSheetAt(0);
- cell = sheet.getRow(0).getCell(1);
- assertEquals(REPLACED, cell.getRichStringCellValue().getString());
- cell = sheet.getRow(0).getCell(0);
- assertEquals(DO_NOT_REPLACE, cell.getRichStringCellValue().getString());
- cell = sheet.getRow(1).getCell(0);
- assertEquals(REPLACED, cell.getRichStringCellValue().getString());
- cell = sheet.getRow(1).getCell(1);
- assertEquals(DO_NOT_REPLACE, cell.getRichStringCellValue().getString());
-
- wb2.close();
- wb1.close();
- }
-
- /**
- * TEST NAME: Test Modify Sheet With Styling
- * OBJECTIVE: Test that HSSF can read a simple spreadsheet with string values and replace
- * them with other string values despite any styling. In this release of HSSF styling will
- * probably be lost and is NOT tested.
- * SUCCESS: HSSF reads a sheet. HSSF replaces the cell values with other cell values. HSSF
- * writes the sheet out to another file. HSSF reads the result and ensures the value
- * has been properly replaced.
- * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts.
- * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value
- * is incorrect or has not been replaced.
- */
- @Test
- void testModifySimpleWithStyling() throws IOException {
- HSSFWorkbook wb1 = openSample("SimpleWithStyling.xls");
- HSSFSheet sheet = wb1.getSheetAt(0);
-
- for (int k = 0; k < 4; k++) {
- HSSFCell cell = sheet.getRow(k).getCell(0);
- cell.setCellValue(new HSSFRichTextString(REPLACED));
- }
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- sheet = wb2.getSheetAt(0);
- for (int k = 0; k < 4; k++) {
- HSSFCell cell = sheet.getRow(k).getCell(0);
- assertEquals(REPLACED, cell.getRichStringCellValue().getString());
- }
-
- wb2.close();
- wb1.close();
- }
-
- /**
- * TEST NAME: Test Modify Employee Sheet
- * OBJECTIVE: Test that HSSF can read a simple spreadsheet with string values and replace
- * them with other string values despite any styling. In this release of HSSF styling will
- * probably be lost and is NOT tested.
- * SUCCESS: HSSF reads a sheet. HSSF replaces the cell values with other cell values. HSSF
- * writes the sheet out to another file. HSSF reads the result and ensures the value
- * has been properly replaced.
- * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts.
- * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value
- * is incorrect or has not been replaced.
- */
- @Test
- void testModifyEmployee() throws IOException {
- HSSFWorkbook wb1 = openSample("Employee.xls");
- HSSFSheet sheet = wb1.getSheetAt(0);
- HSSFCell cell = sheet.getRow(3).getCell(2);
-
- cell.setCellValue(new HSSFRichTextString(LAST_NAME_VALUE));
- cell = sheet.getRow(4).getCell(2);
- cell.setCellValue(new HSSFRichTextString(FIRST_NAME_VALUE));
- cell = sheet.getRow(5).getCell(2);
- cell.setCellValue(new HSSFRichTextString(SSN_VALUE));
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- sheet = wb2.getSheetAt(0);
- assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getRichStringCellValue().getString());
- assertEquals(LAST_NAME_VALUE, sheet.getRow(3).getCell(2).getRichStringCellValue().getString());
- assertEquals(FIRST_NAME_VALUE, sheet.getRow(4).getCell(2).getRichStringCellValue().getString());
- assertEquals(SSN_VALUE, sheet.getRow(5).getCell(2).getRichStringCellValue().getString());
-
- wb2.close();
- wb1.close();
- }
-
- /**
- * TEST NAME: Test Read Sheet with an RK number
- * OBJECTIVE: Test that HSSF can read a simple spreadsheet with and RKRecord and correctly
- * identify the cell as numeric and convert it to a NumberRecord.
- * SUCCESS: HSSF reads a sheet. HSSF returns that the cell is a numeric type cell.
- * FAILURE: HSSF does not read a sheet or excepts. HSSF incorrectly identifies the cell
- */
- @Test
- void testReadSheetWithRK() throws IOException {
- HSSFWorkbook wb = openSample("rk.xls");
- HSSFSheet s = wb.getSheetAt(0);
- HSSFCell c = s.getRow(0).getCell(0);
-
- assertEquals(CellType.NUMERIC, c.getCellType());
-
- wb.close();
- }
-
- /**
- * TEST NAME: Test Write/Modify Sheet Simple
- * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values,
- * remove some rows, yet still have a valid file/data.
- * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects
- * Last row, first row is tested against the correct values (74,25).
- * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good.
- * HSSFSheet last row or first row is incorrect.
- */
- @Test
- void testWriteModifySheetMerged() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet s = wb1.createSheet();
-
- populateSheet(s);
-
- assertEquals(0, s.addMergedRegion(new CellRangeAddress(0, 10, 0, 10)));
- assertEquals(1, s.addMergedRegion(new CellRangeAddress(30, 40, 5, 15)));
- sanityChecker.checkHSSFWorkbook(wb1);
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
-
- s = wb2.getSheetAt(0);
- CellRangeAddress r1 = s.getMergedRegion(0);
- CellRangeAddress r2 = s.getMergedRegion(1);
-
- confirmRegion(new CellRangeAddress(0, 10, 0, 10), r1);
- confirmRegion(new CellRangeAddress(30, 40,5, 15), r2);
-
- wb2.close();
- wb1.close();
- }
-
- private void populateSheet(Sheet s) {
- for (int rownum = 0; rownum < 100; rownum++) {
- Row r = s.createRow(rownum);
-
- for (int cellnum = 0; cellnum < 50; cellnum += 2) {
- Cell c = r.createCell(cellnum);
- c.setCellValue(rownum * 10000 + cellnum
- + ((( double ) rownum / 1000)
- + (( double ) cellnum / 10000)));
- c = r.createCell(cellnum + 1);
- c.setCellValue(new HSSFRichTextString("TEST"));
- }
- }
- }
-
- private static void confirmRegion(CellRangeAddress ra, CellRangeAddress rb) {
- assertEquals(ra.getFirstRow(), rb.getFirstRow());
- assertEquals(ra.getLastRow(), rb.getLastRow());
- assertEquals(ra.getFirstColumn(), rb.getFirstColumn());
- assertEquals(ra.getLastColumn(), rb.getLastColumn());
- }
-
- /**
- * Test the backup field gets set as expected.
- */
- @Test
- void testBackupRecord() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- wb.createSheet();
- InternalWorkbook workbook = wb.getWorkbook();
- BackupRecord record = workbook.getBackupRecord();
-
- assertEquals(0, record.getBackup());
- assertFalse(wb.getBackupFlag());
- wb.setBackupFlag(true);
- assertEquals(1, record.getBackup());
- assertTrue(wb.getBackupFlag());
- wb.setBackupFlag(false);
- assertEquals(0, record.getBackup());
- assertFalse(wb.getBackupFlag());
-
- wb.close();
- }
-
- private static final class RecordCounter implements RecordVisitor {
- private int _count;
-
- public RecordCounter() {
- _count=0;
- }
- public int getCount() {
- return _count;
- }
- @Override
- public void visitRecord(org.apache.poi.hssf.record.Record r) {
- if (r instanceof LabelSSTRecord) {
- _count++;
- }
- }
- }
-
- /**
- * This tests is for bug [ #506658 ] Repeating output.
- *
- * We need to make sure only one LabelSSTRecord is produced.
- */
- @Test
- void testRepeatingBug() throws IOException {
- HSSFWorkbook workbook = new HSSFWorkbook();
- HSSFSheet sheet = workbook.createSheet("Design Variants");
- HSSFRow row = sheet.createRow(2);
- HSSFCell cell = row.createCell(1);
-
- cell.setCellValue(new HSSFRichTextString("Class"));
- cell = row.createCell(2);
- assertNotNull(cell);
-
- RecordCounter rc = new RecordCounter();
- sheet.getSheet().visitContainedRecords(rc, 0);
- assertEquals(1, rc.getCount());
-
- workbook.close();
- }
-
-
- /**
- * Test for row indexes beyond {@link Short#MAX_VALUE}.
- * This bug was first fixed in svn r352609.
- */
- @Test
- void testRowIndexesBeyond32768() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet();
- HSSFRow row;
- HSSFCell cell;
- for (int i = 32700; i < 32771; i++) {
- row = sheet.createRow(i);
- cell = row.createCell(0);
- cell.setCellValue(i);
- }
- sanityChecker.checkHSSFWorkbook(wb1);
- assertEquals(32770, sheet.getLastRowNum(), "LAST ROW == 32770");
- cell = sheet.getRow(32770).getCell(0);
- double lastVal = cell.getNumericCellValue();
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- HSSFSheet s = wb2.getSheetAt(0);
- row = s.getRow(32770);
- cell = row.getCell(0);
- assertEquals(lastVal, cell.getNumericCellValue(), 0, "Value from last row == 32770");
- assertEquals(32770, s.getLastRowNum(), "LAST ROW == 32770");
-
- wb2.close();
- wb1.close();
- }
-
- /**
- * Generate a file to verify repeating rows and cols made it
- */
- @Test
- void testRepeatingColsRows() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet("Test Print Titles");
-
- HSSFRow row = sheet.createRow(0);
-
- HSSFCell cell = row.createCell(1);
- cell.setCellValue(new HSSFRichTextString("hi"));
-
- CellRangeAddress cra = CellRangeAddress.valueOf("A1:B1");
- sheet.setRepeatingColumns(cra);
- sheet.setRepeatingRows(cra);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- sheet = wb2.getSheetAt(0);
- assertEquals("A:B", sheet.getRepeatingColumns().formatAsString());
- assertEquals("1:1", sheet.getRepeatingRows().formatAsString());
-
- wb2.close();
- wb1.close();
- }
-
- /**
- * Test setRepeatingRowsAndColumns when startRow and startColumn are -1.
- */
- @Test
- void testRepeatingColsRowsMinusOne() throws IOException
- {
- HSSFWorkbook workbook = new HSSFWorkbook();
- HSSFSheet sheet = workbook.createSheet("Test Print Titles");
-
- HSSFRow row = sheet.createRow(0);
-
- HSSFCell cell = row.createCell(1);
- cell.setCellValue(new HSSFRichTextString("hi"));
- CellRangeAddress cra = new CellRangeAddress(-1, 1, -1, 1);
- assertThrows(IllegalArgumentException.class, () -> sheet.setRepeatingColumns(cra), "invalid start index is ignored");
- assertThrows(IllegalArgumentException.class, () -> sheet.setRepeatingRows(cra), "invalid start index is ignored");
-
- sheet.setRepeatingColumns(null);
- sheet.setRepeatingRows(null);
-
- HSSFTestDataSamples.writeOutAndReadBack(workbook).close();
-
- workbook.close();
- }
-
- @Test
- void testBug58085RemoveSheetWithNames() throws Exception {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- Sheet sheet1 = wb1.createSheet("sheet1");
- Sheet sheet2 = wb1.createSheet("sheet2");
- Sheet sheet3 = wb1.createSheet("sheet3");
-
- sheet1.createRow(0).createCell((short) 0).setCellValue("val1");
- sheet2.createRow(0).createCell((short) 0).setCellValue("val2");
- sheet3.createRow(0).createCell((short) 0).setCellValue("val3");
-
- Name namedCell1 = wb1.createName();
- namedCell1.setNameName("name1");
- String reference1 = "sheet1!$A$1";
- namedCell1.setRefersToFormula(reference1);
-
- Name namedCell2= wb1.createName();
- namedCell2.setNameName("name2");
- String reference2 = "sheet2!$A$1";
- namedCell2.setRefersToFormula(reference2);
-
- Name namedCell3 = wb1.createName();
- namedCell3.setNameName("name3");
- String reference3 = "sheet3!$A$1";
- namedCell3.setRefersToFormula(reference3);
-
- Workbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
-
- Name nameCell = wb2.getName("name1");
- assertNotNull(nameCell);
- assertEquals("sheet1!$A$1", nameCell.getRefersToFormula());
- nameCell = wb2.getName("name2");
- assertNotNull(nameCell);
- assertEquals("sheet2!$A$1", nameCell.getRefersToFormula());
- nameCell = wb2.getName("name3");
- assertNotNull(nameCell);
- assertEquals("sheet3!$A$1", nameCell.getRefersToFormula());
-
- wb2.removeSheetAt(wb2.getSheetIndex("sheet1"));
-
- nameCell = wb2.getName("name1");
- assertNotNull(nameCell);
- assertEquals("#REF!$A$1", nameCell.getRefersToFormula());
- nameCell = wb2.getName("name2");
- assertNotNull(nameCell);
- assertEquals("sheet2!$A$1", nameCell.getRefersToFormula());
- nameCell = wb2.getName("name3");
- assertNotNull(nameCell);
- assertEquals("sheet3!$A$1", nameCell.getRefersToFormula());
-
- wb2.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java b/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java
deleted file mode 100644
index 1fe92ec022..0000000000
--- a/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java
+++ /dev/null
@@ -1,309 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hssf.util;
-
-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.InputStream;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.model.HSSFFormulaParser;
-import org.apache.poi.hssf.model.InternalWorkbook;
-import org.apache.poi.hssf.record.NameRecord;
-import org.apache.poi.hssf.usermodel.HSSFCell;
-import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
-import org.apache.poi.hssf.usermodel.HSSFName;
-import org.apache.poi.hssf.usermodel.HSSFRow;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.hssf.usermodel.TestHSSFWorkbook;
-import org.apache.poi.ss.SpreadsheetVersion;
-import org.apache.poi.ss.formula.ptg.Area3DPtg;
-import org.apache.poi.ss.formula.ptg.MemFuncPtg;
-import org.apache.poi.ss.formula.ptg.Ptg;
-import org.apache.poi.ss.formula.ptg.UnionPtg;
-import org.apache.poi.ss.util.AreaReference;
-import org.apache.poi.ss.util.CellReference;
-import org.junit.jupiter.api.Test;
-
-final class TestAreaReference {
-
- @Test
- void testAreaRef1() {
- AreaReference ar = new AreaReference("$A$1:$B$2", SpreadsheetVersion.EXCEL97);
- assertFalse(ar.isSingleCell(), "Two cells expected");
- CellReference cf = ar.getFirstCell();
- assertEquals(0, cf.getRow(), "row is 4");
- assertEquals(0, cf.getCol(), "col is 1");
- assertTrue(cf.isRowAbsolute(), "row is abs");
- assertTrue(cf.isColAbsolute(), "col is abs");
- assertEquals("$A$1", cf.formatAsString(), "string is $A$1");
-
- cf = ar.getLastCell();
- assertEquals(1, cf.getRow(), "row is 4");
- assertEquals(1, cf.getCol(), "col is 1");
- assertTrue(cf.isRowAbsolute(), "row is abs");
- assertTrue(cf.isColAbsolute(), "col is abs");
- assertEquals("$B$2", cf.formatAsString(), "string is $B$2");
-
- CellReference[] refs = ar.getAllReferencedCells();
- assertEquals(4, refs.length);
-
- assertEquals(0, refs[0].getRow());
- assertEquals(0, refs[0].getCol());
- assertNull(refs[0].getSheetName());
-
- assertEquals(0, refs[1].getRow());
- assertEquals(1, refs[1].getCol());
- assertNull(refs[1].getSheetName());
-
- assertEquals(1, refs[2].getRow());
- assertEquals(0, refs[2].getCol());
- assertNull(refs[2].getSheetName());
-
- assertEquals(1, refs[3].getRow());
- assertEquals(1, refs[3].getCol());
- assertNull(refs[3].getSheetName());
- }
-
- /**
- * References failed when sheet names were being used Reported by
- * Arne.Clauss@gedas.de
- */
- @Test
- void testReferenceWithSheet() {
- AreaReference ar;
-
- ar = new AreaReference("Tabelle1!B5:B5", SpreadsheetVersion.EXCEL97);
- assertTrue(ar.isSingleCell());
- TestCellReference.confirmCell(ar.getFirstCell(), "Tabelle1", 4, 1, false, false, "Tabelle1!B5");
-
- assertEquals(1, ar.getAllReferencedCells().length);
-
- ar = new AreaReference("Tabelle1!$B$5:$B$7", SpreadsheetVersion.EXCEL97);
- assertFalse(ar.isSingleCell());
-
- TestCellReference.confirmCell(ar.getFirstCell(), "Tabelle1", 4, 1, true, true, "Tabelle1!$B$5");
- TestCellReference.confirmCell(ar.getLastCell(), "Tabelle1", 6, 1, true, true, "Tabelle1!$B$7");
-
- // And all that make it up
- CellReference[] allCells = ar.getAllReferencedCells();
- assertEquals(3, allCells.length);
- TestCellReference.confirmCell(allCells[0], "Tabelle1", 4, 1, true, true, "Tabelle1!$B$5");
- TestCellReference.confirmCell(allCells[1], "Tabelle1", 5, 1, true, true, "Tabelle1!$B$6");
- TestCellReference.confirmCell(allCells[2], "Tabelle1", 6, 1, true, true, "Tabelle1!$B$7");
- }
-
- @Test
- void testContiguousReferences() {
- String refSimple = "$C$10:$C$10";
- String ref2D = "$C$10:$D$11";
- String refDCSimple = "$C$10:$C$10,$D$12:$D$12,$E$14:$E$14";
- String refDC2D = "$C$10:$C$11,$D$12:$D$12,$E$14:$E$20";
- String refDC3D = "Tabelle1!$C$10:$C$14,Tabelle1!$D$10:$D$12";
- String refComma = "'A,Sheet'!$A$1:$A$1,'A,Sheet'!$A$4:$A$5";
- String refCommaExp = "'!Sheet,Comma!'!$A$1:$B$1";
-
- // Check that we detect as contiguous properly
- assertTrue(AreaReference.isContiguous(refSimple));
- assertTrue(AreaReference.isContiguous(ref2D));
- assertFalse(AreaReference.isContiguous(refDCSimple));
- assertFalse(AreaReference.isContiguous(refDC2D));
- assertFalse(AreaReference.isContiguous(refDC3D));
- assertFalse(AreaReference.isContiguous(refComma));
- assertTrue(AreaReference.isContiguous(refCommaExp));
-
- // Check we can only create contiguous entries
- new AreaReference(refSimple, SpreadsheetVersion.EXCEL97);
- new AreaReference(ref2D, SpreadsheetVersion.EXCEL97);
- assertThrows(IllegalArgumentException.class, () -> new AreaReference(refDCSimple, SpreadsheetVersion.EXCEL97));
- assertThrows(IllegalArgumentException.class, () -> new AreaReference(refDC2D, SpreadsheetVersion.EXCEL97));
- assertThrows(IllegalArgumentException.class, () -> new AreaReference(refDC3D, SpreadsheetVersion.EXCEL97));
-
- // Test that we split as expected
- AreaReference[] refs;
-
- refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refSimple);
- assertEquals(1, refs.length);
- assertTrue(refs[0].isSingleCell());
- assertEquals("$C$10", refs[0].formatAsString());
-
- refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, ref2D);
- assertEquals(1, refs.length);
- assertFalse(refs[0].isSingleCell());
- assertEquals("$C$10:$D$11", refs[0].formatAsString());
-
- refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refDCSimple);
- assertEquals(3, refs.length);
- assertTrue(refs[0].isSingleCell());
- assertTrue(refs[1].isSingleCell());
- assertTrue(refs[2].isSingleCell());
- assertEquals("$C$10", refs[0].formatAsString());
- assertEquals("$D$12", refs[1].formatAsString());
- assertEquals("$E$14", refs[2].formatAsString());
-
- refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refDC2D);
- assertEquals(3, refs.length);
- assertFalse(refs[0].isSingleCell());
- assertTrue(refs[1].isSingleCell());
- assertFalse(refs[2].isSingleCell());
- assertEquals("$C$10:$C$11", refs[0].formatAsString());
- assertEquals("$D$12", refs[1].formatAsString());
- assertEquals("$E$14:$E$20", refs[2].formatAsString());
-
- refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refDC3D);
- assertEquals(2, refs.length);
- assertFalse(refs[0].isSingleCell());
- assertFalse(refs[0].isSingleCell());
- assertEquals("Tabelle1!$C$10:$C$14", refs[0].formatAsString());
- assertEquals("Tabelle1!$D$10:$D$12", refs[1].formatAsString());
- assertEquals("Tabelle1", refs[0].getFirstCell().getSheetName());
- assertEquals("Tabelle1", refs[0].getLastCell().getSheetName());
- assertEquals("Tabelle1", refs[1].getFirstCell().getSheetName());
- assertEquals("Tabelle1", refs[1].getLastCell().getSheetName());
-
- refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refComma);
- assertEquals(2, refs.length);
- System.out.println(refs[0].formatAsString());
- assertTrue(refs[0].isSingleCell());
- assertEquals("'A,Sheet'!$A$1", refs[0].formatAsString());
- assertEquals("A,Sheet", refs[0].getLastCell().getSheetName());
- assertEquals("'A,Sheet'!$A$4:$A$5", refs[1].formatAsString());
- assertEquals("A,Sheet", refs[1].getLastCell().getSheetName());
-
- refs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, refCommaExp);
- assertEquals(1, refs.length);
- assertFalse(refs[0].isSingleCell());
- assertEquals("'!Sheet,Comma!'!$A$1:$B$1", refs[0].formatAsString());
- assertEquals("!Sheet,Comma!", refs[0].getLastCell().getSheetName());
- }
-
- @Test
- void testDiscontinousReference() throws Exception {
- try (InputStream is = HSSFTestDataSamples.openSampleFileStream("44167.xls");
- HSSFWorkbook wb = new HSSFWorkbook(is)) {
- InternalWorkbook workbook = TestHSSFWorkbook.getInternalWorkbook(wb);
- HSSFEvaluationWorkbook eb = HSSFEvaluationWorkbook.create(wb);
-
- assertEquals(1, wb.getNumberOfNames());
- String sheetName = "Tabelle1";
- String rawRefA = "$C$10:$C$14";
- String rawRefB = "$C$16:$C$18";
- String refA = sheetName + "!" + rawRefA;
- String refB = sheetName + "!" + rawRefB;
- String ref = refA + "," + refB;
-
- // Check the low level record
- NameRecord nr = workbook.getNameRecord(0);
- assertNotNull(nr);
- assertEquals("test", nr.getNameText());
-
- Ptg[] def = nr.getNameDefinition();
- assertEquals(4, def.length);
-
- MemFuncPtg ptgA = (MemFuncPtg) def[0];
- Area3DPtg ptgB = (Area3DPtg) def[1];
- Area3DPtg ptgC = (Area3DPtg) def[2];
- UnionPtg ptgD = (UnionPtg) def[3];
- assertEquals("", ptgA.toFormulaString());
- assertEquals(refA, ptgB.toFormulaString(eb));
- assertEquals(refB, ptgC.toFormulaString(eb));
- assertEquals(",", ptgD.toFormulaString());
-
- assertEquals(ref, HSSFFormulaParser.toFormulaString(wb, nr.getNameDefinition()));
-
- // Check the high level definition
- HSSFName aNamedCell = wb.getName("test");
-
- // Should have 2 references
- assertNotNull(aNamedCell);
- String formulaRefs = aNamedCell.getRefersToFormula();
- assertNotNull(formulaRefs);
- assertEquals(ref, formulaRefs);
-
- // Check the parsing of the reference into cells
- assertFalse(AreaReference.isContiguous(formulaRefs));
- AreaReference[] arefs = AreaReference.generateContiguous(SpreadsheetVersion.EXCEL97, formulaRefs);
- assertEquals(2, arefs.length);
- assertEquals(refA, arefs[0].formatAsString());
- assertEquals(refB, arefs[1].formatAsString());
-
- for (AreaReference ar : arefs) {
- confirmResolveCellRef(wb, ar.getFirstCell());
- confirmResolveCellRef(wb, ar.getLastCell());
- }
- }
- }
-
- private static void confirmResolveCellRef(HSSFWorkbook wb, CellReference cref) {
- HSSFSheet s = wb.getSheet(cref.getSheetName());
- HSSFRow r = s.getRow(cref.getRow());
- HSSFCell c = r.getCell(cref.getCol());
- assertNotNull(c);
- }
-
- @Test
- void testSpecialSheetNames() {
- AreaReference ar;
- ar = new AreaReference("'Sheet A'!A1:A1", SpreadsheetVersion.EXCEL97);
- confirmAreaSheetName(ar, "Sheet A", "'Sheet A'!A1");
-
- ar = new AreaReference("'Hey! Look Here!'!A1:A1", SpreadsheetVersion.EXCEL97);
- confirmAreaSheetName(ar, "Hey! Look Here!", "'Hey! Look Here!'!A1");
-
- ar = new AreaReference("'O''Toole'!A1:B2", SpreadsheetVersion.EXCEL97);
- confirmAreaSheetName(ar, "O'Toole", "'O''Toole'!A1:B2");
-
- ar = new AreaReference("'one:many'!A1:B2", SpreadsheetVersion.EXCEL97);
- confirmAreaSheetName(ar, "one:many", "'one:many'!A1:B2");
-
- ar = new AreaReference("'O,Comma'!A1:B1", SpreadsheetVersion.EXCEL97);
- confirmAreaSheetName(ar, "O,Comma", "'O,Comma'!A1:B1");
- }
-
- private static void confirmAreaSheetName(AreaReference ar, String sheetName, String expectedFullText) {
- CellReference[] cells = ar.getAllReferencedCells();
- assertEquals(sheetName, cells[0].getSheetName());
- assertEquals(expectedFullText, ar.formatAsString());
- }
-
- @Test
- void testWholeColumnRefs() {
- confirmWholeColumnRef("A:A", 0, 0, false, false);
- confirmWholeColumnRef("$C:D", 2, 3, true, false);
- confirmWholeColumnRef("AD:$AE", 29, 30, false, true);
- }
-
- private static void confirmWholeColumnRef(String ref, int firstCol, int lastCol, boolean firstIsAbs, boolean lastIsAbs) {
- AreaReference ar = new AreaReference(ref, SpreadsheetVersion.EXCEL97);
- confirmCell(ar.getFirstCell(), 0, firstCol, true, firstIsAbs);
- confirmCell(ar.getLastCell(), 0xFFFF, lastCol, true, lastIsAbs);
- }
-
- private static void confirmCell(CellReference cell, int row, int col, boolean isRowAbs, boolean isColAbs) {
- assertEquals(row, cell.getRow());
- assertEquals(col, cell.getCol());
- assertEquals(isRowAbs, cell.isRowAbsolute());
- assertEquals(isColAbs, cell.isColAbsolute());
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/util/TestCellReference.java b/src/testcases/org/apache/poi/hssf/util/TestCellReference.java
deleted file mode 100644
index f761e251dd..0000000000
--- a/src/testcases/org/apache/poi/hssf/util/TestCellReference.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.hssf.util;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-import org.apache.poi.ss.SpreadsheetVersion;
-import org.apache.poi.ss.util.CellReference;
-import org.apache.poi.ss.util.CellReference.NameType;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for the HSSF and SS versions of CellReference.
- * See also {@link org.apache.poi.ss.util.TestCellReference}
- */
-final class TestCellReference {
- @Test
- void testColNumConversion() {
- assertEquals(0, CellReference.convertColStringToIndex("A"));
- assertEquals(1, CellReference.convertColStringToIndex("B"));
- assertEquals(25, CellReference.convertColStringToIndex("Z"));
- assertEquals(26, CellReference.convertColStringToIndex("AA"));
- assertEquals(27, CellReference.convertColStringToIndex("AB"));
- assertEquals(51, CellReference.convertColStringToIndex("AZ"));
- assertEquals(701, CellReference.convertColStringToIndex("ZZ"));
- assertEquals(702, CellReference.convertColStringToIndex("AAA"));
- assertEquals(18277, CellReference.convertColStringToIndex("ZZZ"));
-
- assertEquals("A", CellReference.convertNumToColString(0));
- assertEquals("B", CellReference.convertNumToColString(1));
- assertEquals("Z", CellReference.convertNumToColString(25));
- assertEquals("AA", CellReference.convertNumToColString(26));
- assertEquals("ZZ", CellReference.convertNumToColString(701));
- assertEquals("AAA", CellReference.convertNumToColString(702));
- assertEquals("ZZZ", CellReference.convertNumToColString(18277));
-
- // Absolute references are allowed for the string ones
- assertEquals(0, CellReference.convertColStringToIndex("$A"));
- assertEquals(25, CellReference.convertColStringToIndex("$Z"));
- assertEquals(26, CellReference.convertColStringToIndex("$AA"));
-
- // $ sign isn't allowed elsewhere though
- assertThrows(IllegalArgumentException.class, () -> CellReference.convertColStringToIndex("A$B$"),
- "Column reference is invalid and shouldn't be accepted");
- }
-
- @Test
- void testAbsRef1(){
- CellReference cf = new CellReference("$B$5");
- confirmCell(cf, null, 4, 1, true, true, "$B$5");
- }
-
- @Test
- void testAbsRef2(){
- CellReference cf = new CellReference(4,1,true,true);
- confirmCell(cf, null, 4, 1, true, true, "$B$5");
- }
-
- @Test
- void testAbsRef3(){
- CellReference cf = new CellReference("B$5");
- confirmCell(cf, null, 4, 1, true, false, "B$5");
- }
-
- @Test
- void testAbsRef4(){
- CellReference cf = new CellReference(4,1,true,false);
- confirmCell(cf, null, 4, 1, true, false, "B$5");
- }
-
- @Test
- void testAbsRef5(){
- CellReference cf = new CellReference("$B5");
- confirmCell(cf, null, 4, 1, false, true, "$B5");
- }
-
- @Test
- void testAbsRef6(){
- CellReference cf = new CellReference(4,1,false,true);
- confirmCell(cf, null, 4, 1, false, true, "$B5");
- }
-
- @Test
- void testAbsRef7(){
- CellReference cf = new CellReference("B5");
- confirmCell(cf, null, 4, 1, false, false, "B5");
- }
-
- @Test
- void testAbsRef8(){
- CellReference cf = new CellReference(4,1,false,false);
- confirmCell(cf, null, 4, 1, false, false, "B5");
- }
-
- @Test
- void testSpecialSheetNames() {
- CellReference cf;
- cf = new CellReference("'profit + loss'!A1");
- confirmCell(cf, "profit + loss", 0, 0, false, false, "'profit + loss'!A1");
-
- cf = new CellReference("'O''Brien''s Sales'!A1");
- confirmCell(cf, "O'Brien's Sales", 0, 0, false, false, "'O''Brien''s Sales'!A1");
-
- cf = new CellReference("'Amazing!'!A1");
- confirmCell(cf, "Amazing!", 0, 0, false, false, "'Amazing!'!A1");
- }
-
- /* package */ static void confirmCell(CellReference cf, String expSheetName, int expRow,
- int expCol, boolean expIsRowAbs, boolean expIsColAbs, String expText) {
-
- assertEquals(expSheetName, cf.getSheetName());
- assertEquals(expRow, cf.getRow(), "row index is wrong");
- assertEquals(expCol, cf.getCol(), "col index is wrong");
- assertEquals(expIsRowAbs, cf.isRowAbsolute(), "isRowAbsolute is wrong");
- assertEquals(expIsColAbs, cf.isColAbsolute(), "isColAbsolute is wrong");
- assertEquals(expText, cf.formatAsString(), "text is wrong");
- }
-
- @Test
- void testClassifyCellReference() {
- confirmNameType("a1", NameType.CELL);
- confirmNameType("pfy1", NameType.NAMED_RANGE);
- confirmNameType("pf1", NameType.NAMED_RANGE); // (col) out of cell range
- confirmNameType("fp1", NameType.CELL);
- confirmNameType("pf$1", NameType.BAD_CELL_OR_NAMED_RANGE);
- confirmNameType("_A1", NameType.NAMED_RANGE);
- confirmNameType("A_1", NameType.NAMED_RANGE);
- confirmNameType("A1_", NameType.NAMED_RANGE);
- confirmNameType(".A1", NameType.BAD_CELL_OR_NAMED_RANGE);
- confirmNameType("A.1", NameType.NAMED_RANGE);
- confirmNameType("A1.", NameType.NAMED_RANGE);
- }
-
- @Test
- void testClassificationOfRowReferences(){
- confirmNameType("10", NameType.ROW);
- confirmNameType("$10", NameType.ROW);
- confirmNameType("65536", NameType.ROW);
-
- confirmNameType("65537", NameType.BAD_CELL_OR_NAMED_RANGE);
- confirmNameType("$100000", NameType.BAD_CELL_OR_NAMED_RANGE);
- confirmNameType("$1$1", NameType.BAD_CELL_OR_NAMED_RANGE);
- }
-
- private void confirmNameType(String ref, NameType expectedResult) {
- NameType actualResult = CellReference.classifyCellReference(ref, SpreadsheetVersion.EXCEL97);
- assertEquals(expectedResult, actualResult);
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java b/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java
deleted file mode 100644
index ff3ec06277..0000000000
--- a/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.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.hssf.util;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.Map;
-
-import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
-import org.junit.jupiter.api.Test;
-
-final class TestHSSFColor {
- @Test
- void testBasics() {
- assertTrue(HSSFColorPredefined.YELLOW.getIndex() > 0);
- assertTrue(HSSFColorPredefined.YELLOW.getIndex2() > 0);
- }
-
- @Test
- void testContents() {
- short[] triplet = HSSFColorPredefined.YELLOW.getTriplet();
- assertEquals(3, triplet.length);
- assertEquals(255, triplet[0]);
- assertEquals(255, triplet[1]);
- assertEquals(0, triplet[2]);
-
- assertEquals("FFFF:FFFF:0", HSSFColorPredefined.YELLOW.getHexString());
- }
-
- @Test
- void testTripletHash() {
- Map triplets = HSSFColor.getTripletHash();
-
- assertEquals(
- HSSFColorPredefined.MAROON.getColor(),
- triplets.get(HSSFColorPredefined.MAROON.getHexString())
- );
- assertEquals(
- HSSFColorPredefined.YELLOW.getColor(),
- triplets.get(HSSFColorPredefined.YELLOW.getHexString())
- );
- }
-}
diff --git a/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java b/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java
deleted file mode 100644
index 15190f93ab..0000000000
--- a/src/testcases/org/apache/poi/hssf/util/TestRKUtil.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.hssf.util;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests the {@link RKUtil} class.
- */
-final class TestRKUtil {
-
- /**
- * Check we can decode correctly.
- */
- @Test
- void testDecode() {
-
- int[] values = { 1074266112, 1081384961, 1081397249,
- 0x3FF00000, 0x405EC001, 0x02F1853A, 0x02F1853B, 0xFCDD699A,
- };
- double[] rvalues = { 3.0, 3.3, 3.33,
- 1, 1.23, 12345678, 123456.78, -13149594,
- };
-
- for (int j = 0; j < values.length; j++) {
-
- int intBits = values[j];
- double expectedValue = rvalues[j];
- double actualValue = RKUtil.decodeNumber(intBits);
- assertEquals(expectedValue, actualValue, 0);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java b/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java
deleted file mode 100644
index 959565cfeb..0000000000
--- a/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-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 java.io.InputStream;
-
-import javax.crypto.spec.SecretKeySpec;
-
-import org.apache.poi.hssf.record.crypto.Biff8DecryptingStream;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link Biff8DecryptingStream}
- */
-final class TestBiff8DecryptingStream {
-
- /**
- * A mock {@link InputStream} that keeps track of position and also produces
- * slightly interesting data. Each successive data byte value is one greater
- * than the previous.
- */
- private static final class MockStream extends InputStream {
- private final int _initialValue;
- private int _position;
-
- public MockStream(int initialValue) {
- _initialValue = initialValue;
- }
-
- @Override
- public int read() {
- return (_initialValue+_position++) & 0xFF;
- }
- }
-
- private static final class StreamTester {
- private final Biff8DecryptingStream _bds;
-
- /**
- * @param expectedFirstInt expected value of the first int read from the decrypted stream
- */
- public StreamTester(MockStream ms, String keyDigestHex, int expectedFirstInt) {
- byte[] keyDigest = HexRead.readFromString(keyDigestHex);
- EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4);
- Decryptor dec = ei.getDecryptor();
- dec.setSecretKey(new SecretKeySpec(keyDigest, "RC4"));
-
- _bds = new Biff8DecryptingStream(ms, 0, ei);
- assertEquals(expectedFirstInt, _bds.readInt());
- }
-
- public Biff8DecryptingStream getBDS() {
- return _bds;
- }
-
- /**
- * Used to 'skip over' the uninteresting middle bits of the key blocks.
- * Also confirms that read position of the underlying stream is aligned.
- */
- void rollForward(int fromPosition, int toPosition) {
- assertEquals(fromPosition, _bds.getPosition());
- for (int i = fromPosition; i < toPosition; i++) {
- _bds.readByte();
- }
- assertEquals(toPosition, _bds.getPosition());
- }
-
- void confirmByte(int expVal) {
- assertEquals(expVal, _bds.readUByte());
- }
-
- void confirmShort(int expVal) {
- assertEquals((short)expVal, _bds.readShort());
- }
-
- void confirmUShort(int expVal) {
- assertEquals(expVal, _bds.readUShort());
- }
-
- public short readShort() {
- return _bds.readShort();
- }
-
- public int readUShort() {
- return _bds.readUShort();
- }
-
- void confirmInt(int expVal) {
- assertEquals(expVal, _bds.readInt());
- }
-
- void confirmLong(long expVal) {
- assertEquals(expVal, _bds.readLong());
- }
-
- void confirmData(String expHexData) {
-
- byte[] expData = HexRead.readFromString(expHexData);
- byte[] actData = new byte[expData.length];
- _bds.readFully(actData);
- assertArrayEquals(expData, actData, "Data mismatch");
- }
- }
-
- /**
- * Tests reading of 64,32,16 and 8 bit integers aligned with key changing boundaries
- */
- @Test
- void readsAlignedWithBoundary() {
- StreamTester st = createStreamTester();
-
- st.rollForward(0x0004, 0x03FF);
- st.confirmByte(0x3E);
- st.confirmByte(0x28);
- st.rollForward(0x0401, 0x07FE);
- st.confirmShort(0x76CC);
- st.confirmShort(0xD83E);
- st.rollForward(0x0802, 0x0BFC);
- st.confirmInt(0x25F280EB);
- st.confirmInt(0xB549E99B);
- st.rollForward(0x0C04, 0x0FF8);
- st.confirmLong(0x6AA2D5F6B975D10CL);
- st.confirmLong(0x34248ADF7ED4F029L);
- // check for signed/unsigned shorts #58069
- st.rollForward(0x1008, 0x7213);
- st.confirmUShort(0xFFFF);
- st.rollForward(0x7215, 0x1B9AD);
- st.confirmShort(-1);
- st.rollForward(0x1B9AF, 0x37D99);
- assertEquals(0xFFFF, st.readUShort());
- st.rollForward(0x37D9B, 0x4A6F2);
- assertEquals(-1, st.readShort());
- }
-
- /**
- * Tests reading of 64,32 and 16 bit integers across key changing boundaries
- */
- @Test
- void readsSpanningBoundary() {
- StreamTester st = createStreamTester();
-
- st.rollForward(0x0004, 0x03FC);
- st.confirmLong(0x885243283E2A5EEFL);
- st.rollForward(0x0404, 0x07FE);
- st.confirmInt(0xD83E76CC);
- st.rollForward(0x0802, 0x0BFF);
- st.confirmShort(0x9B25);
- }
-
- /**
- * Checks that the BIFF header fields (sid, size) get read without applying decryption,
- * and that the RC4 stream stays aligned during these calls
- */
- @Test
- void readHeaderUShort() {
- StreamTester st = createStreamTester();
-
- st.rollForward(0x0004, 0x03FF);
-
- Biff8DecryptingStream bds = st.getBDS();
- int hval = bds.readDataSize(); // unencrypted
- int nextInt = bds.readInt();
- assertNotEquals(0x8F534029, nextInt, "Indentified bug in key alignment after call to readHeaderUShort()");
- assertEquals(0x16885243, nextInt);
- assertNotEquals(0x283E, hval, "readHeaderUShort() incorrectly decrypted result");
- assertEquals(0x504F, hval);
-
- // confirm next key change
- st.rollForward(0x0405, 0x07FC);
- st.confirmInt(0x76CC1223);
- st.confirmInt(0x4842D83E);
- }
-
- /**
- * Tests reading of byte sequences across and aligned with key changing boundaries
- */
- @Test
- void readByteArrays() {
- StreamTester st = createStreamTester();
-
- st.rollForward(0x0004, 0x2FFC);
- st.confirmData("66 A1 20 B1 04 A3 35 F5"); // 4 bytes on either side of boundary
- st.rollForward(0x3004, 0x33F8);
- st.confirmData("F8 97 59 36"); // last 4 bytes in block
- st.confirmData("01 C2 4E 55"); // first 4 bytes in next block
- }
-
- private static StreamTester createStreamTester() {
- return new StreamTester(new MockStream(0x50), "BA AD F0 0D 00", 0x96C66829);
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java b/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java
deleted file mode 100644
index 22452a0efd..0000000000
--- a/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-import org.apache.poi.EncryptedDocumentException;
-import org.junit.jupiter.api.Test;
-
-class TestCipherAlgorithm {
- @Test
- void validInputs() {
- assertEquals(128, CipherAlgorithm.aes128.defaultKeySize);
-
- for(CipherAlgorithm alg : CipherAlgorithm.values()) {
- assertEquals(alg, CipherAlgorithm.valueOf(alg.toString()));
- }
-
- assertEquals(CipherAlgorithm.aes128, CipherAlgorithm.fromEcmaId(0x660E));
- assertEquals(CipherAlgorithm.aes192, CipherAlgorithm.fromXmlId("AES", 192));
- }
-
- @Test
- void invalidInputs() {
- assertThrows(EncryptedDocumentException.class, () -> CipherAlgorithm.fromEcmaId(0));
- assertThrows(EncryptedDocumentException.class, () -> CipherAlgorithm.fromXmlId("AES", 1));
- assertThrows(EncryptedDocumentException.class, () -> CipherAlgorithm.fromXmlId("RC1", 0x40));
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java b/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java
deleted file mode 100644
index 2bca550236..0000000000
--- a/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.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.poifs.crypt;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.record.FilePassRecord;
-import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.util.HexRead;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-class TestXorEncryption {
-
- private static final HSSFTestDataSamples samples = new HSSFTestDataSamples();
-
- @Test
- void testXorEncryption() {
- // Xor-Password: abc
- // 2.5.343 XORObfuscation
- // key = 20810
- // verifier = 52250
- int verifier = CryptoFunctions.createXorVerifier1("abc");
- int key = CryptoFunctions.createXorKey1("abc");
- assertEquals(20810, key);
- assertEquals(52250, verifier);
-
- byte[] xorArrAct = CryptoFunctions.createXorArray1("abc");
- byte[] xorArrExp = HexRead.readFromString("AC-CC-A4-AB-D6-BA-C3-BA-D6-A3-2B-45-D3-79-29-BB");
- assertThat(xorArrExp, equalTo(xorArrAct));
- }
-
- @SuppressWarnings("static-access")
- @Test
- void testUserFile() throws IOException {
- File f = samples.getSampleFile("xor-encryption-abc.xls");
- Biff8EncryptionKey.setCurrentUserPassword("abc");
- try (POIFSFileSystem fs = new POIFSFileSystem(f, true);
- HSSFWorkbook hwb = new HSSFWorkbook(fs.getRoot(), true)) {
- HSSFSheet sh = hwb.getSheetAt(0);
- assertEquals(1.0, sh.getRow(0).getCell(0).getNumericCellValue(), 0.0);
- assertEquals(2.0, sh.getRow(1).getCell(0).getNumericCellValue(), 0.0);
- assertEquals(3.0, sh.getRow(2).getCell(0).getNumericCellValue(), 0.0);
- } finally {
- Biff8EncryptionKey.setCurrentUserPassword(null);
- }
- }
-
- @Test
- @Disabled("currently not supported")
- void encrypt() throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- try {
- try (HSSFWorkbook hwb = HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")) {
- Biff8EncryptionKey.setCurrentUserPassword("abc");
- hwb.getInternalWorkbook().getWorkbookRecordList()
- .add(1, new FilePassRecord(EncryptionMode.xor));
- hwb.write(bos);
- }
- try (HSSFWorkbook hwb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) {
- assertEquals(3, hwb.getNumberOfSheets());
- }
- } finally {
- Biff8EncryptionKey.setCurrentUserPassword(null);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java b/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java
deleted file mode 100644
index 42a607c130..0000000000
--- a/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.binaryrc4;
-
-import static org.apache.poi.util.HexRead.readFromString;
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.security.GeneralSecurityException;
-
-import javax.crypto.SecretKey;
-
-import org.apache.poi.poifs.crypt.Decryptor;
-import org.apache.poi.poifs.crypt.EncryptionInfo;
-import org.apache.poi.poifs.crypt.EncryptionMode;
-import org.junit.jupiter.api.Test;
-
-class TestBinaryRC4 {
- @Test
- void createKeyDigest() {
- byte[] docIdData = readFromString("17 F6 D1 6B 09 B1 5F 7B 4C 9D 03 B4 81 B5 B4 4A");
- byte[] expResult = readFromString("C2 D9 56 B2 6B");
-
- EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4);
- BinaryRC4EncryptionVerifier ver = (BinaryRC4EncryptionVerifier)ei.getVerifier();
- ver.setSalt(docIdData);
- SecretKey sk = BinaryRC4Decryptor.generateSecretKey("MoneyForNothing", ver);
-
- assertArrayEquals(expResult, sk.getEncoded(), "keyDigest mismatch");
- }
-
- @Test
- void testValidateWithDefaultPassword() throws GeneralSecurityException {
-
- String docIdSuffixA = "F 35 52 38 0D 75 4A E6 85 C2 FD 78 CE 3D D1 B6"; // valid prefix is 'D'
- String saltHashA = "30 38 BE 5E 93 C5 7E B4 5F 52 CD A1 C6 8F B6 2A";
- String saltDataA = "D4 04 43 EC B7 A7 6F 6A D2 68 C7 DF CF A8 80 68";
-
- String docIdB = "39 D7 80 41 DA E4 74 2C 8C 84 F9 4D 39 9A 19 2D";
- String saltDataSuffixB = "3 EA 8D 52 11 11 37 D2 BD 55 4C 01 0A 47 6E EB"; // valid prefix is 'C'
- String saltHashB = "96 19 F5 D0 F1 63 08 F1 3E 09 40 1E 87 F0 4E 16";
-
- confirmValid(true, "D" + docIdSuffixA, saltDataA, saltHashA);
- confirmValid(true, docIdB, "C" + saltDataSuffixB, saltHashB);
- confirmValid(false, "E" + docIdSuffixA, saltDataA, saltHashA);
- confirmValid(false, docIdB, "B" + saltDataSuffixB, saltHashB);
- }
-
- @Test
- void testValidateWithSuppliedPassword() throws GeneralSecurityException {
-
- String docId = "DF 35 52 38 0D 75 4A E6 85 C2 FD 78 CE 3D D1 B6";
- String saltData = "D4 04 43 EC B7 A7 6F 6A D2 68 C7 DF CF A8 80 68";
- String saltHashA = "8D C2 63 CC E1 1D E0 05 20 16 96 AF 48 59 94 64"; // for password '5ecret'
- String saltHashB = "31 0B 0D A4 69 55 8E 27 A1 03 AD C9 AE F8 09 04"; // for password '5ecret'
-
- confirmValid(true, docId, saltData, saltHashA, "5ecret");
- confirmValid(false, docId, saltData, saltHashA, "Secret");
- confirmValid(true, docId, saltData, saltHashB, "Secret");
- confirmValid(false, docId, saltData, saltHashB, "secret");
- }
-
-
- private static void confirmValid(boolean expectedResult,
- String docIdHex, String saltDataHex, String saltHashHex) throws GeneralSecurityException {
- confirmValid(expectedResult, docIdHex, saltDataHex, saltHashHex, null);
- }
-
- private static void confirmValid(boolean expectedResult, String docIdHex,
- String saltDataHex, String saltHashHex, String password) throws GeneralSecurityException {
- byte[] docId = readFromString(docIdHex);
- byte[] saltData = readFromString(saltDataHex);
- byte[] saltHash = readFromString(saltHashHex);
-
- EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4);
- BinaryRC4EncryptionVerifier ver = (BinaryRC4EncryptionVerifier)ei.getVerifier();
- ver.setSalt(docId);
- ver.setEncryptedVerifier(saltData);
- ver.setEncryptedVerifierHash(saltHash);
-
- String pass = password == null ? Decryptor.DEFAULT_PASSWORD : password;
- boolean actResult = ei.getDecryptor().verifyPassword(pass);
- assertEquals(expectedResult, actResult, expectedResult ? "validate failed" : "validate succeeded unexpectedly");
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java b/src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java
deleted file mode 100644
index 1fa1802bea..0000000000
--- a/src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.dev;
-
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
-import java.security.Permission;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.poifs.filesystem.NotOLE2FileException;
-import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.poifs.property.PropertyTable;
-import org.apache.poi.util.NullPrintStream;
-import org.apache.poi.util.TempFile;
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-
-public class TestPOIFSDump {
-
- private static PrintStream SYSTEM;
- @BeforeAll
- public static void setUp() throws UnsupportedEncodingException {
- SYSTEM = System.out;
- System.setOut(new NullPrintStream());
- }
-
- @AfterAll
- public static void resetSystemOut() {
- System.setOut(SYSTEM);
- }
-
- private static final String TEST_FILE = HSSFTestDataSamples.getSampleFile("46515.xls").getAbsolutePath();
- private static final String INVALID_FILE = HSSFTestDataSamples.getSampleFile("48936-strings.txt").getAbsolutePath();
- private static final String INVALID_XLSX_FILE = HSSFTestDataSamples.getSampleFile("47668.xlsx").getAbsolutePath();
-
- private static final String[] DUMP_OPTIONS = {
- "-dumprops",
- "-dump-props",
- "-dump-properties",
- "-dumpmini",
- "-dump-mini",
- "-dump-ministream",
- "-dump-mini-stream",
- };
-
- @AfterEach
- void tearDown() throws IOException {
- // clean up the directory that POIFSDump writes to
- deleteDirectory(new File(new File(TEST_FILE+"_dump").getName()));
- }
-
- public static void deleteDirectory(File directory) throws IOException {
- if (!directory.exists()) {
- return;
- }
-
- cleanDirectory(directory);
-
- if (!directory.delete()) {
- String message =
- "Unable to delete directory " + directory + ".";
- throw new IOException(message);
- }
- }
-
- private static void cleanDirectory(File directory) throws IOException {
- if (!directory.isDirectory()) {
- String message = directory + " is not a directory";
- throw new IllegalArgumentException(message);
- }
-
- File[] files = directory.listFiles();
- if (files == null) { // null if security restricted
- throw new IOException("Failed to list contents of " + directory);
- }
-
- IOException exception = null;
- for (File file : files) {
- try {
- forceDelete(file);
- } catch (IOException ioe) {
- exception = ioe;
- }
- }
-
- if (null != exception) {
- throw exception;
- }
- }
-
- private static void forceDelete(File file) throws IOException {
- if (file.isDirectory()) {
- deleteDirectory(file);
- } else {
- boolean filePresent = file.exists();
- if (!file.delete()) {
- if (!filePresent){
- throw new FileNotFoundException("File does not exist: " + file);
- }
- String message =
- "Unable to delete file: " + file;
- throw new IOException(message);
- }
- }
- }
-
- @Test
- void testMain() throws Exception {
- POIFSDump.main(new String[]{TEST_FILE});
-
- for(String option : DUMP_OPTIONS) {
- assertDoesNotThrow(() -> POIFSDump.main(new String[]{option, TEST_FILE}));
- }
- }
- @Test
- void testInvalidFile() {
- assertThrows(NotOLE2FileException.class, () -> POIFSDump.main(new String[]{INVALID_FILE}));
- assertThrows(OfficeXmlFileException.class, () -> POIFSDump.main(new String[]{INVALID_XLSX_FILE}));
-
- for(String option : DUMP_OPTIONS) {
- assertThrows(NotOLE2FileException.class, () -> POIFSDump.main(new String[]{option, INVALID_FILE}));
- assertThrows(OfficeXmlFileException.class, () -> POIFSDump.main(new String[]{option, INVALID_XLSX_FILE}));
- }
- }
-
- @Test
- void testMainNoArgs() throws Exception {
- SecurityManager sm = System.getSecurityManager();
- try {
- System.setSecurityManager(new SecurityManager() {
- @Override
- public void checkExit(int status) {
- throw new SecurityException();
- }
-
- @Override
- public void checkPermission(Permission perm) {
- // Allow other activities by default
- }
- });
-
- assertThrows(SecurityException.class, () -> POIFSDump.main(new String[]{}));
- } finally {
- System.setSecurityManager(sm);
- }
- }
-
- @Test
- void testFailToWrite() throws IOException {
- File dir = TempFile.createTempFile("TestPOIFSDump", ".tst");
- assertTrue(dir.exists(), "Had: " + dir);
- assertTrue(dir.delete(), "Had: " + dir);
- assertTrue(dir.mkdirs(), "Had: " + dir);
-
- FileInputStream is = new FileInputStream(TEST_FILE);
- POIFSFileSystem fs = new POIFSFileSystem(is);
- is.close();
-
- PropertyTable props = fs.getPropertyTable();
- assertNotNull(props);
-
- // try with an invalid startBlock to trigger an exception
- // to validate that file-handles are closed properly
- assertThrows(IndexOutOfBoundsException.class, () -> POIFSDump.dump(fs, 999999999, "mini-stream", dir));
- }
-}
\ No newline at end of file
diff --git a/src/testcases/org/apache/poi/poifs/eventfilesystem/Listener.java b/src/testcases/org/apache/poi/poifs/eventfilesystem/Listener.java
deleted file mode 100644
index 4b597c1719..0000000000
--- a/src/testcases/org/apache/poi/poifs/eventfilesystem/Listener.java
+++ /dev/null
@@ -1,45 +0,0 @@
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.eventfilesystem;
-
-/**
- * Class Listener
- *
- * @author Marc Johnson (mjohnson at apache dot org)
- * @version %I%, %G%
- */
-
-class Listener
- implements POIFSReaderListener
-{
-
- /**
- * Process a POIFSReaderEvent that this listener had registered
- * for
- *
- * @param event the POIFSReaderEvent
- */
-
- @Override
- public void processPOIFSReaderEvent(POIFSReaderEvent event)
- {
- }
-} // end class Listener
-
diff --git a/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java b/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java
deleted file mode 100644
index 1eb939f961..0000000000
--- a/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.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.poifs.eventfilesystem;
-
-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.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.apache.poi.poifs.filesystem.POIFSDocumentPath;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test POIFSReaderRegistry functionality
- *
- * @author Marc Johnson
- */
-final class TestPOIFSReaderRegistry {
- private final POIFSReaderListener[] listeners =
- {
- new Listener(), new Listener(), new Listener(), new Listener()
- };
- private final POIFSDocumentPath[] paths =
- {
- new POIFSDocumentPath(), new POIFSDocumentPath(new String[]
- {
- "a"
- }), new POIFSDocumentPath(new String[]
- {
- "b"
- }), new POIFSDocumentPath(new String[]
- {
- "c"
- })
- };
- private final String[] names =
- {
- "a0", "a1", "a2", "a3"
- };
-
- /**
- * Test empty registry
- */
- @Test
- void testEmptyRegistry() {
- POIFSReaderRegistry registry = new POIFSReaderRegistry();
-
- for (POIFSDocumentPath path : paths) {
- for (String name : names) {
- Iterator listeners =
- registry.getListeners(path, name).iterator();
-
- assertFalse(listeners.hasNext());
- }
- }
- }
-
- /**
- * Test mixed registration operations
- */
- @Test
- void testMixedRegistrationOperations() {
- POIFSReaderRegistry registry = new POIFSReaderRegistry();
-
- for (int j = 0; j < listeners.length; j++)
- {
- for (int k = 0; k < paths.length; k++)
- {
- for (int n = 0; n < names.length; n++)
- {
- if ((j != k) && (k != n))
- {
- registry.registerListener(
- listeners[ j ], paths[ k ], names[ n ]);
- }
- }
- }
- }
- for (int k = 0; k < paths.length; k++)
- {
- for (int n = 0; n < names.length; n++)
- {
- Iterable listeners =
- registry.getListeners(paths[ k ], names[ n ]);
-
- if (k == n)
- {
- assertFalse(listeners.iterator().hasNext());
- }
- else
- {
- Set registeredListeners =
- new HashSet<>();
-
- for (POIFSReaderListener rl : listeners) {
- registeredListeners.add(rl);
- }
- assertEquals(this.listeners.length - 1,
- registeredListeners.size());
- for (int j = 0; j < this.listeners.length; j++)
- {
- if (j == k)
- {
- assertFalse(registeredListeners
- .contains(this.listeners[j]));
- }
- else
- {
- assertTrue(registeredListeners
- .contains(this.listeners[ j ]));
- }
- }
- }
- }
- }
- for (POIFSReaderListener listener : listeners) {
- registry.registerListener(listener);
- }
- for (POIFSDocumentPath path : paths) {
- for (String name : names) {
- Iterable listeners =
- registry.getListeners(path, name);
- Set registeredListeners =
- new HashSet<>();
-
- for (POIFSReaderListener rl : listeners) {
- registeredListeners.add(rl);
- }
- assertEquals(this.listeners.length,
- registeredListeners.size());
- for (POIFSReaderListener listener : this.listeners) {
- assertTrue(registeredListeners
- .contains(listener));
- }
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java b/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java
deleted file mode 100644
index ed2ce941ab..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java
+++ /dev/null
@@ -1,170 +0,0 @@
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.poi.poifs.eventfilesystem.POIFSReader;
-import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
-import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
-import org.apache.poi.util.IOUtils;
-
-/**
- * Test (Proof of concept) program that employs the
- * POIFSReaderListener and POIFSWriterListener interfaces
- *
- * @author Marc Johnson (mjohnson at apache dot org)
- */
-
-public final class ReaderWriter
- implements POIFSReaderListener, POIFSWriterListener
-{
- private final DirectoryEntry root;
-
- // keys are DocumentDescriptors, values are byte[]s
- private final Map dataMap = new HashMap<>();
-
- private ReaderWriter(final POIFSFileSystem filesystem) {
- root = filesystem.getRoot();
- }
-
- public static void main(String [] args) throws IOException
- {
- if (args.length != 2)
- {
- System.err.println(
- "two arguments required: one input file name and one output file name");
- }
- else
- {
- POIFSReader reader = new POIFSReader();
- POIFSFileSystem filesystem = new POIFSFileSystem();
-
- reader.registerListener(new ReaderWriter(filesystem));
-
- reader.read(new File(args[ 0 ]));
- FileOutputStream ostream = new FileOutputStream(args[ 1 ]);
-
- filesystem.writeFilesystem(ostream);
- ostream.close();
-
- filesystem.close();
- }
- }
-
- /* ********** START implementation of POIFSReaderListener ********** */
-
- /**
- * Process a POIFSReaderEvent that this listener had registered
- * for
- *
- * @param event the POIFSReaderEvent
- */
-
- @Override
- public void processPOIFSReaderEvent(final POIFSReaderEvent event)
- {
- @SuppressWarnings("resource")
- DocumentInputStream istream = event.getStream();
- POIFSDocumentPath path = event.getPath();
- String name = event.getName();
-
- try {
- byte[] data = IOUtils.toByteArray(istream);
- int size = data.length;
-
- DocumentDescriptor descriptor = new DocumentDescriptor(path,
- name);
-
- System.out.println("adding document: " + descriptor + " (" + size
- + " bytes)");
- dataMap.put(descriptor, data);
- //int pathLength = path.length();
- DirectoryEntry entry = root;
-
- for (int k = 0; k < path.length(); k++)
- {
- String componentName = path.getComponent(k);
- Entry nextEntry = null;
-
- try
- {
- nextEntry = entry.getEntry(componentName);
- }
- catch (FileNotFoundException ignored)
- {
- try
- {
- nextEntry = entry.createDirectory(componentName);
- }
- catch (IOException e)
- {
- System.out.println("Unable to create directory");
- e.printStackTrace();
- System.exit(1);
- }
- }
- entry = ( DirectoryEntry ) nextEntry;
- }
- entry.createDocument(name, size, this);
- }
- catch (IOException ignored)
- {
- }
- }
-
- /* ********** END implementation of POIFSReaderListener ********** */
- /* ********** START implementation of POIFSWriterListener ********** */
-
- /**
- * Process a POIFSWriterEvent that this listener had registered
- * for
- *
- * @param event the POIFSWriterEvent
- */
-
- @Override
- public void processPOIFSWriterEvent(final POIFSWriterEvent event)
- {
- try
- {
- DocumentDescriptor descriptor =
- new DocumentDescriptor(event.getPath(), event.getName());
-
- System.out.println("looking up document: " + descriptor + " ("
- + event.getLimit() + " bytes)");
- event.getStream().write(dataMap.get(descriptor));
- }
- catch (IOException e)
- {
- System.out.println("Unable to write document");
- e.printStackTrace();
- System.exit(1);
- }
- }
-
- /* ********** END implementation of POIFSWriterListener ********** */
-} // end public class ReaderWriter
-
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/SlowInputStream.java b/src/testcases/org/apache/poi/poifs/filesystem/SlowInputStream.java
deleted file mode 100644
index f818d21978..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/SlowInputStream.java
+++ /dev/null
@@ -1,41 +0,0 @@
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-import java.io.*;
-import java.util.Random;
-
-/**
- * Returns a random amount of requested data. Used to check conformance with
- * InputStream API contracts.
- */
-public class SlowInputStream extends FilterInputStream
-{
- private final Random r = new Random(0);
-
- public SlowInputStream(InputStream in) {
- super(in);
- }
-
- @Override
- public int read(byte[] b, int off, int len) throws IOException {
- return super.read(b, off, r.nextInt(len) + 1);
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java
deleted file mode 100644
index 9212aa6c8f..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java
+++ /dev/null
@@ -1,208 +0,0 @@
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-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 java.io.ByteArrayInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.Iterator;
-
-import org.apache.poi.poifs.property.DirectoryProperty;
-import org.apache.poi.poifs.property.DocumentProperty;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test DirectoryNode functionality
- */
-final class TestDirectoryNode {
-
- /**
- * test trivial constructor (a DirectoryNode with no children)
- */
- @Test
- void testEmptyConstructor() throws IOException {
- try (POIFSFileSystem fs = new POIFSFileSystem()) {
- DirectoryProperty property1 = new DirectoryProperty("parent");
- DirectoryProperty property2 = new DirectoryProperty("child");
- DirectoryNode parent = new DirectoryNode(property1, fs, null);
- DirectoryNode node = new DirectoryNode(property2, fs, parent);
-
- assertEquals(0, parent.getPath().length());
- assertEquals(1, node.getPath().length());
- assertEquals("child", node.getPath().getComponent(0));
-
- // verify that getEntries behaves correctly
- int count = 0;
- Iterator iter = node.getEntries();
-
- while (iter.hasNext()) {
- count++;
- iter.next();
- }
- assertEquals(0, count);
-
- // verify behavior of isEmpty
- assertTrue(node.isEmpty());
-
- // verify behavior of getEntryCount
- assertEquals(0, node.getEntryCount());
-
- // verify behavior of getEntry
- assertThrows(FileNotFoundException.class, () -> node.getEntry("foo"));
-
- // verify behavior of isDirectoryEntry
- assertTrue(node.isDirectoryEntry());
-
- // verify behavior of getName
- assertEquals(property2.getName(), node.getName());
-
- // verify behavior of isDocumentEntry
- assertFalse(node.isDocumentEntry());
-
- // verify behavior of getParent
- assertEquals(parent, node.getParent());
- }
- }
-
- /**
- * test non-trivial constructor (a DirectoryNode with children)
- */
- @Test
- void testNonEmptyConstructor() throws IOException {
- DirectoryProperty property1 = new DirectoryProperty("parent");
- DirectoryProperty property2 = new DirectoryProperty("child1");
-
- property1.addChild(property2);
- property1.addChild(new DocumentProperty("child2", 2000));
- property2.addChild(new DocumentProperty("child3", 30000));
-
- try (POIFSFileSystem fs = new POIFSFileSystem()) {
- DirectoryNode node = new DirectoryNode(property1, fs, null);
-
- // verify that getEntries behaves correctly
- int count = 0;
- Iterator iter = node.getEntries();
-
- while (iter.hasNext()) {
- count++;
- iter.next();
- }
- assertEquals(2, count);
-
- // verify behavior of isEmpty
- assertFalse(node.isEmpty());
-
- // verify behavior of getEntryCount
- assertEquals(2, node.getEntryCount());
-
- // verify behavior of getEntry
- DirectoryNode child1 = (DirectoryNode) node.getEntry("child1");
-
- child1.getEntry("child3");
- node.getEntry("child2");
- assertThrows(FileNotFoundException.class, () -> node.getEntry("child3"));
-
- // verify behavior of isDirectoryEntry
- assertTrue(node.isDirectoryEntry());
-
- // verify behavior of getName
- assertEquals(property1.getName(), node.getName());
-
- // verify behavior of isDocumentEntry
- assertFalse(node.isDocumentEntry());
-
- // verify behavior of getParent
- assertNull(node.getParent());
- }
- }
-
- /**
- * test deletion methods
- */
- @Test
- void testDeletion() throws IOException {
- try (POIFSFileSystem fs = new POIFSFileSystem()) {
- DirectoryEntry root = fs.getRoot();
-
- // verify cannot delete the root directory
- assertFalse(root.delete());
- assertTrue(root.isEmpty());
-
- DirectoryEntry dir = fs.createDirectory("myDir");
-
- assertFalse(root.isEmpty());
- assertTrue(dir.isEmpty());
-
- // verify can delete empty directory
- assertFalse(root.delete());
- assertTrue(dir.delete());
-
- // Now look at a non-empty one
- dir = fs.createDirectory("NextDir");
- DocumentEntry doc =
- dir.createDocument("foo",
- new ByteArrayInputStream(new byte[1]));
-
- assertFalse(root.isEmpty());
- assertFalse(dir.isEmpty());
-
- // verify cannot delete non-empty directory
- assertFalse(dir.delete());
-
- // but we can delete it if we remove the document
- assertTrue(doc.delete());
- assertTrue(dir.isEmpty());
- assertTrue(dir.delete());
-
- // It's really gone!
- assertTrue(root.isEmpty());
-
- }
- }
-
- /**
- * test change name methods
- */
- @Test
- void testRename() throws IOException {
- try (POIFSFileSystem fs = new POIFSFileSystem()) {
- DirectoryEntry root = fs.getRoot();
-
- // verify cannot rename the root directory
- assertFalse(root.renameTo("foo"));
- DirectoryEntry dir = fs.createDirectory("myDir");
-
- assertTrue(dir.renameTo("foo"));
- assertEquals("foo", dir.getName());
- DirectoryEntry dir2 = fs.createDirectory("myDir");
-
- assertFalse(dir2.renameTo("foo"));
- assertEquals("myDir", dir2.getName());
- assertTrue(dir.renameTo("FirstDir"));
- assertTrue(dir2.renameTo("foo"));
- assertEquals("foo", dir2.getName());
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java
deleted file mode 100644
index 15edc14e92..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-import static org.apache.poi.poifs.common.POIFSConstants.LARGER_BIG_BLOCK_SIZE;
-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.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.stream.IntStream;
-
-import org.apache.poi.poifs.property.DocumentProperty;
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.apache.poi.util.IOUtils;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test POIFSDocument functionality
- */
-class TestDocument {
-
- /**
- * Integration test -- really about all we can do
- */
- @Test
- void testPOIFSDocument() throws IOException {
-
- try (POIFSFileSystem poifs = new POIFSFileSystem()) {
-
- // verify correct number of blocks get created for document
- // that is exact multiple of block size
- checkDocument(poifs, LARGER_BIG_BLOCK_SIZE);
-
- // verify correct number of blocks get created for document
- // that is not an exact multiple of block size
- checkDocument(poifs, LARGER_BIG_BLOCK_SIZE + 1);
-
- // verify correct number of blocks get created for document
- // that is small
- checkDocument(poifs, LARGER_BIG_BLOCK_SIZE - 1);
-
- // verify correct number of blocks get created for document
- // that is rather small
- checkDocument(poifs, 199);
-
-
- // verify that output is correct
- POIFSDocument document = checkDocument(poifs, LARGER_BIG_BLOCK_SIZE + 1);
- DocumentProperty property = document.getDocumentProperty();
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
-
- property.writeData(stream);
- byte[] output = stream.toByteArray();
- byte[] array2 = RawDataUtil.decompress("H4sIAAAAAAAAAEtlyGMoYShiqGSwYCAH8DEwMf5HAsToMQdiRgEIGwCDyzEQgAAAAA==");
-
- assertArrayEquals(array2, output);
- }
- }
-
- private static POIFSDocument checkDocument(final POIFSFileSystem poifs, final int size) throws IOException {
- final byte[] input = new byte[size];
- IntStream.range(0, size).forEach(i -> input[i] = (byte)i);
-
- POIFSDocument document = ((DocumentNode)poifs.createDocument(
- new SlowInputStream(new ByteArrayInputStream(input)),
- "entry"+poifs.getRoot().getEntryCount())).getDocument();
-
- final int blockSize = (size >= 4096) ? 512 : 64;
- final int blockCount = (size + (blockSize-1)) / blockSize;
-
- final byte[] bytCpy = checkValues(blockCount, document, input);
- final POIFSDocument copied = makeCopy(document,bytCpy);
-
- checkValues(blockCount, copied, input);
-
- return document;
- }
-
- private static POIFSDocument makeCopy(POIFSDocument document, byte[] input) throws IOException {
- POIFSFileSystem poifs = document.getFileSystem();
- String name = "test" + input.length;
- DirectoryNode root = poifs.getRoot();
- if (root.hasEntry(name)) {
- root.deleteEntry((EntryNode)root.getEntry(name));
- }
- return ((DocumentNode)root
- .createDocument(name, new ByteArrayInputStream(input)))
- .getDocument();
- }
-
- private static byte[] checkValues(final int blockCountExp, POIFSDocument document, byte[] input) throws IOException {
- assertNotNull(document);
- assertNotNull(document.getDocumentProperty().getDocument());
- assertEquals(document, document.getDocumentProperty().getDocument());
-
- ByteArrayInputStream bis = new ByteArrayInputStream(input);
-
- int blockCountAct = 0, bytesRemaining = input.length;
- for (ByteBuffer bb : document) {
- assertTrue(bytesRemaining > 0);
- int bytesAct = Math.min(bb.remaining(), bytesRemaining);
- assertTrue(bytesAct <= document.getDocumentBlockSize());
- byte[] bufAct = new byte[bytesAct];
- bb.get(bufAct);
-
- byte[] bufExp = new byte[bytesAct];
- int bytesExp = bis.read(bufExp, 0, bytesAct);
- assertEquals(bytesExp, bytesAct);
-
- assertArrayEquals(bufExp, bufAct);
- blockCountAct++;
- bytesRemaining -= bytesAct;
- }
-
- assertEquals(blockCountExp, blockCountAct);
-
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- try (DocumentInputStream dis = document.getFileSystem().createDocumentInputStream(
- document.getDocumentProperty().getName())) {
- IOUtils.copy(dis, stream);
- }
-
- byte[] output = stream.toByteArray();
- assertArrayEquals(input, stream.toByteArray());
- return output;
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java
deleted file mode 100644
index 17c1b572d5..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.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.poifs.filesystem;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test DocumentDescriptor functionality
- */
-final class TestDocumentDescriptor {
-
- /**
- * test equality
- */
- @Test
- void testEquality() {
- String[] names = { "c1", "c2", "c3", "c4", "c5" };
- POIFSDocumentPath a1 = new POIFSDocumentPath();
- POIFSDocumentPath a2 = new POIFSDocumentPath(null);
- POIFSDocumentPath a3 = new POIFSDocumentPath(new String[ 0 ]);
- POIFSDocumentPath a4 = new POIFSDocumentPath(a1, null);
- POIFSDocumentPath a5 = new POIFSDocumentPath(a1,
- new String[ 0 ]);
- POIFSDocumentPath[] paths = { a1, a2, a3, a4, a5 };
-
- for (int j = 0; j < paths.length; j++) {
- for (int k = 0; k < paths.length; k++) {
- for (int m = 0; m < names.length; m++) {
- DocumentDescriptor d1 = new DocumentDescriptor(paths[ j ], names[ m ]);
-
- for (int n = 0; n < names.length; n++) {
- DocumentDescriptor d2 = new DocumentDescriptor(paths[ k ], names[ n ]);
-
- if (m == n) {
- assertEquals(d1, d2, "" + j + "," + k + "," + m + "," + n);
- } else {
- assertNotEquals(d1, d2);
- }
- }
- }
- }
- }
- a2 = new POIFSDocumentPath(a1, new String[]{"foo"});
- a3 = new POIFSDocumentPath(a2, new String[]{"bar"});
- a4 = new POIFSDocumentPath(a3, new String[]{"fubar"});
- a5 = new POIFSDocumentPath(a4, new String[]{"foobar"});
- POIFSDocumentPath[] builtUpPaths = {a1, a2, a3, a4, a5};
- POIFSDocumentPath[] fullPaths = {
- new POIFSDocumentPath(),
- new POIFSDocumentPath(new String[]{"foo"}),
- new POIFSDocumentPath(new String[]{"foo", "bar"}),
- new POIFSDocumentPath(new String[]{"foo", "bar", "fubar"}),
- new POIFSDocumentPath(new String[]{"foo", "bar", "fubar", "foobar"})
- };
-
- for (int k = 0; k < builtUpPaths.length; k++) {
- for (int j = 0; j < fullPaths.length; j++) {
- for (int m = 0; m < names.length; m++) {
- DocumentDescriptor d1 = new DocumentDescriptor(fullPaths[ j ], names[ m ]);
-
- for (int n = 0; n < names.length; n++) {
- DocumentDescriptor d2 = new DocumentDescriptor(builtUpPaths[ k ], names[ n ]);
-
- if ((k == j) && (m == n)) {
- assertEquals(d1, d2, "" + j + "," + k + "," + m + "," + n);
- } else {
- assertNotEquals(d1, d2);
- }
- }
- }
- }
- }
- POIFSDocumentPath[] badPaths = {
- new POIFSDocumentPath(new String[]{"_foo"}),
- new POIFSDocumentPath(new String[]{"foo", "_bar"}),
- new POIFSDocumentPath(new String[]{"foo", "bar", "_fubar"}),
- new POIFSDocumentPath(new String[]{"foo", "bar", "fubar", "_foobar"})
- };
-
- for (POIFSDocumentPath builtUpPath : builtUpPaths) {
- for (POIFSDocumentPath badPath : badPaths) {
- for (String s : names) {
- DocumentDescriptor d1 = new DocumentDescriptor(badPath, s);
- for (String name : names) {
- DocumentDescriptor d2 = new DocumentDescriptor(builtUpPath, name);
- assertNotEquals(d1, d2);
- }
- }
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java
deleted file mode 100644
index c0d4de1353..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-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.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Arrays;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.util.SuppressForbidden;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test DocumentInputStream functionality
- */
-final class TestDocumentInputStream {
- private DocumentNode _workbook_n;
- private byte[] _workbook_data;
- private static final int _workbook_size = 5000;
-
- // non-even division of _workbook_size, also non-even division of
- // any block size
- private static final int _buffer_size = 6;
-
- @BeforeEach
- void setUp() throws Exception {
- int blocks = (_workbook_size + 511) / 512;
-
- _workbook_data = new byte[512 * blocks];
- Arrays.fill(_workbook_data, (byte) -1);
- for (int j = 0; j < _workbook_size; j++) {
- _workbook_data[j] = (byte) (j * j);
- }
-
- // Now create the POIFS Version
- byte[] _workbook_data_only = Arrays.copyOf(_workbook_data, _workbook_size);
-
- POIFSFileSystem poifs = new POIFSFileSystem();
- // Make it easy when debugging to see what isn't the doc
- byte[] minus1 = new byte[512];
- Arrays.fill(minus1, (byte) -1);
- poifs.getBlockAt(-1).put(minus1);
- poifs.getBlockAt(0).put(minus1);
- poifs.getBlockAt(1).put(minus1);
-
- // Create the POIFS document
- _workbook_n = (DocumentNode) poifs.createDocument(
- new ByteArrayInputStream(_workbook_data_only),
- "Workbook"
- );
- }
-
- /**
- * test constructor
- */
- @Test
- void testConstructor() throws IOException {
- try (DocumentInputStream nstream = new DocumentInputStream(_workbook_n)) {
- assertEquals(_workbook_size, _workbook_n.getSize());
- assertEquals(_workbook_size, available(nstream));
- }
- }
-
- /**
- * test available() behavior
- */
- @Test
- void testAvailable() throws IOException {
- DocumentInputStream nstream = new DocumentInputStream(_workbook_n);
- assertEquals(_workbook_size, available(nstream));
- nstream.close();
-
- assertThrows(IllegalStateException.class, () -> available(nstream));
- }
-
- /**
- * test mark/reset/markSupported.
- */
- @SuppressWarnings("ResultOfMethodCallIgnored")
- @Test
- void testMarkFunctions() throws IOException {
- byte[] buffer = new byte[_workbook_size / 5];
- byte[] small_buffer = new byte[212];
-
- DocumentInputStream stream = new DocumentInputStream(_workbook_n);
- // Read a fifth of it, and check all's correct
- stream.read(buffer);
- for (int j = 0; j < buffer.length; j++) {
- assertEquals(_workbook_data[j], buffer[j], "checking byte " + j);
- }
- assertEquals(_workbook_size - buffer.length, available(stream));
-
- // Reset, and check the available goes back to being the
- // whole of the stream
- stream.reset();
- assertEquals(_workbook_size, available(stream));
-
-
- // Read part of a block
- stream.read(small_buffer);
- for (int j = 0; j < small_buffer.length; j++) {
- assertEquals(_workbook_data[j], small_buffer[j], "checking byte " + j);
- }
- assertEquals(_workbook_size - small_buffer.length, available(stream));
- stream.mark(0);
-
- // Read the next part
- stream.read(small_buffer);
- for (int j = 0; j < small_buffer.length; j++) {
- assertEquals(_workbook_data[j + small_buffer.length], small_buffer[j], "checking byte " + j);
- }
- assertEquals(_workbook_size - 2 * small_buffer.length, available(stream));
-
- // Reset, check it goes back to where it was
- stream.reset();
- assertEquals(_workbook_size - small_buffer.length, available(stream));
-
- // Read
- stream.read(small_buffer);
- for (int j = 0; j < small_buffer.length; j++) {
- assertEquals(_workbook_data[j + small_buffer.length], small_buffer[j], "checking byte " + j);
- }
- assertEquals(_workbook_size - 2 * small_buffer.length, available(stream));
-
-
- // Now read at various points
- Arrays.fill(small_buffer, (byte) 0);
- stream.read(small_buffer, 6, 8);
- stream.read(small_buffer, 100, 10);
- stream.read(small_buffer, 150, 12);
- int pos = small_buffer.length * 2;
- for (int j = 0; j < small_buffer.length; j++) {
- byte exp = 0;
- if (j >= 6 && j < 6 + 8) {
- exp = _workbook_data[pos];
- pos++;
- }
- if (j >= 100 && j < 100 + 10) {
- exp = _workbook_data[pos];
- pos++;
- }
- if (j >= 150 && j < 150 + 12) {
- exp = _workbook_data[pos];
- pos++;
- }
-
- assertEquals(exp, small_buffer[j], "checking byte " + j);
- }
-
- // Now repeat it with spanning multiple blocks
- stream = new DocumentInputStream(_workbook_n);
- // Read several blocks work
- buffer = new byte[_workbook_size / 5];
- stream.read(buffer);
- for (int j = 0; j < buffer.length; j++) {
- assertEquals(_workbook_data[j], buffer[j], "checking byte " + j);
- }
- assertEquals(_workbook_size - buffer.length, available(stream));
-
- // Read all of it again, check it began at the start again
- stream.reset();
- assertEquals(_workbook_size, available(stream));
-
- stream.read(buffer);
- for (int j = 0; j < buffer.length; j++) {
- assertEquals(_workbook_data[j], buffer[j], "checking byte " + j);
- }
-
- // Mark our position, and read another whole buffer
- stream.mark(12);
- stream.read(buffer);
- assertEquals(_workbook_size - (2 * buffer.length), available(stream));
- for (int j = buffer.length; j < (2 * buffer.length); j++) {
- assertEquals(_workbook_data[j], buffer[j - buffer.length], "checking byte " + j);
- }
-
- // Reset, should go back to only one buffer full read
- stream.reset();
- assertEquals(_workbook_size - buffer.length, available(stream));
-
- // Read the buffer again
- stream.read(buffer);
- assertEquals(_workbook_size - (2 * buffer.length), available(stream));
- for (int j = buffer.length; j < (2 * buffer.length); j++) {
- assertEquals(_workbook_data[j], buffer[j - buffer.length], "checking byte " + j);
- }
- assertTrue(stream.markSupported());
- }
-
- /**
- * test simple read method
- */
- @SuppressWarnings("ResultOfMethodCallIgnored")
- @Test
- void testReadSingleByte() throws IOException {
- DocumentInputStream stream = new DocumentInputStream(_workbook_n);
- int remaining = _workbook_size;
-
- // Try and read each byte in turn
- for (int j = 0; j < _workbook_size; j++) {
- int b = stream.read();
- assertTrue(b >= 0, "checking sign of " + j);
- assertEquals(_workbook_data[j], (byte) b, "validating byte " + j);
- remaining--;
- assertEquals(remaining, available(stream), "checking remaining after reading byte " + j);
- }
-
- // Ensure we fell off the end
- assertEquals(-1, stream.read());
-
- // Check that after close we can no longer read
- stream.close();
- assertThrows(IOException.class, stream::read);
- }
-
- /**
- * Test buffered read
- */
- @SuppressWarnings("ResultOfMethodCallIgnored")
- @Test
- void testBufferRead() throws IOException {
- DocumentInputStream stream = new DocumentInputStream(_workbook_n);
- // Need to give a byte array to read
- assertThrows(NullPointerException.class, () -> stream.read(null));
-
- // test reading zero length buffer
- assertEquals(0, stream.read(new byte[0]));
- assertEquals(_workbook_size, available(stream));
- byte[] buffer = new byte[_buffer_size];
- int offset = 0;
-
- while (available(stream) >= buffer.length) {
- assertEquals(_buffer_size, stream.read(buffer));
- for (byte element : buffer) {
- assertEquals(_workbook_data[offset], element, "in main loop, byte " + offset);
- offset++;
- }
- assertEquals(_workbook_size - offset, available(stream), "offset " + offset);
- }
- assertEquals(_workbook_size % _buffer_size, available(stream));
- Arrays.fill(buffer, (byte) 0);
- int count = stream.read(buffer);
-
- assertEquals(_workbook_size % _buffer_size, count);
- for (int j = 0; j < count; j++) {
- assertEquals(_workbook_data[offset], buffer[j], "past main loop, byte " + offset);
- offset++;
- }
- assertEquals(_workbook_size, offset);
- for (int j = count; j < buffer.length; j++) {
- assertEquals(0, buffer[j], "checking remainder, byte " + j);
- }
- assertEquals(-1, stream.read(buffer));
- stream.close();
-
- assertThrows(IOException.class, () -> stream.read(buffer));
- }
-
- /**
- * Test complex buffered read
- */
- @SuppressWarnings("ResultOfMethodCallIgnored")
- @Test
- void testComplexBufferRead() throws IOException {
- DocumentInputStream stream = new DocumentInputStream(_workbook_n);
- assertThrows(IllegalArgumentException.class, () -> stream.read(null, 0, 1));
-
- // test illegal offsets and lengths
- assertThrows(IndexOutOfBoundsException.class, () -> stream.read(new byte[5], -4, 0));
- assertThrows(IndexOutOfBoundsException.class, () -> stream.read(new byte[5], 0, -4));
- assertThrows(IndexOutOfBoundsException.class, () -> stream.read(new byte[5], 0, 6));
-
- // test reading zero
- assertEquals(0, stream.read(new byte[5], 0, 0));
- assertEquals(_workbook_size, available(stream));
- byte[] buffer = new byte[_workbook_size];
- int offset = 0;
-
- while (available(stream) >= _buffer_size) {
- Arrays.fill(buffer, (byte) 0);
- assertEquals(_buffer_size, stream.read(buffer, offset, _buffer_size));
- for (int j = 0; j < offset; j++) {
- assertEquals(0, buffer[j], "checking byte " + j);
- }
- for (int j = offset; j < (offset + _buffer_size); j++) {
- assertEquals(_workbook_data[j], buffer[j], "checking byte " + j);
- }
- for (int j = offset + _buffer_size; j < buffer.length; j++) {
- assertEquals(0, buffer[j], "checking byte " + j);
- }
- offset += _buffer_size;
- assertEquals(_workbook_size - offset, available(stream), "offset " + offset);
- }
- assertEquals(_workbook_size % _buffer_size, available(stream));
- Arrays.fill(buffer, (byte) 0);
- int count = stream.read(buffer, offset, _workbook_size % _buffer_size);
-
- assertEquals(_workbook_size % _buffer_size, count);
- for (int j = 0; j < offset; j++) {
- assertEquals(0, buffer[j], "checking byte " + j);
- }
- for (int j = offset; j < buffer.length; j++) {
- assertEquals(_workbook_data[j], buffer[j], "checking byte " + j);
- }
- assertEquals(_workbook_size, offset + count);
- for (int j = count; j < offset; j++) {
- assertEquals(0, buffer[j], "byte " + j);
- }
-
- assertEquals(-1, stream.read(buffer, 0, 1));
- stream.close();
-
- assertThrows(IOException.class, () -> stream.read(buffer, 0, 1));
- }
-
- /**
- * Tests that we can skip within the stream
- */
- @Test
- void testSkip() throws IOException {
- DocumentInputStream stream = new DocumentInputStream(_workbook_n);
- assertEquals(_workbook_size, available(stream));
- int count = available(stream);
-
- while (available(stream) >= _buffer_size) {
- assertEquals(_buffer_size, stream.skip(_buffer_size));
- count -= _buffer_size;
- assertEquals(count, available(stream));
- }
- assertEquals(_workbook_size % _buffer_size,
- stream.skip(_buffer_size));
- assertEquals(0, available(stream));
- stream.reset();
- assertEquals(_workbook_size, available(stream));
- assertEquals(_workbook_size, stream.skip(_workbook_size * 2));
- assertEquals(0, available(stream));
- stream.reset();
- assertEquals(_workbook_size, available(stream));
- assertEquals(_workbook_size,
- stream.skip(2 + (long) Integer.MAX_VALUE));
- assertEquals(0, available(stream));
- }
-
- /**
- * Test that we can read files at multiple levels down the tree
- */
- @Test
- void testReadMultipleTreeLevels() throws Exception {
- final POIDataSamples _samples = POIDataSamples.getPublisherInstance();
- File sample = _samples.getFile("Sample.pub");
-
- DocumentInputStream stream;
-
- try (POIFSFileSystem poifs = new POIFSFileSystem(sample)) {
- // Ensure we have what we expect on the root
- assertEquals(poifs, poifs.getRoot().getFileSystem());
-
- // Check inside
- DirectoryNode root = poifs.getRoot();
- // Top Level
- Entry top = root.getEntry("Contents");
- assertTrue(top.isDocumentEntry());
- stream = root.createDocumentInputStream(top);
- assertNotEquals(-1, stream.read());
-
- // One Level Down
- DirectoryNode escher = (DirectoryNode) root.getEntry("Escher");
- Entry one = escher.getEntry("EscherStm");
- assertTrue(one.isDocumentEntry());
- stream = escher.createDocumentInputStream(one);
- assertNotEquals(-1, stream.read());
-
- // Two Levels Down
- DirectoryNode quill = (DirectoryNode) root.getEntry("Quill");
- DirectoryNode quillSub = (DirectoryNode) quill.getEntry("QuillSub");
- Entry two = quillSub.getEntry("CONTENTS");
- assertTrue(two.isDocumentEntry());
- stream = quillSub.createDocumentInputStream(two);
- assertNotEquals(-1, stream.read());
- }
- }
-
- @SuppressForbidden("just for testing")
- private static int available(InputStream is) throws IOException {
- return is.available();
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java
deleted file mode 100644
index d2815e0254..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.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.poifs.filesystem;
-
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.fail;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.poi.util.IOUtils;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test DocumentOutputStream functionality
- */
-final class TestDocumentOutputStream {
-
- /**
- * test write(int) behavior
- */
- @Test
- void testWrite1() throws IOException {
- final byte[] expected = data(25);
-
- POIFSWriterListener l = (event) -> {
- DocumentOutputStream dstream = event.getStream();
-
- try {
- for (byte b : expected) {
- dstream.write((int)b);
- }
- } catch (IOException ignored) {
- fail("stream exhausted too early");
- }
-
- assertThrows(IOException.class, () -> dstream.write(0));
- };
-
- compare(l, expected);
- }
-
- /**
- * test write(byte[]) behavior
- */
- @Test
- void testWrite2() throws IOException {
- final byte[] expected = data(24);
-
- POIFSWriterListener l = (event) -> {
- DocumentOutputStream dstream = event.getStream();
-
- try {
- dstream.write(expected);
- } catch (IOException ignored) {
- fail("stream exhausted too early");
- }
-
- assertThrows(IOException.class, () -> dstream.write(new byte[]{'7','7','7','7'}));
- };
-
- compare(l, expected);
- }
-
- /**
- * test write(byte[], int, int) behavior
- */
- @Test
- void testWrite3() throws IOException {
- byte[] input = data(50);
- byte[] expected = Arrays.copyOfRange(input, 1, 1+25);
-
- POIFSWriterListener l = (event) -> {
- DocumentOutputStream dstream = event.getStream();
- try {
- dstream.write(input, 1, 25);
- } catch (IOException ignored) {
- fail("stream exhausted too early");
- }
- assertThrows(IOException.class, () -> dstream.write(input, 0, 1));
- };
-
- compare(l, expected);
- }
-
- private static byte[] data(int len) {
- byte[] input = new byte[len];
- for (int i = 0; i < len; i++) {
- input[i] = (byte)('0' + (i%10));
- }
- return input;
- }
-
- private void compare(POIFSWriterListener l, byte[] expected) throws IOException {
- try (POIFSFileSystem poifs = new POIFSFileSystem()) {
- DirectoryNode root = poifs.getRoot();
- root.createDocument("foo", expected.length, l);
-
- try (DocumentInputStream is = root.createDocumentInputStream("foo")) {
- final ByteArrayOutputStream bos = new ByteArrayOutputStream(expected.length);
- IOUtils.copy(is, bos);
- assertArrayEquals(expected, bos.toByteArray());
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java b/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java
deleted file mode 100644
index c594fb513d..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.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.poifs.filesystem;
-
-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 java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.stream.Stream;
-
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.apache.poi.util.IOUtils;
-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;
-
-final class TestEmptyDocument {
- private static final Logger LOG = LogManager.getLogger(TestEmptyDocument.class);
-
- private interface EmptyDoc {
- void handle(DirectoryEntry dir) throws IOException;
- }
-
- public static Stream emptySupplier() {
- return Stream.of(
- Arguments.of("SingleEmptyDocument", (EmptyDoc)TestEmptyDocument::SingleEmptyDocument),
- Arguments.of("SingleEmptyDocumentEvent", (EmptyDoc)TestEmptyDocument::SingleEmptyDocumentEvent),
- Arguments.of("EmptyDocumentWithFriend", (EmptyDoc)TestEmptyDocument::EmptyDocumentWithFriend),
- Arguments.of("EmptyDocumentEventWithFriend", (EmptyDoc)TestEmptyDocument::EmptyDocumentEventWithFriend)
- );
- }
-
- private static void SingleEmptyDocument(DirectoryEntry dir) throws IOException {
- dir.createDocument("Foo", new ByteArrayInputStream(new byte[]{}));
- }
-
- private static void SingleEmptyDocumentEvent(DirectoryEntry dir) throws IOException {
- dir.createDocument("Foo", 0, event -> LOG.atWarn().log("written"));
- }
-
- private static void EmptyDocumentWithFriend(DirectoryEntry dir) throws IOException {
- dir.createDocument("Bar", new ByteArrayInputStream(new byte[]{0}));
- dir.createDocument("Foo", new ByteArrayInputStream(new byte[]{}));
- }
-
- private static void EmptyDocumentEventWithFriend(DirectoryEntry dir) throws IOException {
- dir.createDocument("Bar", 1, event -> {
- try {
- event.getStream().write(0);
- } catch (IOException exception) {
- throw new RuntimeException("exception on write: " + exception);
- }
- });
- dir.createDocument("Foo", 0, event -> {});
- }
-
-
- @ParameterizedTest(name = "{index} {0}")
- @MethodSource("emptySupplier")
- void testFoo(String testName, EmptyDoc emptyDoc) throws IOException {
- try (POIFSFileSystem fs = new POIFSFileSystem()) {
- DirectoryEntry dir = fs.getRoot();
- emptyDoc.handle(dir);
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- fs.writeFilesystem(out);
- assertDoesNotThrow(() -> new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())));
- }
- }
-
- @Test
- void testEmptyDocumentBug11744() throws Exception {
- byte[] testData = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- try (POIFSFileSystem fs = new POIFSFileSystem()) {
- fs.createDocument(new ByteArrayInputStream(new byte[0]), "Empty");
- fs.createDocument(new ByteArrayInputStream(testData), "NotEmpty");
- fs.writeFilesystem(out);
- }
-
- // This line caused the error.
- try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()))) {
- DocumentEntry entry = (DocumentEntry) fs.getRoot().getEntry("Empty");
- assertEquals(0, entry.getSize(), "Expected zero size");
- byte[] actualReadbackData;
- actualReadbackData = IOUtils.toByteArray(new DocumentInputStream(entry));
- assertEquals(0, actualReadbackData.length, "Expected zero read from stream");
-
- entry = (DocumentEntry) fs.getRoot().getEntry("NotEmpty");
- actualReadbackData = IOUtils.toByteArray(new DocumentInputStream(entry));
- assertEquals(testData.length, entry.getSize(), "Expected size was wrong");
- assertArrayEquals(testData, actualReadbackData, "Expected same data read from stream");
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java b/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java
deleted file mode 100644
index b85550cc15..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-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 java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.jupiter.api.Test;
-
-class TestEntryUtils {
- private static final byte[] dataSmallA = new byte[] { 12, 42, 11, -12, -121 };
- private static final byte[] dataSmallB = new byte[] { 11, 73, 21, -92, -103 };
-
- @Test
- void testCopyRecursively() throws IOException {
- POIFSFileSystem fsD = new POIFSFileSystem();
- POIFSFileSystem fs = new POIFSFileSystem();
- DirectoryEntry dirA = fs.createDirectory("DirA");
- DirectoryEntry dirB = fs.createDirectory("DirB");
-
- DocumentEntry entryR = fs.createDocument(new ByteArrayInputStream(dataSmallA), "EntryRoot");
- DocumentEntry entryA1 = dirA.createDocument("EntryA1", new ByteArrayInputStream(dataSmallA));
- DocumentEntry entryA2 = dirA.createDocument("EntryA2", new ByteArrayInputStream(dataSmallB));
-
- // Copy docs
- assertEquals(0, fsD.getRoot().getEntryCount());
- EntryUtils.copyNodeRecursively(entryR, fsD.getRoot());
-
- assertEquals(1, fsD.getRoot().getEntryCount());
- assertNotNull(fsD.getRoot().getEntry("EntryRoot"));
-
- EntryUtils.copyNodeRecursively(entryA1, fsD.getRoot());
- assertEquals(2, fsD.getRoot().getEntryCount());
- assertNotNull(fsD.getRoot().getEntry("EntryRoot"));
- assertNotNull(fsD.getRoot().getEntry("EntryA1"));
-
- EntryUtils.copyNodeRecursively(entryA2, fsD.getRoot());
- assertEquals(3, fsD.getRoot().getEntryCount());
- assertNotNull(fsD.getRoot().getEntry("EntryRoot"));
- assertNotNull(fsD.getRoot().getEntry("EntryA1"));
- assertNotNull(fsD.getRoot().getEntry("EntryA2"));
-
- fsD.close();
-
- // Copy directories
- fsD = new POIFSFileSystem();
- assertEquals(0, fsD.getRoot().getEntryCount());
-
- EntryUtils.copyNodeRecursively(dirB, fsD.getRoot());
- assertEquals(1, fsD.getRoot().getEntryCount());
- assertNotNull(fsD.getRoot().getEntry("DirB"));
- assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount());
-
- EntryUtils.copyNodeRecursively(dirA, fsD.getRoot());
- assertEquals(2, fsD.getRoot().getEntryCount());
- assertNotNull(fsD.getRoot().getEntry("DirB"));
- assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount());
- assertNotNull(fsD.getRoot().getEntry("DirA"));
- assertEquals(2, ((DirectoryEntry)fsD.getRoot().getEntry("DirA")).getEntryCount());
- fsD.close();
-
- // Copy the whole lot
- fsD = new POIFSFileSystem();
- assertEquals(0, fsD.getRoot().getEntryCount());
-
- EntryUtils.copyNodes(fs, fsD, new ArrayList<>());
- assertEquals(3, fsD.getRoot().getEntryCount());
- assertNotNull(fsD.getRoot().getEntry(dirA.getName()));
- assertNotNull(fsD.getRoot().getEntry(dirB.getName()));
- assertNotNull(fsD.getRoot().getEntry(entryR.getName()));
- assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount());
- assertEquals(2, ((DirectoryEntry)fsD.getRoot().getEntry("DirA")).getEntryCount());
- fsD.close();
- fs.close();
- }
-
- @Test
- void testAreDocumentsIdentical() throws IOException {
- POIFSFileSystem fs = new POIFSFileSystem();
- DirectoryEntry dirA = fs.createDirectory("DirA");
- DirectoryEntry dirB = fs.createDirectory("DirB");
-
- DocumentEntry entryA1 = dirA.createDocument("Entry1", new ByteArrayInputStream(dataSmallA));
- DocumentEntry entryA1b = dirA.createDocument("Entry1b", new ByteArrayInputStream(dataSmallA));
- DocumentEntry entryA2 = dirA.createDocument("Entry2", new ByteArrayInputStream(dataSmallB));
- DocumentEntry entryB1 = dirB.createDocument("Entry1", new ByteArrayInputStream(dataSmallA));
-
-
- // Names must match
- assertNotEquals(entryA1.getName(), entryA1b.getName());
- assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA1b));
-
- // Contents must match
- assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA2));
-
- // Parents don't matter if contents + names are the same
- assertNotEquals(entryA1.getParent(), entryB1.getParent());
- assertTrue(EntryUtils.areDocumentsIdentical(entryA1, entryB1));
-
-
- // Can work with POIFS
- ByteArrayOutputStream tmpO = new ByteArrayOutputStream();
- fs.writeFilesystem(tmpO);
-
- ByteArrayInputStream tmpI = new ByteArrayInputStream(tmpO.toByteArray());
- POIFSFileSystem nfs = new POIFSFileSystem(tmpI);
-
- DirectoryEntry dN1 = (DirectoryEntry)nfs.getRoot().getEntry("DirA");
- DirectoryEntry dN2 = (DirectoryEntry)nfs.getRoot().getEntry("DirB");
- DocumentEntry eNA1 = (DocumentEntry)dN1.getEntry(entryA1.getName());
- DocumentEntry eNA2 = (DocumentEntry)dN1.getEntry(entryA2.getName());
- DocumentEntry eNB1 = (DocumentEntry)dN2.getEntry(entryB1.getName());
-
- assertFalse(EntryUtils.areDocumentsIdentical(eNA1, eNA2));
- assertTrue(EntryUtils.areDocumentsIdentical(eNA1, eNB1));
-
- assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA1b));
- assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA2));
-
- assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryA1));
- assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryB1));
- nfs.close();
- fs.close();
- }
-
- @Test
- void testAreDirectoriesIdentical() throws IOException {
- POIFSFileSystem fs = new POIFSFileSystem();
- DirectoryEntry dirA = fs.createDirectory("DirA");
- DirectoryEntry dirB = fs.createDirectory("DirB");
-
- // Names must match
- assertFalse(EntryUtils.areDirectoriesIdentical(dirA, dirB));
-
- // Empty dirs are fine
- DirectoryEntry dirA1 = dirA.createDirectory("TheDir");
- DirectoryEntry dirB1 = dirB.createDirectory("TheDir");
- assertEquals(0, dirA1.getEntryCount());
- assertEquals(0, dirB1.getEntryCount());
- assertTrue(EntryUtils.areDirectoriesIdentical(dirA1, dirB1));
-
- // Otherwise children must match
- dirA1.createDocument("Entry1", new ByteArrayInputStream(dataSmallA));
- assertFalse(EntryUtils.areDirectoriesIdentical(dirA1, dirB1));
-
- dirB1.createDocument("Entry1", new ByteArrayInputStream(dataSmallA));
- assertTrue(EntryUtils.areDirectoriesIdentical(dirA1, dirB1));
-
- dirA1.createDirectory("DD");
- assertFalse(EntryUtils.areDirectoriesIdentical(dirA1, dirB1));
- dirB1.createDirectory("DD");
- assertTrue(EntryUtils.areDirectoriesIdentical(dirA1, dirB1));
-
-
- // Excludes support
- List excl = Arrays.asList("Ignore1", "IgnDir/Ign2");
- FilteringDirectoryNode fdA = new FilteringDirectoryNode(dirA1, excl);
- FilteringDirectoryNode fdB = new FilteringDirectoryNode(dirB1, excl);
-
- assertTrue(EntryUtils.areDirectoriesIdentical(fdA, fdB));
-
- // Add an ignored doc, no notice is taken
- fdA.createDocument("Ignore1", new ByteArrayInputStream(dataSmallA));
- assertTrue(EntryUtils.areDirectoriesIdentical(fdA, fdB));
-
- // Add a directory with filtered contents, not the same
- DirectoryEntry dirAI = dirA1.createDirectory("IgnDir");
- assertFalse(EntryUtils.areDirectoriesIdentical(fdA, fdB));
-
- DirectoryEntry dirBI = dirB1.createDirectory("IgnDir");
- assertTrue(EntryUtils.areDirectoriesIdentical(fdA, fdB));
-
- // Add something to the filtered subdir that gets ignored
- dirAI.createDocument("Ign2", new ByteArrayInputStream(dataSmallA));
- assertTrue(EntryUtils.areDirectoriesIdentical(fdA, fdB));
-
- // And something that doesn't
- dirAI.createDocument("IgnZZ", new ByteArrayInputStream(dataSmallA));
- assertFalse(EntryUtils.areDirectoriesIdentical(fdA, fdB));
-
- dirBI.createDocument("IgnZZ", new ByteArrayInputStream(dataSmallA));
- assertTrue(EntryUtils.areDirectoriesIdentical(fdA, fdB));
-
- fs.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java b/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java
deleted file mode 100644
index 456ca076ac..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestFileMagic.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-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.assertSame;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
-import java.util.Random;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.util.TempFile;
-import org.junit.jupiter.api.Test;
-
-class TestFileMagic {
- @Test
- void testFileMagic() {
- assertEquals(FileMagic.XML, FileMagic.valueOf("XML"));
- assertEquals(FileMagic.XML, FileMagic.valueOf(" FileMagic.valueOf("some string"));
- }
-
- @Test
- void testFileMagicFile() throws IOException {
- assertEquals(FileMagic.OLE2, FileMagic.valueOf(POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xls")));
- assertEquals(FileMagic.OOXML, FileMagic.valueOf(POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xlsx")));
- }
-
- @Test
- void testFileMagicStream() throws IOException {
- try (InputStream stream = new BufferedInputStream(new FileInputStream(POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xls")))) {
- assertEquals(FileMagic.OLE2, FileMagic.valueOf(stream));
- }
- try (InputStream stream = new BufferedInputStream(new FileInputStream(POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xlsx")))) {
- assertEquals(FileMagic.OOXML, FileMagic.valueOf(stream));
- }
- }
-
- @Test
- void testPrepare() throws IOException {
- try (InputStream stream = new BufferedInputStream(new FileInputStream(POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xlsx")))) {
- assertSame(stream, FileMagic.prepareToCheckMagic(stream));
- }
-
- try (InputStream stream = new InputStream() {
- @Override
- public int read() {
- return 0;
- }
- }) {
- assertNotSame(stream, FileMagic.prepareToCheckMagic(stream));
- }
- }
-
- @Test
- void testMatchingButTooLessData() {
- // this matches JPG, but is not long enough, previously this caused an Exception
- byte[] data = new byte[] { -1, -40, -1, -32, 0, 16, 74, 70 };
-
- assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf(data));
- }
-
- @Test
- void testShortFile() throws IOException {
- // having a file shorter than 8 bytes previously caused an exception
- fetchMagicFromData(new byte[] { -1, -40, -1, -32, 0 });
- fetchMagicFromData(new byte[] { -1, -40, -1, -32 });
- fetchMagicFromData(new byte[] { -1, -40, -1 });
- fetchMagicFromData(new byte[] { -1, -40 });
- fetchMagicFromData(new byte[] { -1 });
- fetchMagicFromData(new byte[0]);
- }
-
- private void fetchMagicFromData(byte[] data) throws IOException {
- File file = TempFile.createTempFile("TestFileMagic", ".bin");
- try {
- try (FileOutputStream fos = new FileOutputStream(file)) {
- fos.write(data);
- }
-
- assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf(file));
- } finally {
- assertTrue(file.delete());
- }
- }
-
- @Test
- void testMarkRequired() throws IOException {
- byte[] data = new byte[] { -1, -40, -1, -32, 0 };
-
- File file = TempFile.createTempFile("TestFileMagic", ".bin");
- try {
- try (FileOutputStream fos = new FileOutputStream(file)) {
- fos.write(data);
- }
-
- // a FileInputStream does not support "marking"
- try (FileInputStream str = new FileInputStream(file)) {
- assertFalse(str.markSupported());
-
- assertThrows(IOException.class, () -> FileMagic.valueOf(str));
- }
- } finally {
- assertTrue(file.delete());
- }
- }
-
- @Test
- void testPatterns() {
- // just try to trash the functionality with some byte-patterns
- for(int i = 0; i < 256;i++) {
- final byte[] data = new byte[12];
- for(int j = 0;j < 12; j++) {
- data[j] = (byte)i;
-
- assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf(data));
- }
- }
- }
-
- @Test
- void testRandomPatterns() {
- Random random = new Random();
-
- // just try to trash the functionality with some byte-patterns
- for(int i = 0; i < 1000;i++) {
- final byte[] data = new byte[12];
- random.nextBytes(data);
-
- // we cannot check for UNKNOWN as we might hit valid byte-patterns here as well
- try {
- assertNotNull(FileMagic.valueOf(data));
- } catch (Exception e) {
- throw new IllegalStateException("Failed with pattern " + Arrays.toString(data), e);
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java b/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java
deleted file mode 100644
index ef504aca69..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.poi.POIDataSamples;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests bugs for POIFSFileSystem
- */
-final class TestFileSystemBugs {
- private static final POIDataSamples _samples = POIDataSamples.getPOIFSInstance();
- private static final POIDataSamples _ssSamples = POIDataSamples.getSpreadSheetInstance();
-
- private List openedFSs;
-
- @AfterEach
- void tearDown() {
- if (openedFSs != null && !openedFSs.isEmpty()) {
- for (POIFSFileSystem fs : openedFSs) {
- try {
- fs.close();
- } catch (Exception e) {
- System.err.println("Error closing FS: " + e);
- }
- }
- }
- openedFSs = null;
- }
-
- private DirectoryNode openSample(String name) throws Exception {
- try (InputStream inps = _samples.openResourceAsStream(name)) {
- return openSample(inps);
- }
- }
-
- @SuppressWarnings("SameParameterValue")
- private DirectoryNode openSSSample(String name) throws Exception {
- try (InputStream inps = _ssSamples.openResourceAsStream(name)) {
- return openSample(inps);
- }
- }
-
- private DirectoryNode openSample(InputStream inps) throws Exception {
- POIFSFileSystem nfs = new POIFSFileSystem(inps);
- if (openedFSs == null) {
- openedFSs = new ArrayList<>();
- }
- openedFSs.add(nfs);
-
- return nfs.getRoot();
- }
-
- /**
- * Test that we can open files that come via Lotus notes.
- * These have a top level directory without a name....
- */
- @Test
- void testNotesOLE2Files() throws Exception {
- // Check the contents
- DirectoryNode root = openSample("Notes.ole2");
- assertEquals(1, root.getEntryCount());
-
- Entry entry = root.getEntries().next();
- assertTrue(entry.isDirectoryEntry());
- assertTrue(entry instanceof DirectoryEntry);
-
- // The directory lacks a name!
- DirectoryEntry dir = (DirectoryEntry)entry;
- assertEquals("", dir.getName());
-
- // Has two children
- assertEquals(2, dir.getEntryCount());
-
- // Check them
- Iterator it = dir.getEntries();
- entry = it.next();
- assertTrue(entry.isDocumentEntry());
- assertEquals(Ole10Native.OLE10_NATIVE, entry.getName());
-
- entry = it.next();
- assertTrue(entry.isDocumentEntry());
- assertEquals("\u0001CompObj", entry.getName());
- }
-
- /**
- * Ensure that a file with a corrupted property in the
- * properties table can still be loaded, and the remaining
- * properties used
- * Note - only works for POIFSFileSystem
- * can't cope with this level of corruption
- */
- @Test
- void testCorruptedProperties() throws Exception {
- DirectoryNode root = openSample("unknown_properties.msg");
- assertEquals(42, root.getEntryCount());
- }
-
- /**
- * With heavily nested documents, ensure we still re-write the same
- */
- @Test
- void testHeavilyNestedReWrite() throws Exception {
- DirectoryNode root = openSSSample("ex42570-20305.xls");
- // Record the structure
- Map entries = new HashMap<>();
- fetchSizes("/", root, entries);
-
- // Prepare to copy
- DirectoryNode dest = new POIFSFileSystem().getRoot();
-
- // Copy over
- EntryUtils.copyNodes(root, dest);
-
- // Re-load
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- root.getFileSystem().writeFilesystem(baos);
-
- POIFSFileSystem read = new POIFSFileSystem(
- new ByteArrayInputStream(baos.toByteArray()));
-
- // Check the structure matches
- checkSizes("/", read.getRoot(), entries);
- }
-
- private void fetchSizes(String path, DirectoryNode dir, Map entries) {
- for (Entry entry : dir) {
- if (entry instanceof DirectoryNode) {
- String ourPath = path + entry.getName() + "/";
- entries.put(ourPath, -1);
- fetchSizes(ourPath, (DirectoryNode)entry, entries);
- } else {
- DocumentNode doc = (DocumentNode)entry;
- entries.put(path+entry.getName(), doc.getSize());
- }
- }
- }
- private void checkSizes(String path, DirectoryNode dir, Map entries) {
- for (Entry entry : dir) {
- if (entry instanceof DirectoryNode) {
- String ourPath = path + entry.getName() + "/";
- assertTrue(entries.containsKey(ourPath));
- assertEquals(-1, entries.get(ourPath).intValue());
- checkSizes(ourPath, (DirectoryNode)entry, entries);
- } else {
- DocumentNode doc = (DocumentNode)entry;
- assertEquals(entries.get(path+entry.getName()).intValue(), doc.getSize());
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java b/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java
deleted file mode 100644
index aa9c8883af..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java
+++ /dev/null
@@ -1,164 +0,0 @@
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-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 java.io.ByteArrayInputStream;
-import java.io.FileNotFoundException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test FilteringDirectoryNode functionality
- */
-final class TestFilteringDirectoryNode {
- private POIFSFileSystem fs;
- private DirectoryEntry dirA;
- private DirectoryEntry dirAA;
- private DirectoryEntry dirB;
- private DocumentEntry eRoot;
- private DocumentEntry eA;
- private DocumentEntry eAA;
-
- @BeforeEach
- void setUp() throws Exception {
- fs = new POIFSFileSystem();
- dirA = fs.createDirectory("DirA");
- dirB = fs.createDirectory("DirB");
- dirAA = dirA.createDirectory("DirAA");
- eRoot = fs.getRoot().createDocument("Root", new ByteArrayInputStream(new byte[]{}));
- eA = dirA.createDocument("NA", new ByteArrayInputStream(new byte[]{}));
- eAA = dirAA.createDocument("NAA", new ByteArrayInputStream(new byte[]{}));
- }
-
- @Test
- void testNoFiltering() throws Exception {
- FilteringDirectoryNode d = new FilteringDirectoryNode(fs.getRoot(), new HashSet<>());
- assertEquals(3, d.getEntryCount());
- assertEquals(dirA.getName(), d.getEntry(dirA.getName()).getName());
-
- assertTrue(d.getEntry(dirA.getName()).isDirectoryEntry());
- assertFalse(d.getEntry(dirA.getName()).isDocumentEntry());
-
- assertTrue(d.getEntry(dirB.getName()).isDirectoryEntry());
- assertFalse(d.getEntry(dirB.getName()).isDocumentEntry());
-
- assertFalse(d.getEntry(eRoot.getName()).isDirectoryEntry());
- assertTrue(d.getEntry(eRoot.getName()).isDocumentEntry());
-
- Iterator i = d.getEntries();
- assertEquals(dirA, i.next());
- assertEquals(dirB, i.next());
- assertEquals(eRoot, i.next());
- assertThrows(NoSuchElementException.class, i::next, "Should throw NoSuchElementException when depleted");
- }
-
- @Test
- void testChildFiltering() throws Exception {
- List excl = Arrays.asList("NotThere", "AlsoNotThere", eRoot.getName());
- FilteringDirectoryNode d1 = new FilteringDirectoryNode(fs.getRoot(), excl);
-
- assertEquals(2, d1.getEntryCount());
- assertTrue(d1.hasEntry(dirA.getName()));
- assertTrue(d1.hasEntry(dirB.getName()));
- assertFalse(d1.hasEntry(eRoot.getName()));
-
- assertEquals(dirA, d1.getEntry(dirA.getName()));
- assertEquals(dirB, d1.getEntry(dirB.getName()));
- assertThrows(FileNotFoundException.class, () -> d1.getEntry(eRoot.getName()));
-
- Iterator i = d1.getEntries();
- assertEquals(dirA, i.next());
- assertEquals(dirB, i.next());
- assertThrows(NoSuchElementException.class, i::next, "Should throw NoSuchElementException when depleted");
-
-
- // Filter more
- excl = Arrays.asList("NotThere", "AlsoNotThere", eRoot.getName(), dirA.getName());
- FilteringDirectoryNode d2 = new FilteringDirectoryNode(fs.getRoot(), excl);
-
- assertEquals(1, d2.getEntryCount());
- assertFalse(d2.hasEntry(dirA.getName()));
- assertTrue(d2.hasEntry(dirB.getName()));
- assertFalse(d2.hasEntry(eRoot.getName()));
- assertThrows(FileNotFoundException.class, () -> d2.getEntry(dirA.getName()), "Should be filtered");
- assertEquals(dirB, d2.getEntry(dirB.getName()));
- assertThrows(FileNotFoundException.class, () -> d2.getEntry(eRoot.getName()), "Should be filtered");
-
- i = d2.getEntries();
- assertEquals(dirB, i.next());
- assertThrows(NoSuchElementException.class, i::next, "Should throw NoSuchElementException when depleted");
-
- // Filter everything
- excl = Arrays.asList("NotThere", eRoot.getName(), dirA.getName(), dirB.getName());
- FilteringDirectoryNode d3 = new FilteringDirectoryNode(fs.getRoot(), excl);
-
- assertEquals(0, d3.getEntryCount());
- assertFalse(d3.hasEntry(dirA.getName()));
- assertFalse(d3.hasEntry(dirB.getName()));
- assertFalse(d3.hasEntry(eRoot.getName()));
- assertThrows(FileNotFoundException.class, () -> d3.getEntry(dirA.getName()), "Should be filtered");
- assertThrows(FileNotFoundException.class, () -> d3.getEntry(dirB.getName()), "Should be filtered");
- assertThrows(FileNotFoundException.class, () -> d3.getEntry(eRoot.getName()), "Should be filtered");
-
- i = d3.getEntries();
- assertThrows(NoSuchElementException.class, i::next, "Should throw NoSuchElementException when depleted");
- }
-
- @Test
- void testNestedFiltering() throws Exception {
- List excl = Arrays.asList(dirA.getName() + "/" + "MadeUp",
- dirA.getName() + "/" + eA.getName(),
- dirA.getName() + "/" + dirAA.getName() + "/Test",
- eRoot.getName());
- FilteringDirectoryNode d = new FilteringDirectoryNode(fs.getRoot(), excl);
-
- // Check main
- assertEquals(2, d.getEntryCount());
- assertTrue(d.hasEntry(dirA.getName()));
- assertTrue(d.hasEntry(dirB.getName()));
- assertFalse(d.hasEntry(eRoot.getName()));
-
- // Check filtering down
- assertTrue(d.getEntry(dirA.getName()) instanceof FilteringDirectoryNode);
- assertFalse(d.getEntry(dirB.getName()) instanceof FilteringDirectoryNode);
-
- DirectoryEntry fdA = (DirectoryEntry) d.getEntry(dirA.getName());
- assertFalse(fdA.hasEntry(eA.getName()));
- assertTrue(fdA.hasEntry(dirAA.getName()));
-
- DirectoryEntry fdAA = (DirectoryEntry) fdA.getEntry(dirAA.getName());
- assertTrue(fdAA.hasEntry(eAA.getName()));
- }
-
- @Test
- void testNullDirectory() {
- assertThrows(IllegalArgumentException.class, () -> new FilteringDirectoryNode(null, null));
- }
-}
\ No newline at end of file
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestNotOLE2Exception.java b/src/testcases/org/apache/poi/poifs/filesystem/TestNotOLE2Exception.java
deleted file mode 100644
index 42d6534dc6..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestNotOLE2Exception.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.poifs.filesystem;
-
-import static org.apache.poi.POITestCase.assertContains;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.hssf.OldExcelFormatException;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test that POIFS complains when given older non-OLE2
- * formats. See also {@link TestOfficeXMLException} for OOXML
- * checks
- */
-class TestNotOLE2Exception {
- private static InputStream openXLSSampleStream(String sampleFileName) {
- return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
- }
- private static InputStream openDOCSampleStream(String sampleFileName) {
- return POIDataSamples.getDocumentInstance().openResourceAsStream(sampleFileName);
- }
-
- @Test
- void testRawXMLException() throws IOException {
- try (InputStream in = openXLSSampleStream("SampleSS.xml")) {
- NotOLE2FileException e = assertThrows(NotOLE2FileException.class, () -> new POIFSFileSystem(in));
- assertContains(e.getMessage(), "The supplied data appears to be a raw XML file");
- assertContains(e.getMessage(), "Formats such as Office 2003 XML");
- }
- }
-
- @Test
- void testMSWriteException() throws IOException {
- try (InputStream in = openDOCSampleStream("MSWriteOld.wri")) {
- NotOLE2FileException e = assertThrows(NotOLE2FileException.class, () -> new POIFSFileSystem(in));
- assertContains(e.getMessage(), "The supplied data appears to be in the old MS Write");
- assertContains(e.getMessage(), "doesn't currently support");
- }
- }
-
- @Test
- void testBiff3Exception() throws IOException {
- try (InputStream in = openXLSSampleStream("testEXCEL_3.xls")) {
- OldExcelFormatException e = assertThrows(OldExcelFormatException.class, () -> new POIFSFileSystem(in));
- assertContains(e.getMessage(), "The supplied data appears to be in BIFF3 format");
- assertContains(e.getMessage(), "try OldExcelExtractor");
- }
- }
-
- @Test
- void testBiff4Exception() throws IOException {
- try (InputStream in = openXLSSampleStream("testEXCEL_4.xls")) {
- OldExcelFormatException e = assertThrows(OldExcelFormatException.class, () -> new POIFSFileSystem(in));
- assertContains(e.getMessage(), "The supplied data appears to be in BIFF4 format");
- assertContains(e.getMessage(), "try OldExcelExtractor");
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java b/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java
deleted file mode 100644
index 8e4dd48298..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-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.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test that POIFS complains when given an Office 2003 XML
- * of Office Open XML (OOXML, 2007+) document
- */
-class TestOfficeXMLException {
-
- private static InputStream openSampleStream(String sampleFileName) {
- return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
- }
-
- @Test
- void testOOXMLException() throws IOException {
- try (InputStream in = openSampleStream("sample.xlsx")) {
- OfficeXmlFileException ex = assertThrows(OfficeXmlFileException.class, () -> new POIFSFileSystem(in));
- assertTrue(ex.getMessage().contains("You are calling the part of POI that deals with OLE2 Office Documents"));
- }
- }
-
- @Test
- void test2003XMLException() throws IOException {
- try (InputStream in = openSampleStream("SampleSS.xml")) {
- NotOLE2FileException ex = assertThrows(NotOLE2FileException.class, () -> new POIFSFileSystem(in));
- assertTrue(ex.getMessage().contains("The supplied data appears to be a raw XML file"));
- }
- }
-
- @Test
- void testDetectAsPOIFS() throws IOException {
- // ooxml file isn't
- confirmIsPOIFS("SampleSS.xlsx", FileMagic.OOXML);
-
- // 2003 xml file isn't
- confirmIsPOIFS("SampleSS.xml", FileMagic.XML);
-
- // xls file is
- confirmIsPOIFS("SampleSS.xls", FileMagic.OLE2);
-
- // older biff formats aren't
- confirmIsPOIFS("testEXCEL_3.xls", FileMagic.BIFF3);
- confirmIsPOIFS("testEXCEL_4.xls", FileMagic.BIFF4);
-
- // newer excel formats are
- confirmIsPOIFS("testEXCEL_5.xls", FileMagic.OLE2);
- confirmIsPOIFS("testEXCEL_95.xls", FileMagic.OLE2);
-
- // text file isn't
- confirmIsPOIFS("SampleSS.txt", FileMagic.UNKNOWN);
- }
-
- private void confirmIsPOIFS(String sampleFileName, FileMagic expected) throws IOException {
- final File file = HSSFTestDataSamples.getSampleFile(sampleFileName);
- assertEquals(expected, FileMagic.valueOf(file));
- }
-
- @Test
- void testFileCorruption() throws Exception {
-
- // create test InputStream
- byte[] testData = {1, 2, 3};
- InputStream testInput = new ByteArrayInputStream(testData);
-
- // detect header
- InputStream in = FileMagic.prepareToCheckMagic(testInput);
-
- assertNotEquals(FileMagic.OLE2, FileMagic.valueOf(in));
-
- // check if InputStream is still intact
- byte[] test = new byte[3];
- assertEquals(3, in.read(test));
- assertArrayEquals(testData, test);
- assertEquals(-1, in.read());
- }
-
-
- @Test
- void testFileCorruptionOPOIFS() throws Exception {
-
- // create test InputStream
- byte[] testData = {(byte) 1, (byte) 2, (byte) 3};
- InputStream testInput = new ByteArrayInputStream(testData);
-
- // detect header
- InputStream in = FileMagic.prepareToCheckMagic(testInput);
- assertNotEquals(FileMagic.OLE2, FileMagic.valueOf(in));
- assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf(in));
-
- // check if InputStream is still intact
- byte[] test = new byte[3];
- assertEquals(3, in.read(test));
- assertArrayEquals(testData, test);
- assertEquals(-1, in.read());
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java b/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java
deleted file mode 100644
index 6becf23aa1..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.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.poifs.filesystem;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.IsEqual.equalTo;
-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.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.RecordFormatException;
-import org.junit.jupiter.api.Test;
-
-class TestOle10Native {
- private static final POIDataSamples dataSamples = POIDataSamples.getPOIFSInstance();
-
- @Test
- void testOleNative() throws IOException, Ole10NativeException {
- POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("oleObject1.bin"));
-
- Ole10Native ole = Ole10Native.createFromEmbeddedOleObject(fs);
-
- assertEquals("File1.svg", ole.getLabel());
- assertEquals("D:\\Documents and Settings\\rsc\\My Documents\\file1.svg", ole.getCommand());
- }
-
- @Test
- void testFiles() throws IOException, Ole10NativeException {
- File[] files = {
- // bug 51891
- POIDataSamples.getPOIFSInstance().getFile("multimedia.doc"),
- // tika bug 1072
- POIDataSamples.getPOIFSInstance().getFile("20-Force-on-a-current-S00.doc"),
- // other files containing ole10native records ...
- POIDataSamples.getDocumentInstance().getFile("Bug53380_3.doc"),
- POIDataSamples.getDocumentInstance().getFile("Bug47731.doc")
- };
-
- for (File f : files) {
- POIFSFileSystem fs = new POIFSFileSystem(f, true);
- List entries = new ArrayList<>();
- findOle10(entries, fs.getRoot(), "/");
-
- for (Entry e : entries) {
- ByteArrayOutputStream bosExp = new ByteArrayOutputStream();
- InputStream is = ((DirectoryNode)e.getParent()).createDocumentInputStream(e);
- IOUtils.copy(is,bosExp);
- is.close();
-
- Ole10Native ole = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)e.getParent());
-
- ByteArrayOutputStream bosAct = new ByteArrayOutputStream();
- ole.writeOut(bosAct);
-
- assertThat(bosExp.toByteArray(), equalTo(bosAct.toByteArray()));
- }
-
- fs.close();
- }
- }
-
- private void findOle10(List entries, DirectoryNode dn, String path) {
- Iterator iter = dn.getEntries();
- while (iter.hasNext()) {
- Entry e = iter.next();
- if (Ole10Native.OLE10_NATIVE.equals(e.getName())) {
- if (entries != null) entries.add(e);
- // System.out.println(filename+" : "+path);
- } else if (e.isDirectoryEntry()) {
- findOle10(entries, (DirectoryNode)e, path+e.getName()+"/");
- }
- }
- }
-
- @Test
- void testOleNativeOOM() throws IOException {
- try (POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("60256.bin"))) {
- RecordFormatException ex = assertThrows(
- RecordFormatException.class,
- () -> Ole10Native.createFromEmbeddedOleObject(fs)
- );
- assertTrue(ex.getMessage().contains("Tried to allocate"));
- }
- }
-
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java
deleted file mode 100644
index 94d8e73e9c..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.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.poifs.filesystem;
-
-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.assertThrows;
-
-import java.util.Arrays;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test POIFSDocumentPath functionality
- */
-final class TestPOIFSDocumentPath {
-
-
- /**
- * Test default constructor
- */
- @Test
- void testDefaultConstructor() {
- POIFSDocumentPath path = new POIFSDocumentPath();
-
- assertEquals(0, path.length());
- }
-
- /**
- * Test full path constructor
- */
- @Test
- void testFullPathConstructor() {
- String[] components = {"foo", "bar", "foobar", "fubar"};
-
- for (int j = 0; j < components.length; j++) {
- String[] params = Arrays.copyOf(components, j);
- POIFSDocumentPath path = new POIFSDocumentPath(params);
-
- assertEquals(j, path.length());
- for (int k = 0; k < j; k++) {
- assertEquals(components[ k ], path.getComponent(k));
- }
- if (j == 0) {
- assertNull(path.getParent());
- } else {
- POIFSDocumentPath parent = path.getParent();
-
- assertNotNull(parent);
- assertEquals(j - 1, parent.length());
- for (int k = 0; k < j - 1; k++) {
- assertEquals(components[ k ], parent.getComponent(k));
- }
- }
- }
-
- // test weird variants
- assertEquals(0, new POIFSDocumentPath(null).length());
- assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(new String[]{"fu", ""}));
- assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(new String[]{"fu", null}));
- }
-
- /**
- * Test relative path constructor
- */
- @Test
- void testRelativePathConstructor() {
- String[] initialComponents = {"a", "b", "c"};
-
- for (int n = 0; n < initialComponents.length; n++) {
- String[] initialParams = Arrays.copyOf(initialComponents, n);
- POIFSDocumentPath base = new POIFSDocumentPath(initialParams);
- String[] components = {"foo", "bar", "foobar", "fubar"};
-
- for (int j = 0; j < components.length; j++) {
- String[] params = Arrays.copyOf(components, j);
- POIFSDocumentPath path = new POIFSDocumentPath(base, params);
-
- assertEquals(j + n, path.length());
- for (int k = 0; k < n; k++) {
- assertEquals(initialComponents[ k ], path.getComponent(k));
- }
- for (int k = 0; k < j; k++) {
- assertEquals(components[ k ], path.getComponent(k + n));
- }
- if ((j + n) == 0) {
- assertNull(path.getParent());
- } else {
- POIFSDocumentPath parent = path.getParent();
-
- assertNotNull(parent);
- assertEquals(j + n - 1, parent.length());
- for (int k = 0; k < (j + n - 1); k++) {
- assertEquals(path.getComponent(k), parent.getComponent(k));
- }
- }
- }
-
- // Test weird variants
-
- // This one is allowed, even if it's really odd
- assertEquals(n, new POIFSDocumentPath(base, null).length());
- new POIFSDocumentPath(base, new String[]{"fu", ""});
-
- // This one is allowed too
- new POIFSDocumentPath(base, new String[]{"", "fu"});
-
- // This one shouldn't be allowed
- assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(base, new String[]{"fu", null}));
-
- // Ditto
- assertThrows(IllegalArgumentException.class, () -> new POIFSDocumentPath(base, new String[]{null, "fu"}));
- }
- }
-
- /**
- * test equality
- */
- @Test
- void testEquality() {
- POIFSDocumentPath a1 = new POIFSDocumentPath();
- POIFSDocumentPath a2 = new POIFSDocumentPath(null);
- POIFSDocumentPath a3 = new POIFSDocumentPath(new String[ 0 ]);
- POIFSDocumentPath a4 = new POIFSDocumentPath(a1, null);
- POIFSDocumentPath a5 = new POIFSDocumentPath(a1, new String[ 0 ]);
-
- POIFSDocumentPath[] paths = {a1, a2, a3, a4, a5};
-
- for (int j = 0; j < paths.length; j++) {
- for (int k = 0; k < paths.length; k++) {
- assertEquals(paths[ j ], paths[ k ], j + "<>" + k);
- }
- }
- a2 = new POIFSDocumentPath(a1, new String[]{"foo"});
- a3 = new POIFSDocumentPath(a2, new String[]{"bar"});
- a4 = new POIFSDocumentPath(a3, new String[]{"fubar"});
- a5 = new POIFSDocumentPath(a4, new String[]{"foobar"});
- POIFSDocumentPath[] builtUpPaths =
- {
- a1, a2, a3, a4, a5
- };
- POIFSDocumentPath[] fullPaths = {
- new POIFSDocumentPath(), new POIFSDocumentPath(new String[]{"foo"}),
- new POIFSDocumentPath(new String[]{"foo", "bar"}),
- new POIFSDocumentPath(new String[]{"foo", "bar", "fubar"}),
- new POIFSDocumentPath(new String[]{"foo", "bar", "fubar", "foobar"})
- };
-
- for (int k = 0; k < builtUpPaths.length; k++) {
- for (int j = 0; j < fullPaths.length; j++) {
- if (k == j) {
- assertEquals(fullPaths[ j ], builtUpPaths[ k ], j + "<>" + k);
- } else {
- assertNotEquals(fullPaths[j], builtUpPaths[k]);
- }
- }
- }
- POIFSDocumentPath[] badPaths = {
- new POIFSDocumentPath(new String[]{"_foo"}),
- new POIFSDocumentPath(new String[]{"foo", "_bar"}),
- new POIFSDocumentPath(new String[]{"foo", "bar", "_fubar"}),
- new POIFSDocumentPath(new String[]{"foo", "bar", "fubar", "_foobar"})
- };
-
- for (int k = 0; k < builtUpPaths.length; k++)
- {
- for (POIFSDocumentPath badPath : badPaths) {
- assertNotEquals(fullPaths[k], badPath);
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java
deleted file mode 100644
index c644fb1c60..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java
+++ /dev/null
@@ -1,350 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-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.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
-import java.util.HashMap;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hpsf.NoPropertySetStreamException;
-import org.apache.poi.hpsf.Property;
-import org.apache.poi.hpsf.PropertySet;
-import org.apache.poi.hpsf.Section;
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.poifs.common.POIFSBigBlockSize;
-import org.apache.poi.poifs.common.POIFSConstants;
-import org.apache.poi.poifs.storage.BATBlock;
-import org.apache.poi.poifs.storage.HeaderBlock;
-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;
-import org.junit.jupiter.params.provider.ValueSource;
-
-/**
- * Tests for the older OPOIFS-based POIFSFileSystem
- */
-final class TestPOIFSFileSystem {
- private final POIDataSamples _samples = POIDataSamples.getPOIFSInstance();
-
- /**
- * Mock exception used to ensure correct error handling
- */
- private static final class MyEx extends RuntimeException {
- MyEx() {
- // no fields to initialise
- }
- }
- /**
- * Helps facilitate testing. Keeps track of whether close() was called.
- * Also can throw an exception at a specific point in the stream.
- */
- private static final class TestIS extends InputStream {
-
- private final InputStream _is;
- private final int _failIndex;
- private int _currentIx;
- private boolean _isClosed;
-
- TestIS(InputStream is, int failIndex) {
- _is = is;
- _failIndex = failIndex;
- _currentIx = 0;
- _isClosed = false;
- }
-
- @Override
- public int read() throws IOException {
- int result = _is.read();
- if(result >=0) {
- checkRead(1);
- }
- return result;
- }
- @Override
- public int read(byte[] b, int off, int len) throws IOException {
- int result = _is.read(b, off, len);
- checkRead(result);
- return result;
- }
-
- private void checkRead(int nBytes) {
- _currentIx += nBytes;
- if(_failIndex > 0 && _currentIx > _failIndex) {
- throw new MyEx();
- }
- }
- @Override
- public void close() throws IOException {
- _isClosed = true;
- _is.close();
- }
- boolean isClosed() {
- return _isClosed;
- }
- }
-
- /**
- * Test for undesired behaviour observable as of svn revision 618865 (5-Feb-2008).
- * POIFSFileSystem was not closing the input stream.
- */
- @Test
- void testAlwaysClose() throws IOException {
- // Normal case - read until EOF and close
- try (TestIS testIS = new TestIS(openSampleStream("13224.xls"), -1);
- POIFSFileSystem ignored = new POIFSFileSystem(testIS)){
- assertTrue(testIS.isClosed(), "input stream was not closed");
- }
-
- // intended to crash after reading 10000 bytes
- try (TestIS testIS = new TestIS(openSampleStream("13224.xls"), 10000)){
- assertThrows(MyEx.class, () -> new POIFSFileSystem(testIS));
- // but still should close
- assertTrue(testIS.isClosed(), "input stream was not closed");
- }
- }
-
- /**
- * Test for bug # 48898 - problem opening an OLE2
- * file where the last block is short (i.e. not a full
- * multiple of 512 bytes)
- *
- * As yet, this problem remains. One school of thought is
- * not not issue an EOF when we discover the last block
- * is short, but this seems a bit wrong.
- * The other is to fix the handling of the last block in
- * POIFS, since it seems to be slight wrong
- */
- @ParameterizedTest
- @CsvSource({ "ShortLastBlock.qwp, 1303681", "ShortLastBlock.wps, 140787" })
- void testShortLastBlock(String file, int size) throws Exception {
- // Open the file up
- try (POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream(file))) {
-
- // Write it into a temp output array
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- fs.writeFilesystem(baos);
-
- // Check sizes
- assertEquals(size, baos.size());
- }
- }
-
- /**
- * Check that we do the right thing when the list of which
- * sectors are BAT blocks points off the list of
- * sectors that exist in the file.
- */
- @Test
- void testFATandDIFATsectors() throws Exception {
- try (InputStream stream = _samples.openResourceAsStream("ReferencesInvalidSectors.mpp")) {
- IndexOutOfBoundsException ex = assertThrows(
- IndexOutOfBoundsException.class,
- () -> new POIFSFileSystem(stream),
- "File is corrupt and shouldn't have been opened"
- );
- assertTrue(ex.getMessage().contains("Block 1148 not found"));
- }
- }
-
- /**
- * Tests that we can write and read a file that contains XBATs
- * as well as regular BATs.
- * However, because a file needs to be at least 6.875mb big
- * to have an XBAT in it, we don't have a test one. So, generate it.
- */
- @Test
- void testBATandXBAT() throws Exception {
- byte[] hugeStream = new byte[8*1024*1024];
- POIFSFileSystem fs = new POIFSFileSystem();
- fs.getRoot().createDocument(
- "BIG", new ByteArrayInputStream(hugeStream)
- );
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- fs.writeFilesystem(baos);
- byte[] fsData = baos.toByteArray();
-
-
- // Check the header was written properly
- InputStream inp = new ByteArrayInputStream(fsData);
- HeaderBlock header = new HeaderBlock(inp);
- assertEquals(109+21, header.getBATCount());
- assertEquals(1, header.getXBATCount());
-
-
- // We should have 21 BATs in the XBAT
- ByteBuffer xbatData = ByteBuffer.allocate(512);
- xbatData.put(fsData, (1+header.getXBATIndex())*512, 512);
- xbatData.position(0);
- BATBlock xbat = BATBlock.createBATBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, xbatData);
- for(int i=0; i<21; i++) {
- assertTrue(xbat.getValueAt(i) != POIFSConstants.UNUSED_BLOCK);
- }
- for(int i=21; i<127; i++) {
- assertEquals(POIFSConstants.UNUSED_BLOCK, xbat.getValueAt(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, xbat.getValueAt(127));
-
-
- // Now load it and check
- fs = new POIFSFileSystem(
- new ByteArrayInputStream(fsData)
- );
-
- DirectoryNode root = fs.getRoot();
- assertEquals(1, root.getEntryCount());
- DocumentNode big = (DocumentNode)root.getEntry("BIG");
- assertEquals(hugeStream.length, big.getSize());
- }
-
- /**
- * Most OLE2 files use 512byte blocks. However, a small number
- * use 4k blocks. Check that we can open these.
- */
- @Test
- void test4KBlocks() throws Exception {
- POIDataSamples _samples = POIDataSamples.getPOIFSInstance();
- try (InputStream inp = _samples.openResourceAsStream("BlockSize4096.zvi")) {
- // First up, check that we can process the header properly
- HeaderBlock header_block = new HeaderBlock(inp);
- POIFSBigBlockSize bigBlockSize = header_block.getBigBlockSize();
- assertEquals(4096, bigBlockSize.getBigBlockSize());
-
- // Check the fat info looks sane
- assertEquals(1, header_block.getBATArray().length);
- assertEquals(1, header_block.getBATCount());
- assertEquals(0, header_block.getXBATCount());
-
- // Now try and open properly
- POIFSFileSystem fs = new POIFSFileSystem(
- _samples.openResourceAsStream("BlockSize4096.zvi"));
- assertTrue(fs.getRoot().getEntryCount() > 3);
-
- // Check we can get at all the contents
- checkAllDirectoryContents(fs.getRoot());
-
- // Finally, check we can do a similar 512byte one too
- fs = new POIFSFileSystem(
- _samples.openResourceAsStream("BlockSize512.zvi"));
- assertTrue(fs.getRoot().getEntryCount() > 3);
- checkAllDirectoryContents(fs.getRoot());
- }
- }
- private void checkAllDirectoryContents(DirectoryEntry dir) throws IOException {
- for(Entry entry : dir) {
- if(entry instanceof DirectoryEntry) {
- checkAllDirectoryContents((DirectoryEntry)entry);
- } else {
- DocumentNode doc = (DocumentNode) entry;
- try (DocumentInputStream dis = new DocumentInputStream(doc)) {
- IOUtils.toByteArray(dis);
- }
- }
- }
- }
-
- @SuppressWarnings("SameParameterValue")
- private static InputStream openSampleStream(String sampleFileName) {
- return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
- }
-
- @Test
- public void fileMagics() {
- for (FileMagic fm : FileMagic.values()) {
- if (fm == FileMagic.UNKNOWN) {
- continue;
- }
- for (byte[] b : fm.magic) {
- assertEquals(fm, FileMagic.valueOf(b));
- }
- }
-
- assertEquals(FileMagic.UNKNOWN, FileMagic.valueOf("foobaa".getBytes(UTF_8)));
- }
-
- @Test
- void test64322() throws NoPropertySetStreamException, IOException {
- try (POIFSFileSystem poiFS = new POIFSFileSystem(_samples.getFile("64322.ole2"))) {
- int count = recurseDir(poiFS.getRoot());
-
- assertEquals(1285, count, "Expecting a fixed number of entries being found in the test-document");
- }
- }
-
- @Test
- void test64322a() throws NoPropertySetStreamException, IOException {
- try (POIFSFileSystem poiFS = new POIFSFileSystem(_samples.openResourceAsStream("64322.ole2"))) {
- int count = recurseDir(poiFS.getRoot());
-
- assertEquals(1285, count, "Expecting a fixed number of entries being found in the test-document");
- }
- }
-
- private static int recurseDir(DirectoryEntry dir) throws IOException, NoPropertySetStreamException {
- int count = 0;
- for (Entry entry : dir) {
- count++;
- if (entry instanceof DirectoryEntry) {
- count += recurseDir((DirectoryEntry) entry);
- }
- if (entry instanceof DocumentEntry) {
- DocumentEntry de = (DocumentEntry) entry;
- HashMap props = new HashMap<>();
- try (DocumentInputStream dis = new DocumentInputStream(de)) {
- props.put("name", de.getName());
-
- if (PropertySet.isPropertySetStream(dis)) {
- dis.mark(10000000);
- PropertySet ps = null;
- try {
- ps = new PropertySet(dis);
-
- } catch (UnsupportedEncodingException e) {
- // ignore
- }
- if (ps != null) {
- for (Section section : ps.getSections()) {
- for (Property p : section.getProperties()) {
- String prop = section.getDictionary() != null
- ? section.getDictionary().get(p.getID())
- : String.valueOf(p.getID());
- if (p.getValue() != null)
- props.put("property_" + prop, p.getValue().toString());
- }
- }
- }
- dis.reset();
- }
- }
- assertTrue(props.size() > 0);
- }
- }
- return count;
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSMiniStore.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSMiniStore.java
deleted file mode 100644
index fcc1e4bcf1..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSMiniStore.java
+++ /dev/null
@@ -1,473 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-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.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.nio.ByteBuffer;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.poifs.common.POIFSConstants;
-import org.apache.poi.util.IOUtils;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for the Mini Store in the NIO POIFS
- */
-@SuppressWarnings("CatchMayIgnoreException")
-final class TestPOIFSMiniStore {
- private static final POIDataSamples _inst = POIDataSamples.getPOIFSInstance();
-
- /**
- * Check that for a given mini block, we can correctly figure
- * out what the next one is
- */
- @Test
- void testNextBlock() throws Exception {
- // It's the same on 512 byte and 4096 byte block files!
- POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- POIFSFileSystem fsC = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- POIFSFileSystem fsD = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB, fsC, fsD}) {
- POIFSMiniStore ministore = fs.getMiniStore();
-
- // 0 -> 51 is one stream
- for (int i = 0; i < 50; i++) {
- assertEquals(i + 1, ministore.getNextBlock(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50));
-
- // 51 -> 103 is the next
- for (int i = 51; i < 103; i++) {
- assertEquals(i + 1, ministore.getNextBlock(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(103));
-
- // Then there are 3 one block ones
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(104));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(105));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(106));
-
- // 107 -> 154 is the next
- for (int i = 107; i < 154; i++) {
- assertEquals(i + 1, ministore.getNextBlock(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(154));
-
- // 155 -> 160 is the next
- for (int i = 155; i < 160; i++) {
- assertEquals(i + 1, ministore.getNextBlock(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(160));
-
- // 161 -> 166 is the next
- for (int i = 161; i < 166; i++) {
- assertEquals(i + 1, ministore.getNextBlock(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(166));
-
- // 167 -> 172 is the next
- for (int i = 167; i < 172; i++) {
- assertEquals(i + 1, ministore.getNextBlock(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(172));
-
- // Now some short ones
- assertEquals(174, ministore.getNextBlock(173));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(174));
-
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(175));
-
- assertEquals(177, ministore.getNextBlock(176));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(177));
-
- assertEquals(179, ministore.getNextBlock(178));
- assertEquals(180, ministore.getNextBlock(179));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180));
-
- // 181 onwards is free
- for (int i = 181; i < fs.getBigBlockSizeDetails().getBATEntriesPerBlock(); i++) {
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i));
- }
- }
- fsD.close();
- fsC.close();
- fsB.close();
- fsA.close();
- }
-
- /**
- * Check we get the right data back for each block
- */
- @Test
- void testGetBlock() throws Exception {
- // It's the same on 512 byte and 4096 byte block files!
- POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- POIFSFileSystem fsC = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- POIFSFileSystem fsD = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB, fsC, fsD}) {
- // Mini stream should be at big block zero
- assertEquals(0, fs._get_property_table().getRoot().getStartBlock());
-
- // Grab the ministore
- POIFSMiniStore ministore = fs.getMiniStore();
- ByteBuffer b;
-
- // Runs from the start of the data section in 64 byte chungs
- b = ministore.getBlockAt(0);
- assertEquals((byte) 0x9e, b.get());
- assertEquals((byte) 0x75, b.get());
- assertEquals((byte) 0x97, b.get());
- assertEquals((byte) 0xf6, b.get());
- assertEquals((byte) 0xff, b.get());
- assertEquals((byte) 0x21, b.get());
- assertEquals((byte) 0xd2, b.get());
- assertEquals((byte) 0x11, b.get());
-
- // And the next block
- b = ministore.getBlockAt(1);
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x03, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x12, b.get());
- assertEquals((byte) 0x02, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
-
- // Check the last data block
- b = ministore.getBlockAt(180);
- assertEquals((byte) 0x30, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x80, b.get());
-
- // And the rest until the end of the big block is zeros
- for (int i = 181; i < 184; i++) {
- b = ministore.getBlockAt(i);
- assertEquals((byte) 0, b.get());
- assertEquals((byte) 0, b.get());
- assertEquals((byte) 0, b.get());
- assertEquals((byte) 0, b.get());
- assertEquals((byte) 0, b.get());
- assertEquals((byte) 0, b.get());
- assertEquals((byte) 0, b.get());
- assertEquals((byte) 0, b.get());
- }
- }
- fsD.close();
- fsC.close();
- fsB.close();
- fsA.close();
- }
-
- /**
- * Ask for free blocks where there are some already
- * to be had from the SFAT
- */
- @Test
- void testGetFreeBlockWithSpare() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- POIFSMiniStore ministore = fs.getMiniStore();
-
- // Our 2nd SBAT block has spares
- assertFalse(ministore.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- assertTrue(ministore.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
-
- // First free one at 181
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(181));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(182));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(183));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(184));
-
- // Ask, will get 181
- assertEquals(181, ministore.getFreeBlock());
-
- // Ask again, will still get 181 as not written to
- assertEquals(181, ministore.getFreeBlock());
-
- // Allocate it, then ask again
- ministore.setNextBlock(181, POIFSConstants.END_OF_CHAIN);
- assertEquals(182, ministore.getFreeBlock());
-
- fs.close();
- }
-
- /**
- * Ask for free blocks where no free ones exist, and so the
- * stream needs to be extended and another SBAT added
- */
- @Test
- void testGetFreeBlockWithNoneSpare() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- POIFSMiniStore ministore = fs.getMiniStore();
-
- // We've spare ones from 181 to 255
- for (int i = 181; i < 256; i++) {
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i));
- }
-
- // Check our SBAT free stuff is correct
- assertFalse(ministore.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- assertTrue(ministore.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
-
- // Allocate all the spare ones
- for (int i = 181; i < 256; i++) {
- ministore.setNextBlock(i, POIFSConstants.END_OF_CHAIN);
- }
-
- // SBAT are now full, but there's only the two
- assertFalse(ministore.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- assertFalse(ministore.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> ministore.getBATBlockAndIndex(256), "Should only be two SBATs");
-
- // Now ask for a free one, will need to extend the SBAT chain
- assertEquals(256, ministore.getFreeBlock());
-
- assertFalse(ministore.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- assertFalse(ministore.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
- assertTrue(ministore.getBATBlockAndIndex(256).getBlock().hasFreeSectors());
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(254)); // 2nd SBAT
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(255)); // 2nd SBAT
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(256)); // 3rd SBAT
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(257)); // 3rd SBAT
-
- fs.close();
- }
-
- /**
- * Test that we will extend the underlying chain of
- * big blocks that make up the ministream as needed
- */
- @Test
- void testCreateBlockIfNeeded() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- POIFSMiniStore ministore = fs.getMiniStore();
-
- // 178 -> 179 -> 180, 181+ is free
- assertEquals(179, ministore.getNextBlock(178));
- assertEquals(180, ministore.getNextBlock(179));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180));
- for (int i = 181; i < 256; i++) {
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i));
- }
-
- // However, the ministore data only covers blocks to 183
- for (int i = 0; i <= 183; i++) {
- ministore.getBlockAt(i);
- }
- assertThrows(NoSuchElementException.class, () -> ministore.getBlockAt(184), "No block at 184");
-
- // The ministore itself is made up of 23 big blocks
- Iterator it = new POIFSStream(fs, fs.getRoot().getProperty().getStartBlock()).getBlockIterator();
- int count = 0;
- while (it.hasNext()) {
- count++;
- it.next();
- }
- assertEquals(23, count);
-
- // Ask it to get block 184 with creating, it will do
- ministore.createBlockIfNeeded(184);
-
- // The ministore should be one big block bigger now
- it = new POIFSStream(fs, fs.getRoot().getProperty().getStartBlock()).getBlockIterator();
- count = 0;
- while (it.hasNext()) {
- count++;
- it.next();
- }
- assertEquals(24, count);
-
- // The mini block block counts now run to 191
- for (int i = 0; i <= 191; i++) {
- ministore.getBlockAt(i);
- }
-
- assertThrows(NoSuchElementException.class, () -> ministore.getBlockAt(192), "No block at 192");
-
- // Now try writing through to 192, check that the SBAT and blocks are there
- byte[] data = new byte[15 * 64];
- POIFSStream stream = new POIFSStream(ministore, 178);
- stream.updateContents(data);
-
- // Check now
- assertEquals(179, ministore.getNextBlock(178));
- assertEquals(180, ministore.getNextBlock(179));
- assertEquals(181, ministore.getNextBlock(180));
- assertEquals(182, ministore.getNextBlock(181));
- assertEquals(183, ministore.getNextBlock(182));
- assertEquals(184, ministore.getNextBlock(183));
- assertEquals(185, ministore.getNextBlock(184));
- assertEquals(186, ministore.getNextBlock(185));
- assertEquals(187, ministore.getNextBlock(186));
- assertEquals(188, ministore.getNextBlock(187));
- assertEquals(189, ministore.getNextBlock(188));
- assertEquals(190, ministore.getNextBlock(189));
- assertEquals(191, ministore.getNextBlock(190));
- assertEquals(192, ministore.getNextBlock(191));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(192));
- for (int i = 193; i < 256; i++) {
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i));
- }
-
- fs.close();
- }
-
- @Test
- void testCreateMiniStoreFirst() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem();
- POIFSMiniStore ministore = fs.getMiniStore();
- DocumentInputStream dis;
- DocumentEntry entry;
-
- // Initially has Properties + BAT but nothing else
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(2));
- // Ministore has no blocks, so can't iterate until used
- try {
- ministore.getNextBlock(0);
- } catch (IndexOutOfBoundsException e) {
- }
-
- // Write a very small new document, will populate the ministore for us
- byte[] data = new byte[8];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i + 42);
- }
- fs.getRoot().createDocument("mini", new ByteArrayInputStream(data));
-
- // Should now have a mini-fat and a mini-stream
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(3));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(4));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(0));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(1));
-
- // Re-fetch the mini store, and add it a second time
- ministore = fs.getMiniStore();
- fs.getRoot().createDocument("mini2", new ByteArrayInputStream(data));
-
- // Main unchanged, ministore has a second
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(3));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(4));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(0));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(1));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(2));
-
- // Check the data is unchanged and the right length
- entry = (DocumentEntry) fs.getRoot().getEntry("mini");
- assertEquals(data.length, entry.getSize());
- byte[] rdata = new byte[data.length];
- dis = new DocumentInputStream(entry);
- IOUtils.readFully(dis, rdata);
- assertArrayEquals(data, rdata);
- dis.close();
-
- entry = (DocumentEntry) fs.getRoot().getEntry("mini2");
- assertEquals(data.length, entry.getSize());
- rdata = new byte[data.length];
- dis = new DocumentInputStream(entry);
- IOUtils.readFully(dis, rdata);
- assertArrayEquals(data, rdata);
- dis.close();
-
- // Done
- fs.close();
- }
-
- @Test
- void testMultiBlockStream() throws Exception {
- byte[] data1B = new byte[63];
- byte[] data2B = new byte[64 + 14];
- for (int i = 0; i < data1B.length; i++) {
- data1B[i] = (byte) (i + 2);
- }
- for (int i = 0; i < data2B.length; i++) {
- data2B[i] = (byte) (i + 4);
- }
-
- // New filesystem and store to use
- POIFSFileSystem fs = new POIFSFileSystem();
-
- // Initially has Properties + BAT but nothing else
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(2));
-
- // Store the 2 block one, should use 2 mini blocks, and request
- // the use of 2 big blocks
- POIFSMiniStore ministore = fs.getMiniStore();
- fs.getRoot().createDocument("mini2", new ByteArrayInputStream(data2B));
-
- // Check
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); // SBAT
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(3)); // Mini
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(4));
-
- // First 2 Mini blocks will be used
- assertEquals(2, ministore.getFreeBlock());
-
- // Add one more mini-stream, and check
- fs.getRoot().createDocument("mini1", new ByteArrayInputStream(data1B));
-
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); // SBAT
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(3)); // Mini
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(4));
-
- // One more mini-block will be used
- assertEquals(3, ministore.getFreeBlock());
-
- // Check the contents too
- byte[] r1 = new byte[data1B.length];
- DocumentInputStream dis = fs.createDocumentInputStream("mini1");
- IOUtils.readFully(dis, r1);
- dis.close();
- assertArrayEquals(data1B, r1);
-
- byte[] r2 = new byte[data2B.length];
- dis = fs.createDocumentInputStream("mini2");
- IOUtils.readFully(dis, r2);
- dis.close();
- assertArrayEquals(data2B, r2);
- fs.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java
deleted file mode 100644
index 2a2a8122d1..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java
+++ /dev/null
@@ -1,2792 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.filesystem;
-
-import static org.hamcrest.CoreMatchers.hasItem;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.IsEqual.equalTo;
-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.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.nio.ByteBuffer;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hpsf.DocumentSummaryInformation;
-import org.apache.poi.hpsf.PropertySet;
-import org.apache.poi.hpsf.PropertySetFactory;
-import org.apache.poi.hpsf.SummaryInformation;
-import org.apache.poi.poifs.common.POIFSConstants;
-import org.apache.poi.poifs.property.DirectoryProperty;
-import org.apache.poi.poifs.property.Property;
-import org.apache.poi.poifs.property.PropertyTable;
-import org.apache.poi.poifs.property.RootProperty;
-import org.apache.poi.poifs.storage.BATBlock;
-import org.apache.poi.poifs.storage.HeaderBlock;
-import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.TempFile;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests {@link POIFSStream}
- */
-final class TestPOIFSStream {
- private static final POIDataSamples _inst = POIDataSamples.getPOIFSInstance();
-
- /**
- * Read a single block stream
- */
- @Test
- void testReadTinyStream() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
-
- // 98 is actually the last block in a two block stream...
- POIFSStream stream = new POIFSStream(fs, 98);
- Iterator i = stream.getBlockIterator();
- assertTrue(i.hasNext());
- ByteBuffer b = i.next();
- assertFalse(i.hasNext());
-
- // Check the contents
- assertEquals((byte) 0x81, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x82, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
-
- fs.close();
- }
-
- /**
- * Read a stream with only two blocks in it
- */
- @Test
- void testReadShortStream() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
-
- // 97 -> 98 -> end
- POIFSStream stream = new POIFSStream(fs, 97);
- Iterator i = stream.getBlockIterator();
- assertTrue(i.hasNext());
- ByteBuffer b97 = i.next();
- assertTrue(i.hasNext());
- ByteBuffer b98 = i.next();
- assertFalse(i.hasNext());
-
- // Check the contents of the 1st block
- assertEquals((byte) 0x01, b97.get());
- assertEquals((byte) 0x00, b97.get());
- assertEquals((byte) 0x00, b97.get());
- assertEquals((byte) 0x00, b97.get());
- assertEquals((byte) 0x02, b97.get());
- assertEquals((byte) 0x00, b97.get());
- assertEquals((byte) 0x00, b97.get());
- assertEquals((byte) 0x00, b97.get());
-
- // Check the contents of the 2nd block
- assertEquals((byte) 0x81, b98.get());
- assertEquals((byte) 0x00, b98.get());
- assertEquals((byte) 0x00, b98.get());
- assertEquals((byte) 0x00, b98.get());
- assertEquals((byte) 0x82, b98.get());
- assertEquals((byte) 0x00, b98.get());
- assertEquals((byte) 0x00, b98.get());
- assertEquals((byte) 0x00, b98.get());
-
- fs.close();
- }
-
- /**
- * Read a stream with many blocks
- */
- @Test
- void testReadLongerStream() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
-
- ByteBuffer b0 = null;
- ByteBuffer b1 = null;
- ByteBuffer b22 = null;
-
- // The stream at 0 has 23 blocks in it
- POIFSStream stream = new POIFSStream(fs, 0);
- Iterator i = stream.getBlockIterator();
- int count = 0;
- while (i.hasNext()) {
- ByteBuffer b = i.next();
- if (count == 0) {
- b0 = b;
- }
- if (count == 1) {
- b1 = b;
- }
- if (count == 22) {
- b22 = b;
- }
-
- count++;
- }
- assertEquals(23, count);
-
- // Check the contents
- // 1st block is at 0
- assertNotNull(b0);
- assertEquals((byte) 0x9e, b0.get());
- assertEquals((byte) 0x75, b0.get());
- assertEquals((byte) 0x97, b0.get());
- assertEquals((byte) 0xf6, b0.get());
-
- // 2nd block is at 1
- assertNotNull(b1);
- assertEquals((byte) 0x86, b1.get());
- assertEquals((byte) 0x09, b1.get());
- assertEquals((byte) 0x22, b1.get());
- assertEquals((byte) 0xfb, b1.get());
-
- // last block is at 89
- assertNotNull(b22);
- assertEquals((byte) 0xfe, b22.get());
- assertEquals((byte) 0xff, b22.get());
- assertEquals((byte) 0x00, b22.get());
- assertEquals((byte) 0x00, b22.get());
- assertEquals((byte) 0x05, b22.get());
- assertEquals((byte) 0x01, b22.get());
- assertEquals((byte) 0x02, b22.get());
- assertEquals((byte) 0x00, b22.get());
-
- fs.close();
- }
-
- /**
- * Read a stream with several blocks in a 4096 byte block file
- */
- @Test
- void testReadStream4096() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
-
- // 0 -> 1 -> 2 -> end
- POIFSStream stream = new POIFSStream(fs, 0);
- Iterator i = stream.getBlockIterator();
- assertTrue(i.hasNext());
- ByteBuffer b0 = i.next();
- assertTrue(i.hasNext());
- ByteBuffer b1 = i.next();
- assertTrue(i.hasNext());
- ByteBuffer b2 = i.next();
- assertFalse(i.hasNext());
-
- // Check the contents of the 1st block
- assertEquals((byte) 0x9E, b0.get());
- assertEquals((byte) 0x75, b0.get());
- assertEquals((byte) 0x97, b0.get());
- assertEquals((byte) 0xF6, b0.get());
- assertEquals((byte) 0xFF, b0.get());
- assertEquals((byte) 0x21, b0.get());
- assertEquals((byte) 0xD2, b0.get());
- assertEquals((byte) 0x11, b0.get());
-
- // Check the contents of the 2nd block
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x03, b1.get());
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x00, b1.get());
-
- // Check the contents of the 3rd block
- assertEquals((byte) 0x6D, b2.get());
- assertEquals((byte) 0x00, b2.get());
- assertEquals((byte) 0x00, b2.get());
- assertEquals((byte) 0x00, b2.get());
- assertEquals((byte) 0x03, b2.get());
- assertEquals((byte) 0x00, b2.get());
- assertEquals((byte) 0x46, b2.get());
- assertEquals((byte) 0x00, b2.get());
-
- fs.close();
- }
-
- /**
- * Craft a nasty file with a loop, and ensure we don't get stuck
- */
- @Test
- void testReadFailsOnLoop() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
-
- // Hack the FAT so that it goes 0->1->2->0
- fs.setNextBlock(0, 1);
- fs.setNextBlock(1, 2);
- fs.setNextBlock(2, 0);
-
- // Now try to read
- POIFSStream stream = new POIFSStream(fs, 0);
- Iterator i = stream.getBlockIterator();
- assertTrue(i.hasNext());
-
- // 1st read works
- i.next();
- assertTrue(i.hasNext());
-
- // 2nd read works
- i.next();
- assertTrue(i.hasNext());
-
- // 3rd read works
- i.next();
- assertTrue(i.hasNext());
-
- // 4th read blows up as it loops back to 0
- assertThrows(RuntimeException.class, i::next, "Loop should have been detected but wasn't!");
- assertTrue(i.hasNext());
-
- fs.close();
- }
-
- /**
- * Tests that we can load some streams that are
- * stored in the mini stream.
- */
- @Test
- void testReadMiniStreams() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- POIFSMiniStore ministore = fs.getMiniStore();
-
- // 178 -> 179 -> 180 -> end
- POIFSStream stream = new POIFSStream(ministore, 178);
- Iterator i = stream.getBlockIterator();
- assertTrue(i.hasNext());
- ByteBuffer b178 = i.next();
- assertTrue(i.hasNext());
- ByteBuffer b179 = i.next();
- assertTrue(i.hasNext());
- ByteBuffer b180 = i.next();
- assertFalse(i.hasNext());
-
- // Check the contents of the 1st block
- assertEquals((byte) 0xfe, b178.get());
- assertEquals((byte) 0xff, b178.get());
- assertEquals((byte) 0x00, b178.get());
- assertEquals((byte) 0x00, b178.get());
- assertEquals((byte) 0x05, b178.get());
- assertEquals((byte) 0x01, b178.get());
- assertEquals((byte) 0x02, b178.get());
- assertEquals((byte) 0x00, b178.get());
-
- // And the 2nd
- assertEquals((byte) 0x6c, b179.get());
- assertEquals((byte) 0x00, b179.get());
- assertEquals((byte) 0x00, b179.get());
- assertEquals((byte) 0x00, b179.get());
- assertEquals((byte) 0x28, b179.get());
- assertEquals((byte) 0x00, b179.get());
- assertEquals((byte) 0x00, b179.get());
- assertEquals((byte) 0x00, b179.get());
-
- // And the 3rd
- assertEquals((byte) 0x30, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x80, b180.get());
-
- fs.close();
- }
-
- /**
- * Writing the same amount of data as before
- */
- @Test
- void testReplaceStream() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
-
- byte[] data = new byte[512];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
- }
-
- // 98 is actually the last block in a two block stream...
- POIFSStream stream = new POIFSStream(fs, 98);
- stream.updateContents(data);
-
- // Check the reading of blocks
- Iterator it = stream.getBlockIterator();
- assertTrue(it.hasNext());
- ByteBuffer b = it.next();
- assertFalse(it.hasNext());
-
- // Now check the contents
- data = new byte[512];
- b.get(data);
- for (int i = 0; i < data.length; i++) {
- byte exp = (byte) (i % 256);
- assertEquals(exp, data[i]);
- }
-
- fs.close();
- }
-
- /**
- * Writes less data than before, some blocks will need
- * to be freed
- */
- @Test
- void testReplaceStreamWithLess() throws Exception {
- try (InputStream is = _inst.openResourceAsStream("BlockSize512.zvi");
- POIFSFileSystem fs = new POIFSFileSystem(is)) {
-
- byte[] data = new byte[512];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
- }
-
- // 97 -> 98 -> end
- assertEquals(98, fs.getNextBlock(97));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98));
-
- // Create a 2 block stream, will become a 1 block one
- POIFSStream stream = new POIFSStream(fs, 97);
- stream.updateContents(data);
-
- // 97 should now be the end, and 98 free
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(97));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(98));
-
- // Check the reading of blocks
- Iterator it = stream.getBlockIterator();
- assertTrue(it.hasNext());
- ByteBuffer b = it.next();
- assertFalse(it.hasNext());
-
- // Now check the contents
- data = new byte[512];
- b.get(data);
- for (int i = 0; i < data.length; i++) {
- byte exp = (byte) (i % 256);
- assertEquals(exp, data[i]);
- }
- }
- }
-
- /**
- * Writes more data than before, new blocks will be needed
- */
- @Test
- void testReplaceStreamWithMore() throws Exception {
- try (InputStream is = _inst.openResourceAsStream("BlockSize512.zvi");
- POIFSFileSystem fs = new POIFSFileSystem(is)) {
-
- byte[] data = new byte[512 * 3];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
- }
-
- // 97 -> 98 -> end
- assertEquals(98, fs.getNextBlock(97));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98));
-
- // 100 is our first free one
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
-
- // Create a 2 block stream, will become a 3 block one
- POIFSStream stream = new POIFSStream(fs, 97);
- stream.updateContents(data);
-
- // 97 -> 98 -> 100 -> end
- assertEquals(98, fs.getNextBlock(97));
- assertEquals(100, fs.getNextBlock(98));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
-
- // Check the reading of blocks
- Iterator it = stream.getBlockIterator();
- int count = 0;
- while (it.hasNext()) {
- ByteBuffer b = it.next();
- data = new byte[512];
- b.get(data);
- for (int i = 0; i < data.length; i++) {
- byte exp = (byte) (i % 256);
- assertEquals(exp, data[i]);
- }
- count++;
- }
- assertEquals(3, count);
- }
- }
-
- /**
- * Writes to a new stream in the file
- */
- @Test
- void testWriteNewStream() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
-
- // 100 is our first free one
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
-
-
- // Add a single block one
- byte[] data = new byte[512];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
- }
-
- POIFSStream stream = new POIFSStream(fs);
- stream.updateContents(data);
-
- // Check it was allocated properly
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
-
- // And check the contents
- Iterator it = stream.getBlockIterator();
- int count = 0;
- while (it.hasNext()) {
- ByteBuffer b = it.next();
- data = new byte[512];
- b.get(data);
- for (int i = 0; i < data.length; i++) {
- byte exp = (byte) (i % 256);
- assertEquals(exp, data[i]);
- }
- count++;
- }
- assertEquals(1, count);
-
-
- // And a multi block one
- data = new byte[512 * 3];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
- }
-
- stream = new POIFSStream(fs);
- stream.updateContents(data);
-
- // Check it was allocated properly
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
- assertEquals(102, fs.getNextBlock(101));
- assertEquals(103, fs.getNextBlock(102));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(103));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
-
- // And check the contents
- it = stream.getBlockIterator();
- count = 0;
- while (it.hasNext()) {
- ByteBuffer b = it.next();
- data = new byte[512];
- b.get(data);
- for (int i = 0; i < data.length; i++) {
- byte exp = (byte) (i % 256);
- assertEquals(exp, data[i]);
- }
- count++;
- }
- assertEquals(3, count);
-
- // Free it
- stream.free();
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
-
- fs.close();
- }
-
- /**
- * Writes to a new stream in the file, where we've not enough
- * free blocks so new FAT segments will need to be allocated
- * to support this
- */
- @Test
- void testWriteNewStreamExtraFATs() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
-
- // Allocate almost all the blocks
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127));
- for (int i = 100; i < 127; i++) {
- fs.setNextBlock(i, POIFSConstants.END_OF_CHAIN);
- }
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127));
- assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
-
-
- // Write a 3 block stream
- byte[] data = new byte[512 * 3];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
- }
- POIFSStream stream = new POIFSStream(fs);
- stream.updateContents(data);
-
- // Check we got another BAT
- assertFalse(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- assertTrue(fs.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
-
- // the BAT will be in the first spot of the new block
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(126));
- assertEquals(129, fs.getNextBlock(127));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(128));
- assertEquals(130, fs.getNextBlock(129));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(130));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(131));
-
- fs.close();
- }
-
- /**
- * Replaces data in an existing stream, with a bit
- * more data than before, in a 4096 byte block file
- */
- @Test
- void testWriteStream4096() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
-
- // 0 -> 1 -> 2 -> end
- assertEquals(1, fs.getNextBlock(0));
- assertEquals(2, fs.getNextBlock(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2));
- assertEquals(4, fs.getNextBlock(3));
-
- // First free one is at 15
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(15));
-
-
- // Write a 5 block file
- byte[] data = new byte[4096 * 5];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
- }
- POIFSStream stream = new POIFSStream(fs, 0);
- stream.updateContents(data);
-
-
- // Check it
- assertEquals(1, fs.getNextBlock(0));
- assertEquals(2, fs.getNextBlock(1));
- assertEquals(15, fs.getNextBlock(2)); // Jumps
- assertEquals(4, fs.getNextBlock(3)); // Next stream
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14));
- assertEquals(16, fs.getNextBlock(15)); // Continues
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(16)); // Ends
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(17)); // Free
-
- // Check the contents too
- Iterator it = stream.getBlockIterator();
- int count = 0;
- while (it.hasNext()) {
- ByteBuffer b = it.next();
- data = new byte[512];
- b.get(data);
- for (int i = 0; i < data.length; i++) {
- byte exp = (byte) (i % 256);
- assertEquals(exp, data[i]);
- }
- count++;
- }
- assertEquals(5, count);
-
- fs.close();
- }
-
- /**
- * Tests that we can write into the mini stream
- */
- @Test
- void testWriteMiniStreams() throws Exception {
- try (InputStream is = _inst.openResourceAsStream("BlockSize512.zvi");
- POIFSFileSystem fs = new POIFSFileSystem(is)) {
-
- POIFSMiniStore ministore = fs.getMiniStore();
-
- // 178 -> 179 -> 180 -> end
- assertEquals(179, ministore.getNextBlock(178));
- assertEquals(180, ministore.getNextBlock(179));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180));
-
-
- // Try writing 3 full blocks worth
- byte[] data = new byte[64 * 3];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) i;
- }
- POIFSStream stream = new POIFSStream(ministore, 178);
- stream.updateContents(data);
-
- // Check
- assertEquals(179, ministore.getNextBlock(178));
- assertEquals(180, ministore.getNextBlock(179));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180));
-
- stream = new POIFSStream(ministore, 178);
- Iterator it = stream.getBlockIterator();
- ByteBuffer b178 = it.next();
- ByteBuffer b179 = it.next();
- ByteBuffer b180 = it.next();
- assertFalse(it.hasNext());
-
- assertEquals((byte) 0x00, b178.get());
- assertEquals((byte) 0x01, b178.get());
- assertEquals((byte) 0x40, b179.get());
- assertEquals((byte) 0x41, b179.get());
- assertEquals((byte) 0x80, b180.get());
- assertEquals((byte) 0x81, b180.get());
-
-
- // Try writing just into 3 blocks worth
- data = new byte[64 * 2 + 12];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i + 4);
- }
- stream = new POIFSStream(ministore, 178);
- stream.updateContents(data);
-
- // Check
- assertEquals(179, ministore.getNextBlock(178));
- assertEquals(180, ministore.getNextBlock(179));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180));
-
- stream = new POIFSStream(ministore, 178);
- it = stream.getBlockIterator();
- b178 = it.next();
- b179 = it.next();
- b180 = it.next();
- assertFalse(it.hasNext());
-
- assertEquals((byte) 0x04, b178.get(0));
- assertEquals((byte) 0x05, b178.get(1));
- assertEquals((byte) 0x44, b179.get(0));
- assertEquals((byte) 0x45, b179.get(1));
- assertEquals((byte) 0x84, b180.get(0));
- assertEquals((byte) 0x85, b180.get(1));
-
-
- // Try writing 1, should truncate
- data = new byte[12];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i + 9);
- }
- stream = new POIFSStream(ministore, 178);
- stream.updateContents(data);
-
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(178));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(179));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(180));
-
- stream = new POIFSStream(ministore, 178);
- it = stream.getBlockIterator();
- b178 = it.next();
- assertFalse(it.hasNext());
-
- assertEquals((byte) 0x09, b178.get(0));
- assertEquals((byte) 0x0a, b178.get(1));
-
-
- // Try writing 5, should extend
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(178));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(179));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(180));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(181));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(182));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(183));
-
- data = new byte[64 * 4 + 12];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i + 3);
- }
- stream = new POIFSStream(ministore, 178);
- stream.updateContents(data);
-
- assertEquals(179, ministore.getNextBlock(178));
- assertEquals(180, ministore.getNextBlock(179));
- assertEquals(181, ministore.getNextBlock(180));
- assertEquals(182, ministore.getNextBlock(181));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(182));
-
- stream = new POIFSStream(ministore, 178);
- it = stream.getBlockIterator();
- b178 = it.next();
- b179 = it.next();
- b180 = it.next();
- ByteBuffer b181 = it.next();
- ByteBuffer b182 = it.next();
- assertFalse(it.hasNext());
-
- assertEquals((byte) 0x03, b178.get(0));
- assertEquals((byte) 0x04, b178.get(1));
- assertEquals((byte) 0x43, b179.get(0));
- assertEquals((byte) 0x44, b179.get(1));
- assertEquals((byte) 0x83, b180.get(0));
- assertEquals((byte) 0x84, b180.get(1));
- assertEquals((byte) 0xc3, b181.get(0));
- assertEquals((byte) 0xc4, b181.get(1));
- assertEquals((byte) 0x03, b182.get(0));
- assertEquals((byte) 0x04, b182.get(1));
-
-
- // Write lots, so it needs another big block
- ministore.getBlockAt(183);
- assertThrows(NoSuchElementException.class, () -> ministore.getBlockAt(184), "Block 184 should be off the end of the list");
-
- data = new byte[64 * 6 + 12];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i + 1);
- }
- stream = new POIFSStream(ministore, 178);
- stream.updateContents(data);
-
- // Should have added 2 more blocks to the chain
- assertEquals(179, ministore.getNextBlock(178));
- assertEquals(180, ministore.getNextBlock(179));
- assertEquals(181, ministore.getNextBlock(180));
- assertEquals(182, ministore.getNextBlock(181));
- assertEquals(183, ministore.getNextBlock(182));
- assertEquals(184, ministore.getNextBlock(183));
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(184));
- assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(185));
-
- // Block 184 should exist
- ministore.getBlockAt(183);
- ministore.getBlockAt(184);
- ministore.getBlockAt(185);
-
- // Check contents
- stream = new POIFSStream(ministore, 178);
- it = stream.getBlockIterator();
- b178 = it.next();
- b179 = it.next();
- b180 = it.next();
- b181 = it.next();
- b182 = it.next();
- ByteBuffer b183 = it.next();
- ByteBuffer b184 = it.next();
- assertFalse(it.hasNext());
-
- assertEquals((byte) 0x01, b178.get(0));
- assertEquals((byte) 0x02, b178.get(1));
- assertEquals((byte) 0x41, b179.get(0));
- assertEquals((byte) 0x42, b179.get(1));
- assertEquals((byte) 0x81, b180.get(0));
- assertEquals((byte) 0x82, b180.get(1));
- assertEquals((byte) 0xc1, b181.get(0));
- assertEquals((byte) 0xc2, b181.get(1));
- assertEquals((byte) 0x01, b182.get(0));
- assertEquals((byte) 0x02, b182.get(1));
- assertEquals((byte) 0x41, b183.get(0));
- assertEquals((byte) 0x42, b183.get(1));
- assertEquals((byte) 0x81, b184.get(0));
- assertEquals((byte) 0x82, b184.get(1));
-
- }
- }
-
- /**
- * Craft a nasty file with a loop, and ensure we don't get stuck
- */
- @Test
- void testWriteFailsOnLoop() throws Exception {
- try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) {
-
- // Hack the FAT so that it goes 0->1->2->0
- fs.setNextBlock(0, 1);
- fs.setNextBlock(1, 2);
- fs.setNextBlock(2, 0);
-
- // Try to write a large amount, should fail on the write
- POIFSStream stream1 = new POIFSStream(fs, 0);
- assertThrows(IllegalStateException.class,
- () -> stream1.updateContents(new byte[512 * 4]), "Loop should have been detected but wasn't!");
-
- // Now reset, and try on a small bit
- // Should fail during the freeing set
- fs.setNextBlock(0, 1);
- fs.setNextBlock(1, 2);
- fs.setNextBlock(2, 0);
-
- POIFSStream stream2 = new POIFSStream(fs, 0);
- assertThrows(IllegalStateException.class,
- () -> stream2.updateContents(new byte[512]), "Loop should have been detected but wasn't!");
- }
- }
-
- /**
- * Tests adding a new stream, writing and reading it.
- */
- @Test
- void testReadWriteNewStream() throws Exception {
- try (POIFSFileSystem fs = new POIFSFileSystem()) {
- POIFSStream stream = new POIFSStream(fs);
-
- // Check our filesystem has Properties then BAT
- assertEquals(2, fs.getFreeBlock());
- BATBlock bat = fs.getBATBlockAndIndex(0).getBlock();
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(2));
-
- // Check the stream as-is
- assertEquals(POIFSConstants.END_OF_CHAIN, stream.getStartBlock());
- assertThrows(IllegalStateException.class, stream::getBlockIterator,
- "Shouldn't be able to get an iterator before writing");
-
- // Write in two blocks
- byte[] data = new byte[512 + 20];
- for (int i = 0; i < 512; i++) {
- data[i] = (byte) (i % 256);
- }
- for (int i = 512; i < data.length; i++) {
- data[i] = (byte) (i % 256 + 100);
- }
- stream.updateContents(data);
-
- // Check now
- assertEquals(4, fs.getFreeBlock());
- bat = fs.getBATBlockAndIndex(0).getBlock();
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(3, bat.getValueAt(2));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(4));
-
-
- Iterator it = stream.getBlockIterator();
- assertTrue(it.hasNext());
- ByteBuffer b = it.next();
-
- byte[] read = new byte[512];
- b.get(read);
- for (int i = 0; i < read.length; i++) {
- assertEquals(data[i], read[i], "Wrong value at " + i);
- }
-
- assertTrue(it.hasNext());
- b = it.next();
-
- read = new byte[512];
- b.get(read);
- for (int i = 0; i < 20; i++) {
- assertEquals(data[i + 512], read[i]);
- }
- for (int i = 20; i < read.length; i++) {
- assertEquals(0, read[i]);
- }
-
- assertFalse(it.hasNext());
- }
- }
-
- /**
- * Writes a stream, then replaces it
- */
- @Test
- void testWriteThenReplace() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem();
-
- // Starts empty, other that Properties and BAT
- BATBlock bat = fs.getBATBlockAndIndex(0).getBlock();
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(2));
-
- // Write something that uses a main stream
- byte[] main4106 = new byte[4106];
- main4106[0] = -10;
- main4106[4105] = -11;
- fs.getRoot().createDocument("Normal", new ByteArrayInputStream(main4106));
-
- // Should have used 9 blocks
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(3, bat.getValueAt(2));
- assertEquals(4, bat.getValueAt(3));
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(10, bat.getValueAt(9));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
-
- DocumentEntry normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4106, normal.getSize());
- assertEquals(4106, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Replace with one still big enough for a main stream, but one block smaller
- byte[] main4096 = new byte[4096];
- main4096[0] = -10;
- main4096[4095] = -11;
-
- DocumentOutputStream nout = new DocumentOutputStream(normal);
- nout.write(main4096);
- nout.close();
-
- // Will have dropped to 8
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(3, bat.getValueAt(2));
- assertEquals(4, bat.getValueAt(3));
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4096, normal.getSize());
- assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Write and check
- fs = writeOutAndReadBack(fs);
- bat = fs.getBATBlockAndIndex(0).getBlock();
-
- // No change after write
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); // Properties
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(3, bat.getValueAt(2));
- assertEquals(4, bat.getValueAt(3));
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9)); // End of Normal
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4096, normal.getSize());
- assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Make longer, take 1 block at the end
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- nout = new DocumentOutputStream(normal);
- nout.write(main4106);
- nout.close();
-
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(3, bat.getValueAt(2));
- assertEquals(4, bat.getValueAt(3));
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(10, bat.getValueAt(9));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10)); // Normal
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4106, normal.getSize());
- assertEquals(4106, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Make it small, will trigger the SBAT stream and free lots up
- byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42};
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- nout = new DocumentOutputStream(normal);
- nout.write(mini);
- nout.close();
-
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(4));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(5));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(6));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(7));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(8));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(9));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(7, normal.getSize());
- assertEquals(7, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Finally back to big again
- nout = new DocumentOutputStream(normal);
- nout.write(main4096);
- nout.close();
-
- // Will keep the mini stream, now empty
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(10, bat.getValueAt(9));
- assertEquals(11, bat.getValueAt(10));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4096, normal.getSize());
- assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Save, re-load, re-check
- fs = writeOutAndReadBack(fs);
- bat = fs.getBATBlockAndIndex(0).getBlock();
-
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(10, bat.getValueAt(9));
- assertEquals(11, bat.getValueAt(10));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4096, normal.getSize());
- assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
-
- fs.close();
- }
-
-
- /**
- * Returns test files with 512 byte and 4k block sizes, loaded
- * both from InputStreams and Files
- */
- private POIFSFileSystem[] get512and4kFileAndInput() throws IOException {
- POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- POIFSFileSystem fsC = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- POIFSFileSystem fsD = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- return new POIFSFileSystem[]{fsA, fsB, fsC, fsD};
- }
-
- private static void assertBATCount(POIFSFileSystem fs, int expectedBAT, int expectedXBAT) throws IOException {
- int foundBAT = 0;
- int foundXBAT = 0;
- int sz = (int) (fs.size() / fs.getBigBlockSize());
- for (int i = 0; i < sz; i++) {
- if (fs.getNextBlock(i) == POIFSConstants.FAT_SECTOR_BLOCK) {
- foundBAT++;
- }
- if (fs.getNextBlock(i) == POIFSConstants.DIFAT_SECTOR_BLOCK) {
- foundXBAT++;
- }
- }
- assertEquals(expectedBAT, foundBAT, "Wrong number of BATs");
- assertEquals(expectedXBAT, foundXBAT, "Wrong number of XBATs with " + expectedBAT + " BATs");
- }
-
- private void assertContentsMatches(byte[] expected, DocumentEntry doc) throws IOException {
- DocumentInputStream inp = new DocumentInputStream(doc);
- byte[] contents = new byte[doc.getSize()];
- assertEquals(doc.getSize(), inp.read(contents));
- inp.close();
-
- if (expected != null) {
- assertThat(expected, equalTo(contents));
- }
- }
-
- private static HeaderBlock writeOutAndReadHeader(POIFSFileSystem fs) throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- fs.writeFilesystem(baos);
-
- return new HeaderBlock(new ByteArrayInputStream(baos.toByteArray()));
- }
-
- private static POIFSFileSystem writeOutAndReadBack(POIFSFileSystem original) throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- original.writeFilesystem(baos);
- return new POIFSFileSystem(new ByteArrayInputStream(baos.toByteArray()));
- }
-
- private static POIFSFileSystem writeOutFileAndReadBack(POIFSFileSystem original) throws IOException {
- final File file = TempFile.createTempFile("TestPOIFS", ".ole2");
- try (OutputStream fout = new FileOutputStream(file)) {
- original.writeFilesystem(fout);
- }
- return new POIFSFileSystem(file, false);
- }
-
- @Test
- void basicOpen() throws IOException {
- POIFSFileSystem fsA, fsB;
-
- // With a simple 512 block file
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
- assertEquals(512, fs.getBigBlockSize());
- }
- fsA.close();
- fsB.close();
-
- // Now with a simple 4096 block file
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
- assertEquals(4096, fs.getBigBlockSize());
- }
- fsA.close();
- fsB.close();
- }
-
- @Test
- void propertiesAndFatOnRead() throws IOException {
- POIFSFileSystem fsA, fsB;
-
- // With a simple 512 block file
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
- // Check the FAT was properly processed:
- // Verify we only got one block
- fs.getBATBlockAndIndex(0);
- fs.getBATBlockAndIndex(1);
- assertThrows(IndexOutOfBoundsException.class, () -> fs.getBATBlockAndIndex(140),
- "Should only be one BAT, but a 2nd was found");
-
- // Verify a few next offsets
- // 97 -> 98 -> END
- assertEquals(98, fs.getNextBlock(97));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98));
-
-
- // Check the properties
- PropertyTable props = fs._get_property_table();
- assertEquals(90, props.getStartBlock());
- assertEquals(7, props.countBlocks());
-
- // Root property tells us about the Mini Stream
- RootProperty root = props.getRoot();
- assertEquals("Root Entry", root.getName());
- assertEquals(11564, root.getSize());
- assertEquals(0, root.getStartBlock());
-
- // Check its children too
- Property prop;
- Iterator pi = root.getChildren();
- prop = pi.next();
- assertEquals("Thumbnail", prop.getName());
- prop = pi.next();
- assertEquals("\u0005DocumentSummaryInformation", prop.getName());
- prop = pi.next();
- assertEquals("\u0005SummaryInformation", prop.getName());
- prop = pi.next();
- assertEquals("Image", prop.getName());
- prop = pi.next();
- assertEquals("Tags", prop.getName());
- assertFalse(pi.hasNext());
-
-
- // Check the SBAT (Small Blocks FAT) was properly processed
- POIFSMiniStore ministore = fs.getMiniStore();
-
- // Verify we only got two SBAT blocks
- ministore.getBATBlockAndIndex(0);
- ministore.getBATBlockAndIndex(128);
- assertThrows(IndexOutOfBoundsException.class, () -> ministore.getBATBlockAndIndex(256),
- "Should only be two SBATs, but a 3rd was found");
-
- // Verify a few offsets: 0->50 is a stream
- for (int i = 0; i < 50; i++) {
- assertEquals(i + 1, ministore.getNextBlock(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50));
-
- fs.close();
- }
-
- // Now with a simple 4096 block file
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
- // Check the FAT was properly processed
- // Verify we only got one block
- fs.getBATBlockAndIndex(0);
- fs.getBATBlockAndIndex(1);
- assertThrows(IndexOutOfBoundsException.class, () -> fs.getBATBlockAndIndex(1040),
- "Should only be one BAT, but a 2nd was found");
-
- // Verify a few next offsets
- // 0 -> 1 -> 2 -> END
- assertEquals(1, fs.getNextBlock(0));
- assertEquals(2, fs.getNextBlock(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2));
-
-
- // Check the properties
- PropertyTable props = fs._get_property_table();
- assertEquals(12, props.getStartBlock());
- assertEquals(1, props.countBlocks());
-
- // Root property tells us about the Mini Stream
- RootProperty root = props.getRoot();
- assertEquals("Root Entry", root.getName());
- assertEquals(11564, root.getSize());
- assertEquals(0, root.getStartBlock());
-
- // Check its children too
- Property prop;
- Iterator pi = root.getChildren();
- prop = pi.next();
- assertEquals("Thumbnail", prop.getName());
- prop = pi.next();
- assertEquals("\u0005DocumentSummaryInformation", prop.getName());
- prop = pi.next();
- assertEquals("\u0005SummaryInformation", prop.getName());
- prop = pi.next();
- assertEquals("Image", prop.getName());
- prop = pi.next();
- assertEquals("Tags", prop.getName());
- assertFalse(pi.hasNext());
-
-
- // Check the SBAT (Small Blocks FAT) was properly processed
- POIFSMiniStore ministore = fs.getMiniStore();
-
- // Verify we only got one SBAT block
- ministore.getBATBlockAndIndex(0);
- ministore.getBATBlockAndIndex(128);
- ministore.getBATBlockAndIndex(1023);
- assertThrows(IndexOutOfBoundsException.class, () -> ministore.getBATBlockAndIndex(1024),
- "Should only be one SBAT, but a 2nd was found");
-
- // Verify a few offsets: 0->50 is a stream
- for (int i = 0; i < 50; i++) {
- assertEquals(i + 1, ministore.getNextBlock(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50));
-
- fs.close();
- }
- }
-
- /**
- * Check that for a given block, we can correctly figure
- * out what the next one is
- */
- @Test
- void nextBlock() throws IOException {
- POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
- // 0 -> 21 are simple
- for (int i = 0; i < 21; i++) {
- assertEquals(i + 1, fs.getNextBlock(i));
- }
- // 21 jumps to 89, then ends
- assertEquals(89, fs.getNextBlock(21));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(89));
-
- // 22 -> 88 simple sequential stream
- for (int i = 22; i < 88; i++) {
- assertEquals(i + 1, fs.getNextBlock(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(88));
-
- // 90 -> 96 is another stream
- for (int i = 90; i < 96; i++) {
- assertEquals(i + 1, fs.getNextBlock(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(96));
-
- // 97+98 is another
- assertEquals(98, fs.getNextBlock(97));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98));
-
- // 99 is our FAT block
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
-
- // 100 onwards is free
- for (int i = 100; i < fs.getBigBlockSizeDetails().getBATEntriesPerBlock(); i++) {
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(i));
- }
-
- fs.close();
- }
-
- // Quick check on 4096 byte blocks too
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
- // 0 -> 1 -> 2 -> end
- assertEquals(1, fs.getNextBlock(0));
- assertEquals(2, fs.getNextBlock(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2));
-
- // 4 -> 11 then end
- for (int i = 4; i < 11; i++) {
- assertEquals(i + 1, fs.getNextBlock(i));
- }
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(11));
-
- fs.close();
- }
- }
-
- /**
- * Check we get the right data back for each block
- */
- @Test
- void getBlock() throws IOException {
- POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
- ByteBuffer b;
-
- // The 0th block is the first data block
- b = fs.getBlockAt(0);
- assertEquals((byte) 0x9e, b.get());
- assertEquals((byte) 0x75, b.get());
- assertEquals((byte) 0x97, b.get());
- assertEquals((byte) 0xf6, b.get());
-
- // And the next block
- b = fs.getBlockAt(1);
- assertEquals((byte) 0x86, b.get());
- assertEquals((byte) 0x09, b.get());
- assertEquals((byte) 0x22, b.get());
- assertEquals((byte) 0xfb, b.get());
-
- // Check the final block too
- b = fs.getBlockAt(99);
- assertEquals((byte) 0x01, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x02, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
-
- fs.close();
- }
-
- // Quick check on 4096 byte blocks too
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
- ByteBuffer b;
-
- // The 0th block is the first data block
- b = fs.getBlockAt(0);
- assertEquals((byte) 0x9e, b.get());
- assertEquals((byte) 0x75, b.get());
- assertEquals((byte) 0x97, b.get());
- assertEquals((byte) 0xf6, b.get());
-
- // And the next block
- b = fs.getBlockAt(1);
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x03, b.get());
- assertEquals((byte) 0x00, b.get());
-
- // The 14th block is the FAT
- b = fs.getBlockAt(14);
- assertEquals((byte) 0x01, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x02, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
-
- fs.close();
- }
- }
-
- /**
- * Ask for free blocks where there are some already
- * to be had from the FAT
- */
- @Test
- void getFreeBlockWithSpare() throws IOException {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
-
- // Our first BAT block has spares
- assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
-
- // First free one is 100
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
-
- // Ask, will get 100
- assertEquals(100, fs.getFreeBlock());
-
- // Ask again, will still get 100 as not written to
- assertEquals(100, fs.getFreeBlock());
-
- // Allocate it, then ask again
- fs.setNextBlock(100, POIFSConstants.END_OF_CHAIN);
- assertEquals(101, fs.getFreeBlock());
-
- // All done
- fs.close();
- }
-
- /**
- * Ask for free blocks where no free ones exist, and so the
- * file needs to be extended and another BAT/XBAT added
- */
- @Test
- void getFreeBlockWithNoneSpare() throws IOException {
- POIFSFileSystem fs1 = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- int free;
-
- // We have one BAT at block 99
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(99));
- assertBATCount(fs1, 1, 0);
-
- // We've spare ones from 100 to 128
- for (int i = 100; i < 128; i++) {
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(i));
- }
-
- // Check our BAT knows it's free
- assertTrue(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
-
- // Allocate all the spare ones
- for (int i = 100; i < 128; i++) {
- fs1.setNextBlock(i, POIFSConstants.END_OF_CHAIN);
- }
-
- // BAT is now full, but there's only the one
- assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(128), "Should only be one BAT");
- assertBATCount(fs1, 1, 0);
-
-
- // Now ask for a free one, will need to extend the file
- assertEquals(129, fs1.getFreeBlock());
-
- assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- assertTrue(fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(128));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(129));
-
- // We now have 2 BATs, but no XBATs
- assertBATCount(fs1, 2, 0);
-
-
- // Fill up to hold 109 BAT blocks
- for (int i = 0; i < 109; i++) {
- fs1.getFreeBlock();
- int startOffset = i * 128;
- while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) {
- free = fs1.getFreeBlock();
- fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN);
- }
- }
-
- assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(109 * 128), "Should only be 109 BATs");
-
- // We now have 109 BATs, but no XBATs
- assertBATCount(fs1, 109, 0);
-
-
- // Ask for it to be written out, and check the header
- HeaderBlock header = writeOutAndReadHeader(fs1);
- assertEquals(109, header.getBATCount());
- assertEquals(0, header.getXBATCount());
-
-
- // Ask for another, will get our first XBAT
- free = fs1.getFreeBlock();
- assertTrue(free > 0, "Had: " + free);
-
- assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors());
- assertTrue(fs1.getBATBlockAndIndex(110 * 128 - 1).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(110 * 128), "Should only be 110 BATs");
- assertBATCount(fs1, 110, 1);
-
- header = writeOutAndReadHeader(fs1);
- assertEquals(110, header.getBATCount());
- assertEquals(1, header.getXBATCount());
-
-
- // Fill the XBAT, which means filling 127 BATs
- for (int i = 109; i < 109 + 127; i++) {
- fs1.getFreeBlock();
- int startOffset = i * 128;
- while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) {
- free = fs1.getFreeBlock();
- fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN);
- }
- assertBATCount(fs1, i + 1, 1);
- }
-
- // Should now have 109+127 = 236 BATs
- assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(236 * 128), "Should only be 236 BATs");
- assertBATCount(fs1, 236, 1);
-
-
- // Ask for another, will get our 2nd XBAT
- free = fs1.getFreeBlock();
- assertTrue(free > 0, "Had: " + free);
-
- assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
- assertTrue(fs1.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs");
-
-
- // Check the counts now
- assertBATCount(fs1, 237, 2);
-
- // Check the header
- header = writeOutAndReadHeader(fs1);
- assertNotNull(header);
-
- // Now, write it out, and read it back in again fully
- POIFSFileSystem fs2 = writeOutAndReadBack(fs1);
- fs1.close();
-
- // Check that it is seen correctly
- assertBATCount(fs2, 237, 2);
-
- assertFalse(fs2.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
- assertTrue(fs2.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs2.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs");
-
- // All done
- fs2.close();
- }
-
- /**
- * Test that we can correctly get the list of directory
- * entries, and the details on the files in them
- */
- @Test
- void listEntries() throws IOException {
- for (POIFSFileSystem fs : get512and4kFileAndInput()) {
- DirectoryEntry root = fs.getRoot();
- assertEquals(5, root.getEntryCount());
-
- // Check by the names
- Entry thumbnail = root.getEntry("Thumbnail");
- Entry dsi = root.getEntry("\u0005DocumentSummaryInformation");
- Entry si = root.getEntry("\u0005SummaryInformation");
- Entry image = root.getEntry("Image");
- Entry tags = root.getEntry("Tags");
-
- assertFalse(thumbnail.isDirectoryEntry());
- assertFalse(dsi.isDirectoryEntry());
- assertFalse(si.isDirectoryEntry());
- assertTrue(image.isDirectoryEntry());
- assertFalse(tags.isDirectoryEntry());
-
- // Check via the iterator
- Iterator it = root.getEntries();
- assertEquals(thumbnail.getName(), it.next().getName());
- assertEquals(dsi.getName(), it.next().getName());
- assertEquals(si.getName(), it.next().getName());
- assertEquals(image.getName(), it.next().getName());
- assertEquals(tags.getName(), it.next().getName());
-
- // Look inside another
- DirectoryEntry imageD = (DirectoryEntry) image;
- assertEquals(7, imageD.getEntryCount());
-
- fs.close();
- }
- }
-
- /**
- * Tests that we can get the correct contents for
- * a document in the filesystem
- */
- @Test
- void getDocumentEntry() throws Exception {
- for (POIFSFileSystem fs : get512and4kFileAndInput()) {
- DirectoryEntry root = fs.getRoot();
- Entry si = root.getEntry("\u0005SummaryInformation");
-
- assertTrue(si.isDocumentEntry());
- DocumentNode doc = (DocumentNode) si;
-
- // Check we can read it
- assertContentsMatches(null, doc);
-
- // Now try to build the property set
- DocumentInputStream inp = new DocumentInputStream(doc);
- PropertySet ps = PropertySetFactory.create(inp);
- SummaryInformation inf = (SummaryInformation) ps;
-
- // Check some bits in it
- assertNull(inf.getApplicationName());
- assertNull(inf.getAuthor());
- assertNull(inf.getSubject());
- assertEquals(131333, inf.getOSVersion());
-
- // Finish with this one
- inp.close();
-
-
- // Try the other summary information
- si = root.getEntry("\u0005DocumentSummaryInformation");
- assertTrue(si.isDocumentEntry());
- doc = (DocumentNode) si;
- assertContentsMatches(null, doc);
-
- inp = new DocumentInputStream(doc);
- ps = PropertySetFactory.create(inp);
- DocumentSummaryInformation dinf = (DocumentSummaryInformation) ps;
- assertEquals(131333, dinf.getOSVersion());
-
- fs.close();
- }
- }
-
- /**
- * Read a file, write it and read it again.
- * Then, alter+add some streams, write and read
- */
- @Test
- void readWriteRead() throws Exception {
- SummaryInformation sinf;
- DocumentSummaryInformation dinf;
- DirectoryEntry root, testDir;
-
- for (POIFSFileSystem fs1 : get512and4kFileAndInput()) {
- // Check we can find the entries we expect
- root = fs1.getRoot();
- assertEquals(5, root.getEntryCount());
- assertThat(root.getEntryNames(), hasItem("Thumbnail"));
- assertThat(root.getEntryNames(), hasItem("Image"));
- assertThat(root.getEntryNames(), hasItem("Tags"));
- assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
- assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));
-
-
- // Write out, re-load
- POIFSFileSystem fs2 = writeOutAndReadBack(fs1);
- fs1.close();
-
- // Check they're still there
- root = fs2.getRoot();
- assertEquals(5, root.getEntryCount());
- assertThat(root.getEntryNames(), hasItem("Thumbnail"));
- assertThat(root.getEntryNames(), hasItem("Image"));
- assertThat(root.getEntryNames(), hasItem("Tags"));
- assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
- assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));
-
-
- // Check the contents of them - parse the summary block and check
- sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream(
- (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME)));
- assertEquals(131333, sinf.getOSVersion());
-
- dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream(
- (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)));
- assertEquals(131333, dinf.getOSVersion());
-
-
- // Add a test mini stream
- testDir = root.createDirectory("Testing 123");
- testDir.createDirectory("Testing 456");
- testDir.createDirectory("Testing 789");
- byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42};
- testDir.createDocument("Mini", new ByteArrayInputStream(mini));
-
-
- // Write out, re-load
- POIFSFileSystem fs3 = writeOutAndReadBack(fs2);
- fs2.close();
-
- root = fs3.getRoot();
- testDir = (DirectoryEntry) root.getEntry("Testing 123");
- assertEquals(6, root.getEntryCount());
- assertThat(root.getEntryNames(), hasItem("Thumbnail"));
- assertThat(root.getEntryNames(), hasItem("Image"));
- assertThat(root.getEntryNames(), hasItem("Tags"));
- assertThat(root.getEntryNames(), hasItem("Testing 123"));
- assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
- assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));
-
-
- // Check old and new are there
- sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream(
- (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME)));
- assertEquals(131333, sinf.getOSVersion());
-
- dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream(
- (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)));
- assertEquals(131333, dinf.getOSVersion());
-
- assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini"));
-
-
- // Write out and read once more, just to be sure
- POIFSFileSystem fs4 = writeOutAndReadBack(fs3);
- fs3.close();
-
- root = fs4.getRoot();
- testDir = (DirectoryEntry) root.getEntry("Testing 123");
- assertEquals(6, root.getEntryCount());
- assertThat(root.getEntryNames(), hasItem("Thumbnail"));
- assertThat(root.getEntryNames(), hasItem("Image"));
- assertThat(root.getEntryNames(), hasItem("Tags"));
- assertThat(root.getEntryNames(), hasItem("Testing 123"));
- assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
- assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));
-
- sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream(
- (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME)));
- assertEquals(131333, sinf.getOSVersion());
-
- dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream(
- (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)));
- assertEquals(131333, dinf.getOSVersion());
-
- assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini"));
-
-
- // Add a full stream, delete a full stream
- byte[] main4096 = new byte[4096];
- main4096[0] = -10;
- main4096[4095] = -11;
- testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096));
-
- root.getEntry("Tags").delete();
-
-
- // Write out, re-load
- POIFSFileSystem fs5 = writeOutAndReadBack(fs4);
- fs4.close();
-
- // Check it's all there
- root = fs5.getRoot();
- testDir = (DirectoryEntry) root.getEntry("Testing 123");
- assertEquals(5, root.getEntryCount());
- assertThat(root.getEntryNames(), hasItem("Thumbnail"));
- assertThat(root.getEntryNames(), hasItem("Image"));
- assertThat(root.getEntryNames(), hasItem("Testing 123"));
- assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
- assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));
-
-
- // Check old and new are there
- sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream(
- (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME)));
- assertEquals(131333, sinf.getOSVersion());
-
- dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream(
- (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)));
- assertEquals(131333, dinf.getOSVersion());
-
- assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini"));
- assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096"));
-
-
- // Delete a directory, and add one more
- testDir.getEntry("Testing 456").delete();
- testDir.createDirectory("Testing ABC");
-
-
- // Save
- POIFSFileSystem fs6 = writeOutAndReadBack(fs5);
- fs5.close();
-
- // Check
- root = fs6.getRoot();
- testDir = (DirectoryEntry) root.getEntry("Testing 123");
-
- assertEquals(5, root.getEntryCount());
- assertThat(root.getEntryNames(), hasItem("Thumbnail"));
- assertThat(root.getEntryNames(), hasItem("Image"));
- assertThat(root.getEntryNames(), hasItem("Testing 123"));
- assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
- assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));
-
- assertEquals(4, testDir.getEntryCount());
- assertThat(testDir.getEntryNames(), hasItem("Mini"));
- assertThat(testDir.getEntryNames(), hasItem("Normal4096"));
- assertThat(testDir.getEntryNames(), hasItem("Testing 789"));
- assertThat(testDir.getEntryNames(), hasItem("Testing ABC"));
-
-
- // Add another mini stream
- byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42};
- testDir.createDocument("Mini2", new ByteArrayInputStream(mini2));
-
- // Save, load, check
- POIFSFileSystem fs7 = writeOutAndReadBack(fs6);
- fs6.close();
-
- root = fs7.getRoot();
- testDir = (DirectoryEntry) root.getEntry("Testing 123");
-
- assertEquals(5, root.getEntryCount());
- assertThat(root.getEntryNames(), hasItem("Thumbnail"));
- assertThat(root.getEntryNames(), hasItem("Image"));
- assertThat(root.getEntryNames(), hasItem("Testing 123"));
- assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
- assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));
-
- assertEquals(5, testDir.getEntryCount());
- assertThat(testDir.getEntryNames(), hasItem("Mini"));
- assertThat(testDir.getEntryNames(), hasItem("Mini2"));
- assertThat(testDir.getEntryNames(), hasItem("Normal4096"));
- assertThat(testDir.getEntryNames(), hasItem("Testing 789"));
- assertThat(testDir.getEntryNames(), hasItem("Testing ABC"));
-
- assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini"));
- assertContentsMatches(mini2, (DocumentEntry) testDir.getEntry("Mini2"));
- assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096"));
-
-
- // Delete a mini stream, add one more
- testDir.getEntry("Mini").delete();
-
- byte[] mini3 = new byte[]{42, 0, 42, 0, 42, 0, 42};
- testDir.createDocument("Mini3", new ByteArrayInputStream(mini3));
-
-
- // Save, load, check
- POIFSFileSystem fs8 = writeOutAndReadBack(fs7);
- fs7.close();
-
- root = fs8.getRoot();
- testDir = (DirectoryEntry) root.getEntry("Testing 123");
-
- assertEquals(5, root.getEntryCount());
- assertThat(root.getEntryNames(), hasItem("Thumbnail"));
- assertThat(root.getEntryNames(), hasItem("Image"));
- assertThat(root.getEntryNames(), hasItem("Testing 123"));
- assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
- assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));
-
- assertEquals(5, testDir.getEntryCount());
- assertThat(testDir.getEntryNames(), hasItem("Mini2"));
- assertThat(testDir.getEntryNames(), hasItem("Mini3"));
- assertThat(testDir.getEntryNames(), hasItem("Normal4096"));
- assertThat(testDir.getEntryNames(), hasItem("Testing 789"));
- assertThat(testDir.getEntryNames(), hasItem("Testing ABC"));
-
- assertContentsMatches(mini2, (DocumentEntry) testDir.getEntry("Mini2"));
- assertContentsMatches(mini3, (DocumentEntry) testDir.getEntry("Mini3"));
- assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096"));
-
-
- // Change some existing streams
- POIFSDocument mini2Doc = new POIFSDocument((DocumentNode) testDir.getEntry("Mini2"));
- mini2Doc.replaceContents(new ByteArrayInputStream(mini));
-
- byte[] main4106 = new byte[4106];
- main4106[0] = 41;
- main4106[4105] = 42;
- POIFSDocument mainDoc = new POIFSDocument((DocumentNode) testDir.getEntry("Normal4096"));
- mainDoc.replaceContents(new ByteArrayInputStream(main4106));
-
-
- // Re-check
- POIFSFileSystem fs9 = writeOutAndReadBack(fs8);
- fs8.close();
-
- root = fs9.getRoot();
- testDir = (DirectoryEntry) root.getEntry("Testing 123");
-
- assertEquals(5, root.getEntryCount());
- assertThat(root.getEntryNames(), hasItem("Thumbnail"));
- assertThat(root.getEntryNames(), hasItem("Image"));
- assertThat(root.getEntryNames(), hasItem("Testing 123"));
- assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation"));
- assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation"));
-
- assertEquals(5, testDir.getEntryCount());
- assertThat(testDir.getEntryNames(), hasItem("Mini2"));
- assertThat(testDir.getEntryNames(), hasItem("Mini3"));
- assertThat(testDir.getEntryNames(), hasItem("Normal4096"));
- assertThat(testDir.getEntryNames(), hasItem("Testing 789"));
- assertThat(testDir.getEntryNames(), hasItem("Testing ABC"));
-
- assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini2"));
- assertContentsMatches(mini3, (DocumentEntry) testDir.getEntry("Mini3"));
- assertContentsMatches(main4106, (DocumentEntry) testDir.getEntry("Normal4096"));
-
-
- // All done
- fs9.close();
- }
- }
-
- /**
- * Create a new file, write it and read it again
- * Then, add some streams, write and read
- */
- @Test
- void createWriteRead() throws IOException {
- POIFSFileSystem fs1 = new POIFSFileSystem();
- DocumentEntry miniDoc;
- DocumentEntry normDoc;
-
- // Initially has Properties + BAT but not SBAT
- assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2));
-
- // Check that the SBAT is empty
- assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getRoot().getProperty().getStartBlock());
-
- // Check that properties table was given block 0
- assertEquals(0, fs1._get_property_table().getStartBlock());
-
- // Write and read it
- POIFSFileSystem fs2 = writeOutAndReadBack(fs1);
- fs1.close();
-
- // No change, SBAT remains empty
- assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(2));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(3));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getRoot().getProperty().getStartBlock());
- assertEquals(0, fs2._get_property_table().getStartBlock());
- fs2.close();
-
- // Check the same but with saving to a file
- POIFSFileSystem fs3 = new POIFSFileSystem();
- POIFSFileSystem fs4 = writeOutFileAndReadBack(fs3);
- fs3.close();
-
- // Same, no change, SBAT remains empty
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(2));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(3));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock());
- assertEquals(0, fs4._get_property_table().getStartBlock());
-
-
- // Put everything within a new directory
- DirectoryEntry testDir = fs4.createDirectory("Test Directory");
-
- // Add a new Normal Stream (Normal Streams minimum 4096 bytes)
- byte[] main4096 = new byte[4096];
- main4096[0] = -10;
- main4096[4095] = -11;
- testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096));
-
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
- assertEquals(3, fs4.getNextBlock(2));
- assertEquals(4, fs4.getNextBlock(3));
- assertEquals(5, fs4.getNextBlock(4));
- assertEquals(6, fs4.getNextBlock(5));
- assertEquals(7, fs4.getNextBlock(6));
- assertEquals(8, fs4.getNextBlock(7));
- assertEquals(9, fs4.getNextBlock(8));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(10));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(11));
- // SBAT still unused
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock());
-
-
- // Add a bigger Normal Stream
- byte[] main5124 = new byte[5124];
- main5124[0] = -22;
- main5124[5123] = -33;
- testDir.createDocument("Normal5124", new ByteArrayInputStream(main5124));
-
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
- assertEquals(3, fs4.getNextBlock(2));
- assertEquals(4, fs4.getNextBlock(3));
- assertEquals(5, fs4.getNextBlock(4));
- assertEquals(6, fs4.getNextBlock(5));
- assertEquals(7, fs4.getNextBlock(6));
- assertEquals(8, fs4.getNextBlock(7));
- assertEquals(9, fs4.getNextBlock(8));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9));
-
- assertEquals(11, fs4.getNextBlock(10));
- assertEquals(12, fs4.getNextBlock(11));
- assertEquals(13, fs4.getNextBlock(12));
- assertEquals(14, fs4.getNextBlock(13));
- assertEquals(15, fs4.getNextBlock(14));
- assertEquals(16, fs4.getNextBlock(15));
- assertEquals(17, fs4.getNextBlock(16));
- assertEquals(18, fs4.getNextBlock(17));
- assertEquals(19, fs4.getNextBlock(18));
- assertEquals(20, fs4.getNextBlock(19));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(21));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(22));
-
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock());
-
-
- // Now Add a mini stream
- byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42};
- testDir.createDocument("Mini", new ByteArrayInputStream(mini));
-
- // Mini stream will get one block for fat + one block for data
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1));
- assertEquals(3, fs4.getNextBlock(2));
- assertEquals(4, fs4.getNextBlock(3));
- assertEquals(5, fs4.getNextBlock(4));
- assertEquals(6, fs4.getNextBlock(5));
- assertEquals(7, fs4.getNextBlock(6));
- assertEquals(8, fs4.getNextBlock(7));
- assertEquals(9, fs4.getNextBlock(8));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9));
-
- assertEquals(11, fs4.getNextBlock(10));
- assertEquals(12, fs4.getNextBlock(11));
- assertEquals(13, fs4.getNextBlock(12));
- assertEquals(14, fs4.getNextBlock(13));
- assertEquals(15, fs4.getNextBlock(14));
- assertEquals(16, fs4.getNextBlock(15));
- assertEquals(17, fs4.getNextBlock(16));
- assertEquals(18, fs4.getNextBlock(17));
- assertEquals(19, fs4.getNextBlock(18));
- assertEquals(20, fs4.getNextBlock(19));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(21));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(22));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(23));
-
- // Check the mini stream location was set
- // (21 is mini fat, 22 is first mini stream block)
- assertEquals(22, fs4.getRoot().getProperty().getStartBlock());
-
-
- // Write and read back
- POIFSFileSystem fs5 = writeOutAndReadBack(fs4);
- fs4.close();
- HeaderBlock header = writeOutAndReadHeader(fs5);
-
- // Check the header has the right points in it
- assertEquals(1, header.getBATCount());
- assertEquals(1, header.getBATArray()[0]);
- assertEquals(0, header.getPropertyStart());
- assertEquals(1, header.getSBATCount());
- assertEquals(21, header.getSBATStart());
- assertEquals(22, fs5._get_property_table().getRoot().getStartBlock());
-
- // Block use should be almost the same, except the properties
- // stream will have grown out to cover 2 blocks
- // Check the block use is all unchanged
- assertEquals(23, fs5.getNextBlock(0)); // Properties now extends over 2 blocks
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs5.getNextBlock(1));
-
- assertEquals(3, fs5.getNextBlock(2));
- assertEquals(4, fs5.getNextBlock(3));
- assertEquals(5, fs5.getNextBlock(4));
- assertEquals(6, fs5.getNextBlock(5));
- assertEquals(7, fs5.getNextBlock(6));
- assertEquals(8, fs5.getNextBlock(7));
- assertEquals(9, fs5.getNextBlock(8));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(9)); // End of normal4096
-
- assertEquals(11, fs5.getNextBlock(10));
- assertEquals(12, fs5.getNextBlock(11));
- assertEquals(13, fs5.getNextBlock(12));
- assertEquals(14, fs5.getNextBlock(13));
- assertEquals(15, fs5.getNextBlock(14));
- assertEquals(16, fs5.getNextBlock(15));
- assertEquals(17, fs5.getNextBlock(16));
- assertEquals(18, fs5.getNextBlock(17));
- assertEquals(19, fs5.getNextBlock(18));
- assertEquals(20, fs5.getNextBlock(19));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(20)); // End of normal5124
-
- assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(21)); // Mini Stream FAT
- assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(22)); // Mini Stream data
- assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(23)); // Properties #2
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs5.getNextBlock(24));
-
-
- // Check some data
- assertEquals(1, fs5.getRoot().getEntryCount());
- testDir = (DirectoryEntry) fs5.getRoot().getEntry("Test Directory");
- assertEquals(3, testDir.getEntryCount());
-
- miniDoc = (DocumentEntry) testDir.getEntry("Mini");
- assertContentsMatches(mini, miniDoc);
-
- normDoc = (DocumentEntry) testDir.getEntry("Normal4096");
- assertContentsMatches(main4096, normDoc);
-
- normDoc = (DocumentEntry) testDir.getEntry("Normal5124");
- assertContentsMatches(main5124, normDoc);
-
-
- // Delete a couple of streams
- miniDoc.delete();
- normDoc.delete();
-
-
- // Check - will have un-used sectors now
- POIFSFileSystem fs6 = writeOutAndReadBack(fs5);
- fs5.close();
-
- assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(0)); // Props back in 1 block
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs6.getNextBlock(1));
-
- assertEquals(3, fs6.getNextBlock(2));
- assertEquals(4, fs6.getNextBlock(3));
- assertEquals(5, fs6.getNextBlock(4));
- assertEquals(6, fs6.getNextBlock(5));
- assertEquals(7, fs6.getNextBlock(6));
- assertEquals(8, fs6.getNextBlock(7));
- assertEquals(9, fs6.getNextBlock(8));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(9)); // End of normal4096
-
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(10));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(11));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(12));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(13));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(14));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(15));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(16));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(17));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(18));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(19));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(20));
-
- assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(21)); // Mini Stream FAT
- assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(22)); // Mini Stream data
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(23)); // Properties gone
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(24));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(25));
-
- // All done
- fs6.close();
- }
-
- @Test
- void addBeforeWrite() throws IOException {
- POIFSFileSystem fs1 = new POIFSFileSystem();
- DocumentEntry miniDoc;
- DocumentEntry normDoc;
- HeaderBlock hdr;
-
- // Initially has Properties + BAT but nothing else
- assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2));
-
- hdr = writeOutAndReadHeader(fs1);
- // No mini stream, and no xbats
- // Will have fat then properties stream
- assertEquals(1, hdr.getBATCount());
- assertEquals(1, hdr.getBATArray()[0]);
- assertEquals(0, hdr.getPropertyStart());
- assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getSBATStart());
- assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex());
- assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 3, fs1.size());
- fs1.close();
-
- // Get a clean filesystem to start with
- fs1 = new POIFSFileSystem();
-
- // Put our test files in a non-standard place
- DirectoryEntry parentDir = fs1.createDirectory("Parent Directory");
- DirectoryEntry testDir = parentDir.createDirectory("Test Directory");
-
-
- // Add to the mini stream
- byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42};
- testDir.createDocument("Mini", new ByteArrayInputStream(mini));
-
- // Add to the main stream
- byte[] main4096 = new byte[4096];
- main4096[0] = -10;
- main4096[4095] = -11;
- testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096));
-
-
- // Check the mini stream was added, then the main stream
- assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(2)); // Mini Fat
- assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(3)); // Mini Stream
- assertEquals(5, fs1.getNextBlock(4)); // Main Stream
- assertEquals(6, fs1.getNextBlock(5));
- assertEquals(7, fs1.getNextBlock(6));
- assertEquals(8, fs1.getNextBlock(7));
- assertEquals(9, fs1.getNextBlock(8));
- assertEquals(10, fs1.getNextBlock(9));
- assertEquals(11, fs1.getNextBlock(10));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(11));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(12));
- assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 13, fs1.size());
-
-
- // Check that we can read the right data pre-write
- miniDoc = (DocumentEntry) testDir.getEntry("Mini");
- assertContentsMatches(mini, miniDoc);
-
- normDoc = (DocumentEntry) testDir.getEntry("Normal4096");
- assertContentsMatches(main4096, normDoc);
-
-
- // Write, read, check
- hdr = writeOutAndReadHeader(fs1);
- POIFSFileSystem fs2 = writeOutAndReadBack(fs1);
- fs1.close();
-
- // Check the header details - will have the sbat near the start,
- // then the properties at the end
- assertEquals(1, hdr.getBATCount());
- assertEquals(1, hdr.getBATArray()[0]);
- assertEquals(2, hdr.getSBATStart());
- assertEquals(0, hdr.getPropertyStart());
- assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex());
-
- // Check the block allocation is unchanged, other than
- // the properties stream going in at the end
- assertEquals(12, fs2.getNextBlock(0)); // Properties
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(2));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(3));
- assertEquals(5, fs2.getNextBlock(4));
- assertEquals(6, fs2.getNextBlock(5));
- assertEquals(7, fs2.getNextBlock(6));
- assertEquals(8, fs2.getNextBlock(7));
- assertEquals(9, fs2.getNextBlock(8));
- assertEquals(10, fs2.getNextBlock(9));
- assertEquals(11, fs2.getNextBlock(10));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(11));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(12));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(13));
- assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 14, fs2.size());
-
-
- // Check the data
- DirectoryEntry fsRoot = fs2.getRoot();
- assertEquals(1, fsRoot.getEntryCount());
-
- parentDir = (DirectoryEntry) fsRoot.getEntry("Parent Directory");
- assertEquals(1, parentDir.getEntryCount());
-
- testDir = (DirectoryEntry) parentDir.getEntry("Test Directory");
- assertEquals(2, testDir.getEntryCount());
-
- miniDoc = (DocumentEntry) testDir.getEntry("Mini");
- assertContentsMatches(mini, miniDoc);
-
- normDoc = (DocumentEntry) testDir.getEntry("Normal4096");
- assertContentsMatches(main4096, normDoc);
-
-
- // Add one more stream to each, then save and re-load
- byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42};
- testDir.createDocument("Mini2", new ByteArrayInputStream(mini2));
-
- // Add to the main stream
- byte[] main4106 = new byte[4106];
- main4106[0] = 41;
- main4106[4105] = 42;
- testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106));
-
-
- // Recheck the data in all 4 streams
- POIFSFileSystem fs3 = writeOutAndReadBack(fs2);
- fs2.close();
-
- fsRoot = fs3.getRoot();
- assertEquals(1, fsRoot.getEntryCount());
-
- parentDir = (DirectoryEntry) fsRoot.getEntry("Parent Directory");
- assertEquals(1, parentDir.getEntryCount());
-
- testDir = (DirectoryEntry) parentDir.getEntry("Test Directory");
- assertEquals(4, testDir.getEntryCount());
-
- miniDoc = (DocumentEntry) testDir.getEntry("Mini");
- assertContentsMatches(mini, miniDoc);
-
- miniDoc = (DocumentEntry) testDir.getEntry("Mini2");
- assertContentsMatches(mini2, miniDoc);
-
- normDoc = (DocumentEntry) testDir.getEntry("Normal4106");
- assertContentsMatches(main4106, normDoc);
-
- // All done
- fs3.close();
- }
-
- @Test
- void readZeroLengthEntries() throws IOException {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("only-zero-byte-streams.ole2"));
- DirectoryNode testDir = fs.getRoot();
- assertEquals(3, testDir.getEntryCount());
- DocumentEntry entry;
-
- entry = (DocumentEntry) testDir.getEntry("test-zero-1");
- assertNotNull(entry);
- assertEquals(0, entry.getSize());
-
- entry = (DocumentEntry) testDir.getEntry("test-zero-2");
- assertNotNull(entry);
- assertEquals(0, entry.getSize());
-
- entry = (DocumentEntry) testDir.getEntry("test-zero-3");
- assertNotNull(entry);
- assertEquals(0, entry.getSize());
-
- // Check properties, all have zero length, no blocks
- PropertyTable props = fs._get_property_table();
- assertEquals(POIFSConstants.END_OF_CHAIN, props.getRoot().getStartBlock());
- for (Property prop : props.getRoot()) {
- assertEquals("test-zero-", prop.getName().substring(0, 10));
- assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock());
- }
-
- // All done
- fs.close();
- }
-
- @Test
- void writeZeroLengthEntries() throws IOException {
- POIFSFileSystem fs1 = new POIFSFileSystem();
- DirectoryNode testDir = fs1.getRoot();
- DocumentEntry miniDoc;
- DocumentEntry normDoc;
- DocumentEntry emptyDoc;
-
- // Add mini and normal sized entries to start
- byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42};
- testDir.createDocument("Mini2", new ByteArrayInputStream(mini2));
-
- // Add to the main stream
- byte[] main4106 = new byte[4106];
- main4106[0] = 41;
- main4106[4105] = 42;
- testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106));
-
- // Now add some empty ones
- byte[] empty = new byte[0];
- testDir.createDocument("empty-1", new ByteArrayInputStream(empty));
- testDir.createDocument("empty-2", new ByteArrayInputStream(empty));
- testDir.createDocument("empty-3", new ByteArrayInputStream(empty));
-
- // Check
- miniDoc = (DocumentEntry) testDir.getEntry("Mini2");
- assertContentsMatches(mini2, miniDoc);
-
- normDoc = (DocumentEntry) testDir.getEntry("Normal4106");
- assertContentsMatches(main4106, normDoc);
-
- emptyDoc = (DocumentEntry) testDir.getEntry("empty-1");
- assertContentsMatches(empty, emptyDoc);
-
- emptyDoc = (DocumentEntry) testDir.getEntry("empty-2");
- assertContentsMatches(empty, emptyDoc);
-
- emptyDoc = (DocumentEntry) testDir.getEntry("empty-3");
- assertContentsMatches(empty, emptyDoc);
-
- // Look at the properties entry, and check the empty ones
- // have zero size and no start block
- PropertyTable props = fs1._get_property_table();
- Iterator propsIt = props.getRoot().getChildren();
-
- Property prop = propsIt.next();
- assertEquals("Mini2", prop.getName());
- assertEquals(0, prop.getStartBlock());
- assertEquals(7, prop.getSize());
-
- prop = propsIt.next();
- assertEquals("Normal4106", prop.getName());
- assertEquals(4, prop.getStartBlock()); // BAT, Props, SBAT, MIni
- assertEquals(4106, prop.getSize());
-
- prop = propsIt.next();
- assertEquals("empty-1", prop.getName());
- assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock());
- assertEquals(0, prop.getSize());
-
- prop = propsIt.next();
- assertEquals("empty-2", prop.getName());
- assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock());
- assertEquals(0, prop.getSize());
-
- prop = propsIt.next();
- assertEquals("empty-3", prop.getName());
- assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock());
- assertEquals(0, prop.getSize());
-
-
- // Save and re-check
- POIFSFileSystem fs2 = writeOutAndReadBack(fs1);
- fs1.close();
- testDir = fs2.getRoot();
-
- miniDoc = (DocumentEntry) testDir.getEntry("Mini2");
- assertContentsMatches(mini2, miniDoc);
-
- normDoc = (DocumentEntry) testDir.getEntry("Normal4106");
- assertContentsMatches(main4106, normDoc);
-
- emptyDoc = (DocumentEntry) testDir.getEntry("empty-1");
- assertContentsMatches(empty, emptyDoc);
-
- emptyDoc = (DocumentEntry) testDir.getEntry("empty-2");
- assertContentsMatches(empty, emptyDoc);
-
- emptyDoc = (DocumentEntry) testDir.getEntry("empty-3");
- assertContentsMatches(empty, emptyDoc);
-
- // Check that a mini-stream was assigned, with one block used
- assertEquals(3, testDir.getProperty().getStartBlock());
- assertEquals(64, testDir.getProperty().getSize());
-
- // All done
- fs2.close();
- }
-
- /**
- * Test that we can read a file with POIFS, create a new POIFS instance,
- * write it out, read it with POIFS, and see the original data
- */
- @Test
- void POIFSReadCopyWritePOIFSRead() throws IOException {
- File testFile = POIDataSamples.getSpreadSheetInstance().getFile("Simple.xls");
- POIFSFileSystem src = new POIFSFileSystem(testFile);
- byte[] wbDataExp = IOUtils.toByteArray(src.createDocumentInputStream("Workbook"));
-
- POIFSFileSystem nfs = new POIFSFileSystem();
- EntryUtils.copyNodes(src.getRoot(), nfs.getRoot());
- src.close();
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- nfs.writeFilesystem(bos);
- nfs.close();
-
- POIFSFileSystem pfs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
- byte[] wbDataAct = IOUtils.toByteArray(pfs.createDocumentInputStream("Workbook"));
-
- assertThat(wbDataExp, equalTo(wbDataAct));
- pfs.close();
- }
-
- /**
- * Ensure that you can recursively delete directories and their
- * contents
- */
- @Test
- void RecursiveDelete() throws IOException {
- File testFile = POIDataSamples.getSpreadSheetInstance().getFile("SimpleMacro.xls");
- POIFSFileSystem src = new POIFSFileSystem(testFile);
-
- // Starts out with 5 entries:
- // _VBA_PROJECT_CUR
- // SummaryInformation <(0x05)SummaryInformation>
- // DocumentSummaryInformation <(0x05)DocumentSummaryInformation>
- // Workbook
- // CompObj <(0x01)CompObj>
- assertEquals(5, _countChildren(src._get_property_table().getRoot()));
- assertEquals(5, src.getRoot().getEntryCount());
-
- // Grab the VBA project root
- DirectoryEntry vbaProj = (DirectoryEntry) src.getRoot().getEntry("_VBA_PROJECT_CUR");
- assertEquals(3, vbaProj.getEntryCount());
- // Can't delete yet, has stuff
- assertFalse(vbaProj.delete());
- // Recursively delete
- _recursiveDeletee(vbaProj);
-
- // Entries gone
- assertEquals(4, _countChildren(src._get_property_table().getRoot()));
- assertEquals(4, src.getRoot().getEntryCount());
-
- // Done
- src.close();
- }
-
- private void _recursiveDeletee(Entry entry) throws IOException {
- if (entry.isDocumentEntry()) {
- assertTrue(entry.delete());
- return;
- }
-
- DirectoryEntry dir = (DirectoryEntry) entry;
- String[] names = dir.getEntryNames().toArray(new String[dir.getEntryCount()]);
- for (String name : names) {
- Entry ce = dir.getEntry(name);
- _recursiveDeletee(ce);
- }
- assertTrue(dir.delete());
- }
-
- @SuppressWarnings("unused")
- private int _countChildren(DirectoryProperty p) {
- int count = 0;
- for (Property cp : p) {
- count++;
- }
- return count;
- }
-
- /**
- * To ensure we can create a file >2gb in size, as well as to
- * extend existing files past the 2gb boundary.
- *
- * Note that to run this test, you will require 2.5+gb of free
- * space on your TMP/TEMP partition/disk
- *
- * Note that to run this test, you need to be able to mmap 2.5+gb
- * files, which may need bigger kernel.shmmax and vm.max_map_count
- * settings on Linux.
- *
- * TODO Fix this to work...
- */
- @Test
- @Disabled("Work in progress test for #60670")
- void creationAndExtensionPast2GB() throws Exception {
- File big = TempFile.createTempFile("poi-test-", ".ole2");
- assumeTrue(big.getFreeSpace() > 2.5 * 1024 * 1024 * 1024,
- "2.5gb of free space is required on your tmp/temp partition/disk to run large file tests");
- System.out.println("Slow, memory heavy test in progress....");
-
- int s100mb = 100 * 1024 * 1024;
- int s512mb = 512 * 1024 * 1024;
- long s2gb = 2L * 1024 * 1024 * 1024;
- DocumentEntry entry;
- POIFSFileSystem fs;
-
- // Create a just-sub 2gb file
- fs = POIFSFileSystem.create(big);
- for (int i = 0; i < 19; i++) {
- fs.createDocument(new DummyDataInputStream(s100mb), "Entry" + i);
- }
- fs.writeFilesystem();
- fs.close();
-
- // Extend it past the 2gb mark
- fs = new POIFSFileSystem(big, false);
- for (int i = 0; i < 19; i++) {
- entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i);
- assertNotNull(entry);
- assertEquals(s100mb, entry.getSize());
- }
-
- fs.createDocument(new DummyDataInputStream(s512mb), "Bigger");
- fs.writeFilesystem();
- fs.close();
-
- // Check it still works
- fs = new POIFSFileSystem(big, false);
- for (int i = 0; i < 19; i++) {
- entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i);
- assertNotNull(entry);
- assertEquals(s100mb, entry.getSize());
- }
- entry = (DocumentEntry) fs.getRoot().getEntry("Bigger");
- assertNotNull(entry);
- assertEquals(s512mb, entry.getSize());
-
- // Tidy
- fs.close();
- assertTrue(big.delete());
-
-
- // Create a >2gb file
- fs = POIFSFileSystem.create(big);
- for (int i = 0; i < 4; i++) {
- fs.createDocument(new DummyDataInputStream(s512mb), "Entry" + i);
- }
- fs.writeFilesystem();
- fs.close();
-
- // Read it
- fs = new POIFSFileSystem(big, false);
- for (int i = 0; i < 4; i++) {
- entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i);
- assertNotNull(entry);
- assertEquals(s512mb, entry.getSize());
- }
-
- // Extend it
- fs.createDocument(new DummyDataInputStream(s512mb), "Entry4");
- fs.writeFilesystem();
- fs.close();
-
- // Check it worked
- fs = new POIFSFileSystem(big, false);
- for (int i = 0; i < 5; i++) {
- entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i);
- assertNotNull(entry);
- assertEquals(s512mb, entry.getSize());
- }
-
- // Tidy
- fs.close();
- assertTrue(big.delete());
-
- // Create a file with a 2gb entry
- fs = POIFSFileSystem.create(big);
- fs.createDocument(new DummyDataInputStream(s100mb), "Small");
- // TODO Check we get a helpful error about the max size
- fs.createDocument(new DummyDataInputStream(s2gb), "Big");
- }
-
- private static final class DummyDataInputStream extends InputStream {
- private final long maxSize;
- private long size;
-
- private DummyDataInputStream(long maxSize) {
- this.maxSize = maxSize;
- this.size = 0;
- }
-
- public int read() {
- if (size >= maxSize) return -1;
- size++;
- return (int) (size % 128);
- }
-
- public int read(byte[] b) {
- return read(b, 0, b.length);
- }
-
- public int read(byte[] b, int offset, int len) {
- if (size >= maxSize) return -1;
- int sz = (int) Math.min(len, maxSize - size);
- for (int i = 0; i < sz; i++) {
- b[i + offset] = (byte) ((size + i) % 128);
- }
- size += sz;
- return sz;
- }
- }
-
- @Disabled("Takes a long time to run")
- @Test
- void performance() throws Exception {
- int iterations = 200;//1_000;
-
- System.out.println("NPOI:");
- long start = System.currentTimeMillis();
-
- for (int i = 0; i < iterations; i++) {
-
- try (InputStream inputStream = POIDataSamples.getHSMFInstance().openResourceAsStream("lots-of-recipients.msg");
- POIFSFileSystem srcFileSystem = new POIFSFileSystem(inputStream);
- POIFSFileSystem destFileSystem = new POIFSFileSystem()) {
-
- copyAllEntries(srcFileSystem.getRoot(), destFileSystem.getRoot());
-
- File file = File.createTempFile("npoi", ".dat");
- try (OutputStream outputStream = new FileOutputStream(file)) {
- destFileSystem.writeFilesystem(outputStream);
- }
-
- assertTrue(file.delete());
- if (i % 10 == 0) System.out.print(".");
- }
- }
-
- System.out.println();
- System.out.println("NPOI took: " + (System.currentTimeMillis() - start));
-
- System.out.println();
- System.out.println();
- }
-
- private static void copyAllEntries(DirectoryEntry srcDirectory, DirectoryEntry destDirectory) throws IOException {
- Iterator iterator = srcDirectory.getEntries();
-
- while (iterator.hasNext()) {
- Entry entry = iterator.next();
-
- if (entry.isDirectoryEntry()) {
- DirectoryEntry childDest = destDirectory.createDirectory(entry.getName());
- copyAllEntries((DirectoryEntry) entry, childDest);
-
- } else {
- DocumentEntry srcEntry = (DocumentEntry) entry;
-
- try (InputStream inputStream = new DocumentInputStream(srcEntry)) {
- destDirectory.createDocument(entry.getName(), inputStream);
- }
- }
- }
- }
-
-}
diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java
deleted file mode 100644
index 29ed3001f0..0000000000
--- a/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.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.poifs.filesystem;
-
-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 java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.apache.poi.poifs.property.DirectoryProperty;
-import org.apache.poi.poifs.property.Property;
-import org.junit.jupiter.api.Test;
-
-/**
- * Verify the order of entries DirectoryProperty .
- *
- * In particular it is important to serialize ROOT._VBA_PROJECT_CUR.VBA node.
- * See bug 39234 in bugzilla. Thanks to Bill Seddon for providing the solution.
- *
- */
-final class TestPropertySorter {
-
- //the correct order of entries in the test file
- private static final String[] _entries = {
- "dir", "JML", "UTIL", "Loader", "Sheet1", "Sheet2", "Sheet3",
- "__SRP_0", "__SRP_1", "__SRP_2", "__SRP_3", "__SRP_4", "__SRP_5",
- "ThisWorkbook", "_VBA_PROJECT",
- };
-
- private static POIFSFileSystem openSampleFS() {
- InputStream is = HSSFTestDataSamples.openSampleFileStream("39234.xls");
- try {
- return new POIFSFileSystem(is);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Test sorting of properties in DirectoryProperty
- */
- @Test
- void testSortProperties() throws IOException {
- POIFSFileSystem fs = openSampleFS();
- Property[] props = getVBAProperties(fs);
-
- assertEquals(_entries.length, props.length);
-
- // (1). See that there is a problem with the old case-sensitive property comparator
- Arrays.sort(props, TestPropertySorter::oldCaseSensitivePropertyCompareTo);
-
- String exp = String.join("", _entries);
- String actOld = Stream.of(props).map(Property::getName).collect(Collectors.joining());
-
- assertNotEquals("expected old case-sensitive property comparator to return properties in wrong order", exp, actOld);
-
- // (2) Verify that the fixed property comparator works right
- Arrays.sort(props, new DirectoryProperty.PropertyComparator());
- String[] actNew = Stream.of(props).map(Property::getName).toArray(String[]::new);
-
- assertArrayEquals(_entries, actNew);
- }
-
- private static int oldCaseSensitivePropertyCompareTo(Property o1, Property o2) {
- String name1 = o1.getName();
- String name2 = o2.getName();
- int result = name1.length() - name2.length();
- return (result != 0) ? result : name1.compareTo(name2);
- }
-
- /**
- * Serialize file system and verify that the order of properties is the same as in the original file.
- */
- @Test
- void testSerialization() throws IOException {
- POIFSFileSystem fs = openSampleFS();
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- fs.writeFilesystem(out);
- out.close();
- InputStream is = new ByteArrayInputStream(out.toByteArray());
- fs = new POIFSFileSystem(is);
- is.close();
- Property[] props = getVBAProperties(fs);
- Arrays.sort(props, new DirectoryProperty.PropertyComparator());
-
- String[] act = Stream.of(props).map(Property::getName).toArray(String[]::new);
- assertArrayEquals(_entries, act);
- }
-
- /**
- * @return array of properties read from ROOT._VBA_PROJECT_CUR.VBA node
- */
- private Property[] getVBAProperties(POIFSFileSystem fs) throws IOException {
- String _VBA_PROJECT_CUR = "_VBA_PROJECT_CUR";
- String VBA = "VBA";
-
- DirectoryEntry root = fs.getRoot();
- DirectoryEntry vba_project = (DirectoryEntry)root.getEntry(_VBA_PROJECT_CUR);
-
- DirectoryNode vba = (DirectoryNode)vba_project.getEntry(VBA);
- DirectoryProperty p = (DirectoryProperty)vba.getProperty();
-
- List lst = new ArrayList<>();
- for (Iterator it = p.getChildren(); it.hasNext();){
- Property ch = it.next();
- lst.add(ch);
- }
- return lst.toArray(new Property[ 0 ]);
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java b/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java
deleted file mode 100644
index 57e9ed814e..0000000000
--- a/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java
+++ /dev/null
@@ -1,320 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.macros;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.StringUtil;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-import static org.apache.poi.POITestCase.assertContains;
-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.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-class TestVBAMacroReader {
- private static final Map expectedMacroContents;
-
- private static String readVBA(POIDataSamples poiDataSamples) {
- File macro = poiDataSamples.getFile("SimpleMacro.vba");
- final byte[] bytes;
- try {
- try (FileInputStream stream = new FileInputStream(macro)) {
- bytes = IOUtils.toByteArray(stream);
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- String testMacroContents = new String(bytes, StringUtil.UTF8);
-
- if (! testMacroContents.startsWith("Sub ")) {
- throw new IllegalArgumentException("Not a macro");
- }
-
- return testMacroContents.substring(testMacroContents.indexOf("()")+3);
- }
-
- static {
- final Map _expectedMacroContents = new HashMap<>();
- final POIDataSamples[] dataSamples = {
- POIDataSamples.getSpreadSheetInstance(),
- POIDataSamples.getSlideShowInstance(),
- POIDataSamples.getDocumentInstance(),
- POIDataSamples.getDiagramInstance()
- };
- for (POIDataSamples sample : dataSamples) {
- _expectedMacroContents.put(sample, readVBA(sample));
- }
- expectedMacroContents = Collections.unmodifiableMap(_expectedMacroContents);
- }
-
- //////////////////////////////// From Stream /////////////////////////////
- @Test
- void HSSFFromStream() throws Exception {
- fromStream(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xls");
- }
- @Test
- void XSSFFromStream() throws Exception {
- fromStream(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xlsm");
- }
- @Disabled("bug 59302: Found 0 macros; See org.apache.poi.hslf.usermodel.TestBugs.getMacrosFromHSLF()" +
- "for an example of how to get macros out of ppt. TODO: make integration across file formats more elegant")
- @Test
- void HSLFFromStream() throws Exception {
- fromStream(POIDataSamples.getSlideShowInstance(), "SimpleMacro.ppt");
- }
- @Test
- void XSLFFromStream() throws Exception {
- fromStream(POIDataSamples.getSlideShowInstance(), "SimpleMacro.pptm");
- }
- @Test
- void HWPFFromStream() throws Exception {
- fromStream(POIDataSamples.getDocumentInstance(), "SimpleMacro.doc");
- }
- @Test
- void XWPFFromStream() throws Exception {
- fromStream(POIDataSamples.getDocumentInstance(), "SimpleMacro.docm");
- }
- @Disabled("Found 0 macros")
- @Test
- void HDGFFromStream() throws Exception {
- fromStream(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd");
- }
- @Test
- void XDGFFromStream() throws Exception {
- fromStream(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsdm");
- }
-
- //////////////////////////////// From File /////////////////////////////
- @Test
- void HSSFFromFile() throws Exception {
- fromFile(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xls");
- }
- @Test
- void XSSFFromFile() throws Exception {
- fromFile(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xlsm");
- }
- @Disabled("bug 59302: Found 0 macros; See org.apache.poi.hslf.usermodel.TestBugs.getMacrosFromHSLF()" +
- "for an example of how to get macros out of ppt. TODO: make integration across file formats more elegant")
- @Test
- void HSLFFromFile() throws Exception {
- fromFile(POIDataSamples.getSlideShowInstance(), "SimpleMacro.ppt");
- }
- @Test
- void XSLFFromFile() throws Exception {
- fromFile(POIDataSamples.getSlideShowInstance(), "SimpleMacro.pptm");
- }
- @Test
- void HWPFFromFile() throws Exception {
- fromFile(POIDataSamples.getDocumentInstance(), "SimpleMacro.doc");
- }
- @Test
- void XWPFFromFile() throws Exception {
- fromFile(POIDataSamples.getDocumentInstance(), "SimpleMacro.docm");
- }
- @Disabled("Found 0 macros")
- @Test
- void HDGFFromFile() throws Exception {
- fromFile(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd");
- }
- @Test
- void XDGFFromFile() throws Exception {
- fromFile(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsdm");
- }
-
- //////////////////////////////// From POIFS /////////////////////////////
- @Test
- void HSSFFromPOIFS() throws Exception {
- fromPOIFS(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xls");
- }
- @Disabled("bug 59302: Found 0 macros")
- @Test
- void HSLFFromPOIFS() throws Exception {
- fromPOIFS(POIDataSamples.getSlideShowInstance(), "SimpleMacro.ppt");
- }
- @Test
- void HWPFFromPOIFS() throws Exception {
- fromPOIFS(POIDataSamples.getDocumentInstance(), "SimpleMacro.doc");
- }
- @Disabled("Found 0 macros")
- @Test
- void HDGFFromPOIFS() throws Exception {
- fromPOIFS(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd");
- }
-
- private void fromFile(POIDataSamples dataSamples, String filename) throws IOException {
- File f = dataSamples.getFile(filename);
- try (VBAMacroReader r = new VBAMacroReader(f)) {
- assertMacroContents(dataSamples, r);
- }
- }
-
- private void fromStream(POIDataSamples dataSamples, String filename) throws IOException {
- try (InputStream fis = dataSamples.openResourceAsStream(filename)) {
- try (VBAMacroReader r = new VBAMacroReader(fis)) {
- assertMacroContents(dataSamples, r);
- }
- }
- }
-
- private void fromPOIFS(POIDataSamples dataSamples, String filename) throws IOException {
- File f = dataSamples.getFile(filename);
- try (POIFSFileSystem fs = new POIFSFileSystem(f)) {
- try (VBAMacroReader r = new VBAMacroReader(fs)) {
- assertMacroContents(dataSamples, r);
- }
- }
- }
-
- private void assertMacroContents(POIDataSamples samples, VBAMacroReader r) throws IOException {
- assertNotNull(r);
- Map contents = r.readMacroModules();
- assertNotNull(contents);
- assertFalse(contents.isEmpty(), "Found 0 macros");
- /*
- assertEquals(5, contents.size());
-
- // Check the ones without scripts
- String[] noScripts = new String[] { "ThisWorkbook",
- "Sheet1", "Sheet2", "Sheet3" };
- for (String entry : noScripts) {
- assertTrue(entry, contents.containsKey(entry));
-
- String content = contents.get(entry);
- assertContains(content, "Attribute VB_Exposed = True");
- assertContains(content, "Attribute VB_Customizable = True");
- assertContains(content, "Attribute VB_TemplateDerived = False");
- assertContains(content, "Attribute VB_GlobalNameSpace = False");
- assertContains(content, "Attribute VB_Exposed = True");
- }
- */
-
- // Check the script one
- assertContains(contents, "Module1");
- Module module = contents.get("Module1");
- assertNotNull(module);
- String content = module.getContent();
- assertContains(content, "Attribute VB_Name = \"Module1\"");
- //assertContains(content, "Attribute TestMacro.VB_Description = \"This is a test macro\"");
-
- assertEquals(Module.ModuleType.Module, module.geModuleType());
- // And the macro itself
- String testMacroNoSub = expectedMacroContents.get(samples);
- assertContains(content, testMacroNoSub);
- }
-
- @Test
- void bug59830() throws IOException {
- //test file is "609751.xls" in govdocs1
- File f = POIDataSamples.getSpreadSheetInstance().getFile("59830.xls");
- VBAMacroReader r = new VBAMacroReader(f);
- Map macros = r.readMacros();
- assertEquals(29, macros.size());
- assertNotNull(macros.get("Module20"));
- assertContains(macros.get("Module20"), "here start of superscripting");
- r.close();
- }
-
- @Test
- void bug59858() throws IOException {
- File f = POIDataSamples.getSpreadSheetInstance().getFile("59858.xls");
- VBAMacroReader r = new VBAMacroReader(f);
- Map macros = r.readMacros();
- assertEquals(11, macros.size());
- assertNotNull(macros.get("Sheet4"));
- assertContains(macros.get("Sheet4"), "intentional constituent");
- r.close();
- }
-
- @Test
- void bug60158() throws IOException {
- File f = POIDataSamples.getDocumentInstance().getFile("60158.docm");
- VBAMacroReader r = new VBAMacroReader(f);
- Map macros = r.readMacros();
- assertEquals(2, macros.size());
- assertNotNull(macros.get("NewMacros"));
- assertContains(macros.get("NewMacros"), "' dirty");
- r.close();
- }
-
- @Test
- void bug60273() throws IOException {
- //test file derives from govdocs1 147240.xls
- File f = POIDataSamples.getSpreadSheetInstance().getFile("60273.xls");
- VBAMacroReader r = new VBAMacroReader(f);
- Map macros = r.readMacros();
- assertEquals(2, macros.size());
- assertNotNull(macros.get("Module1"));
- assertContains(macros.get("Module1"), "9/8/2004");
- r.close();
- }
-
- @Test
- void bug60279() throws IOException {
- File f = POIDataSamples.getDocumentInstance().getFile("60279.doc");
- VBAMacroReader r = new VBAMacroReader(f);
- Map macros = r.readMacros();
- assertEquals(1, macros.size());
- String content = macros.get("ThisDocument");
- assertContains(content, "Attribute VB_Base = \"1Normal.ThisDocument\"");
- assertContains(content, "Attribute VB_Customizable = True");
- r.close();
- }
-
- @Test
- void bug62624() throws IOException {
- //macro comes from Common Crawl: HRLOXHGMGLFIJQQU27RIWXOARRHAAAAS
- File f = POIDataSamples.getSpreadSheetInstance().getFile("62624.bin");
- VBAMacroReader r = new VBAMacroReader(f);
-
- Map macros = r.readMacroModules();
- assertEquals(13, macros.size());
- assertNotNull(macros.get("M\u00F3dulo1"));
- assertContains(macros.get("M\u00F3dulo1").getContent(), "Calcula_tributos");
- assertEquals(Module.ModuleType.Module, macros.get("M\u00F3dulo1").geModuleType());
- r.close();
- }
-
- @Test
- void bug62625() throws IOException {
- //macro comes from Common Crawl: 4BZ22N5QG5R2SUU2MNN47PO7VBQLNYIQ
- //A REFERENCE_NAME can sometimes only have an ascii string without
- //a reserved byte followed by the unicode string.
- //See https://github.com/decalage2/oletools/blob/master/oletools/olevba.py#L1516
- //and https://github.com/decalage2/oletools/pull/135 from (@c1fe)
-
-
- File f = POIDataSamples.getSpreadSheetInstance().getFile("62625.bin");
- VBAMacroReader r = new VBAMacroReader(f);
-
- Map macros = r.readMacroModules();
- assertEquals(20, macros.size());
- r.close();
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java b/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java
deleted file mode 100644
index 3845ce75fe..0000000000
--- a/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java
+++ /dev/null
@@ -1,249 +0,0 @@
-
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.nio;
-
-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 java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.TempFile;
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for the datasource implementations
- */
-class TestDataSource {
- private static final POIDataSamples data = POIDataSamples.getPOIFSInstance();
-
- @Test
- void testFile() throws Exception {
- File f = data.getFile("Notes.ole2");
-
- try (FileBackedDataSource ds = new FileBackedDataSource(f)) {
- checkDataSource(ds, false);
- }
-
- // try a second time
- try (FileBackedDataSource ds = new FileBackedDataSource(f)) {
- checkDataSource(ds, false);
- }
- }
-
- @Test
- void testFileWritable() throws Exception {
- File temp = TempFile.createTempFile("TestDataSource", ".test");
- try {
- writeDataToFile(temp);
-
- try (FileBackedDataSource ds = new FileBackedDataSource(temp, false)) {
- checkDataSource(ds, true);
- }
-
- // try a second time
- try (FileBackedDataSource ds = new FileBackedDataSource(temp, false)) {
- checkDataSource(ds, true);
- }
-
- writeDataToFile(temp);
- } finally {
- assertTrue(temp.exists());
- assertTrue(temp.delete(), "Could not delete file " + temp);
- }
- }
-
-
- @Test
- void testRewritableFile() throws Exception {
- File temp = TempFile.createTempFile("TestDataSource", ".test");
- try {
- writeDataToFile(temp);
-
- ;
- try (FileBackedDataSource ds = new FileBackedDataSource(temp, true)) {
- ByteBuffer buf = ds.read(0, 10);
- assertNotNull(buf);
- buf = ds.read(8, 0x400);
- assertNotNull(buf);
- }
-
- // try a second time
- ;
- try (FileBackedDataSource ds = new FileBackedDataSource(temp, true)) {
- ByteBuffer buf = ds.read(0, 10);
- assertNotNull(buf);
- buf = ds.read(8, 0x400);
- assertNotNull(buf);
- }
-
- writeDataToFile(temp);
- } finally {
- assertTrue(temp.exists());
- assertTrue(temp.delete());
- }
- }
-
- private void writeDataToFile(File temp) throws IOException {
- try (OutputStream str = new FileOutputStream(temp)) {
- try (InputStream in = data.openResourceAsStream("Notes.ole2")) {
- IOUtils.copy(in, str);
- }
- }
- }
-
- private void checkDataSource(FileBackedDataSource ds, boolean writeable) throws IOException {
- assertEquals(writeable, ds.isWriteable());
- assertNotNull(ds.getChannel());
-
- // rewriting changes the size
- if (writeable) {
- assertTrue(ds.size() == 8192 || ds.size() == 8198, "Had: " + ds.size());
- } else {
- assertEquals(8192, ds.size());
- }
-
- // Start of file
- ByteBuffer bs;
- bs = ds.read(4, 0);
- assertEquals(4, bs.capacity());
- assertEquals(0, bs.position());
- assertEquals(0xd0 - 256, bs.get(0));
- assertEquals(0xcf - 256, bs.get(1));
- assertEquals(0x11, bs.get(2));
- assertEquals(0xe0 - 256, bs.get(3));
- assertEquals(0xd0 - 256, bs.get());
- assertEquals(0xcf - 256, bs.get());
- assertEquals(0x11, bs.get());
- assertEquals(0xe0 - 256, bs.get());
-
- // Mid way through
- bs = ds.read(8, 0x400);
- assertEquals(8, bs.capacity());
- assertEquals(0, bs.position());
- assertEquals((byte) 'R', bs.get(0));
- assertEquals(0, bs.get(1));
- assertEquals((byte) 'o', bs.get(2));
- assertEquals(0, bs.get(3));
- assertEquals((byte) 'o', bs.get(4));
- assertEquals(0, bs.get(5));
- assertEquals((byte) 't', bs.get(6));
- assertEquals(0, bs.get(7));
-
- // Can go to the end, but not past it
- bs = ds.read(8, 8190);
- // TODO How best to warn of a short read?
- assertEquals(0, bs.position());
-
- // Can't go off the end
- assertThrows(IndexOutOfBoundsException.class, () -> ds.read(4, ds.size()),
- "Shouldn't be able to read off the end of the file");
- }
-
- @Test
- void testByteArray() {
- byte[] data = new byte[256];
- byte b;
- for (int i = 0; i < data.length; i++) {
- b = (byte) i;
- data[i] = b;
- }
-
- ByteArrayBackedDataSource ds = new ByteArrayBackedDataSource(data);
-
- // Start
- ByteBuffer bs;
- bs = ds.read(4, 0);
- assertEquals(0, bs.position());
- assertEquals(0x00, bs.get());
- assertEquals(0x01, bs.get());
- assertEquals(0x02, bs.get());
- assertEquals(0x03, bs.get());
-
- // Middle
- bs = ds.read(4, 100);
- assertEquals(100, bs.position());
- assertEquals(100, bs.get());
- assertEquals(101, bs.get());
- assertEquals(102, bs.get());
- assertEquals(103, bs.get());
-
- // End
- bs = ds.read(4, 252);
- assertEquals(-4, bs.get());
- assertEquals(-3, bs.get());
- assertEquals(-2, bs.get());
- assertEquals(-1, bs.get());
-
- // Off the end
- bs = ds.read(4, 254);
- assertEquals(-2, bs.get());
- assertEquals(-1, bs.get());
- assertThrows(BufferUnderflowException.class, bs::get, "Shouldn't be able to read off the end");
-
- // Past the end
- assertThrows(IndexOutOfBoundsException.class, () -> ds.read(4, 256), "Shouldn't be able to read off the end");
-
-
- // Overwrite
- bs = ByteBuffer.allocate(4);
- bs.put(0, (byte) -55);
- bs.put(1, (byte) -54);
- bs.put(2, (byte) -53);
- bs.put(3, (byte) -52);
-
- assertEquals(256, ds.size());
- ds.write(bs, 40);
- assertEquals(256, ds.size());
- bs = ds.read(4, 40);
-
- assertEquals(-55, bs.get());
- assertEquals(-54, bs.get());
- assertEquals(-53, bs.get());
- assertEquals(-52, bs.get());
-
- // Append
- bs = ByteBuffer.allocate(4);
- bs.put(0, (byte) -55);
- bs.put(1, (byte) -54);
- bs.put(2, (byte) -53);
- bs.put(3, (byte) -52);
-
- assertEquals(256, ds.size());
- ds.write(bs, 256);
- assertEquals(260, ds.size());
-
- bs = ds.read(4, 256);
- assertEquals(256, bs.position());
- assertEquals(-55, bs.get());
- assertEquals(-54, bs.get());
- assertEquals(-53, bs.get());
- assertEquals(-52, bs.get());
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/property/LocalProperty.java b/src/testcases/org/apache/poi/poifs/property/LocalProperty.java
deleted file mode 100644
index f578129b68..0000000000
--- a/src/testcases/org/apache/poi/poifs/property/LocalProperty.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.property;
-
-class LocalProperty
- extends Property
-{
-
- /**
- * Constructor LocalProperty
- *
- * @param index
- */
-
- LocalProperty(int index)
- {
- super();
- setName("foo" + index);
- setIndex(index);
- }
-
- /**
- * Method preWrite
- */
-
- @Override
- protected void preWrite()
- {
- }
-
- /**
- * Method isDirectory
- *
- * @return false
- */
-
- @Override
- public boolean isDirectory()
- {
- return false;
- }
-} // end package-scope class LocalProperty
-
diff --git a/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java b/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java
deleted file mode 100644
index 49b6553012..0000000000
--- a/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java
+++ /dev/null
@@ -1,273 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.property;
-
-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 java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test DirectoryProperty functionality
- */
-final class TestDirectoryProperty {
- private DirectoryProperty _property;
- private byte[] _testblock;
-
- /**
- * Test constructing DirectoryProperty
- */
- @Test
- void testConstructor() throws IOException {
- createBasicDirectoryProperty();
- verifyProperty();
- }
-
- /**
- * Test pre-write functionality
- */
- @Test
- void testPreWrite() throws IOException {
- createBasicDirectoryProperty();
- _property.preWrite();
-
- // shouldn't change anything at all
- verifyProperty();
- verifyChildren(0);
-
- // now try adding 1 property
- createBasicDirectoryProperty();
- _property.addChild(new LocalProperty(1));
- _property.preWrite();
-
- // update children index
- _testblock[ 0x4C ] = 1;
- _testblock[ 0x4D ] = 0;
- _testblock[ 0x4E ] = 0;
- _testblock[ 0x4F ] = 0;
- verifyProperty();
- verifyChildren(1);
-
- // now try adding 2 properties
- createBasicDirectoryProperty();
- _property.addChild(new LocalProperty(1));
- _property.addChild(new LocalProperty(2));
- _property.preWrite();
-
- // update children index
- _testblock[ 0x4C ] = 2;
- _testblock[ 0x4D ] = 0;
- _testblock[ 0x4E ] = 0;
- _testblock[ 0x4F ] = 0;
- verifyProperty();
- verifyChildren(2);
-
- // beat on the children allocation code
- for (int count = 1; count < 100; count++)
- {
- createBasicDirectoryProperty();
- for (int j = 1; j < (count + 1); j++)
- {
- _property.addChild(new LocalProperty(j));
- }
- _property.preWrite();
- verifyChildren(count);
- }
- }
-
- private void verifyChildren(int count) {
- Iterator iter = _property.getChildren();
- List children = new ArrayList<>();
-
- while (iter.hasNext())
- {
- children.add(iter.next());
- }
- assertEquals(count, children.size());
- if (count != 0)
- {
- boolean[] found = new boolean[ count ];
-
- found[ _property.getChildIndex() - 1 ] = true;
- int total_found = 1;
-
- Arrays.fill(found, false);
- iter = children.iterator();
- while (iter.hasNext())
- {
- Property child = iter.next();
- Child next = child.getNextChild();
-
- if (next != null)
- {
- int index = (( Property ) next).getIndex();
-
- if (index != -1)
- {
- assertFalse(found[index - 1]);
- found[ index - 1 ] = true;
- total_found++;
- }
- }
- Child previous = child.getPreviousChild();
-
- if (previous != null)
- {
- int index = (( Property ) previous).getIndex();
-
- if (index != -1)
- {
- assertFalse(found[index - 1]);
- found[ index - 1 ] = true;
- total_found++;
- }
- }
- }
- assertEquals(count, total_found);
- }
- }
-
- private void createBasicDirectoryProperty() {
- final String name = "MyDirectory";
-
- _property = new DirectoryProperty(name);
- _testblock = new byte[ 128 ];
- int index = 0;
-
- for (; index < 0x40; index++)
- {
- _testblock[ index ] = ( byte ) 0;
- }
- int limit = name.length();
-
- _testblock[ index++ ] = ( byte ) (2 * (limit + 1));
- _testblock[ index++ ] = ( byte ) 0;
- _testblock[ index++ ] = ( byte ) 1;
- _testblock[ index++ ] = ( byte ) 1;
- for (; index < 0x50; index++)
- {
- _testblock[ index ] = ( byte ) 0xff;
- }
- for (; index < 0x80; index++)
- {
- _testblock[ index ] = ( byte ) 0;
- }
- byte[] name_bytes = name.getBytes(LocaleUtil.CHARSET_1252);
-
- for (index = 0; index < limit; index++)
- {
- _testblock[ index * 2 ] = name_bytes[ index ];
- }
- }
-
- private void verifyProperty() throws IOException {
- ByteArrayOutputStream stream = new ByteArrayOutputStream(512);
-
- _property.writeData(stream);
- byte[] output = stream.toByteArray();
-
- assertEquals(_testblock.length, output.length);
- for (int j = 0; j < _testblock.length; j++)
- {
- assertEquals(_testblock[ j ], output[ j ], "mismatch at offset " + j);
- }
- }
-
- @Test
- void testAddChild() throws IOException {
- createBasicDirectoryProperty();
- _property.addChild(new LocalProperty(1));
- _property.addChild(new LocalProperty(2));
- assertThrows(IOException.class, () -> _property.addChild(new LocalProperty(1)));
- assertThrows(IOException.class, () -> _property.addChild(new LocalProperty(2)));
- _property.addChild(new LocalProperty(3));
- }
-
- @Test
- void testDeleteChild() throws IOException {
- createBasicDirectoryProperty();
- Property p1 = new LocalProperty(1);
-
- _property.addChild(p1);
- assertThrows(IOException.class, () -> _property.addChild(new LocalProperty(1)));
- assertTrue(_property.deleteChild(p1));
- assertFalse(_property.deleteChild(p1));
- _property.addChild(new LocalProperty(1));
- }
-
- @Test
- void testChangeName() throws IOException {
- createBasicDirectoryProperty();
- Property p1 = new LocalProperty(1);
- String originalName = p1.getName();
-
- _property.addChild(p1);
- assertTrue(_property.changeName(p1, "foobar"));
- assertEquals("foobar", p1.getName());
- assertFalse(_property.changeName(p1, "foobar"));
- assertEquals("foobar", p1.getName());
- Property p2 = new LocalProperty(1);
-
- _property.addChild(p2);
- assertFalse(_property.changeName(p1, originalName));
- assertTrue(_property.changeName(p2, "foo"));
- assertTrue(_property.changeName(p1, originalName));
- }
-
- @Test
- void testReadingConstructor() {
- String[] input = {
- "42 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "16 00 01 01 FF FF FF FF FF FF FF FF 02 00 00 00 20 08 02 00 00 00 00 00 C0 00 00 00 00 00 00 46",
- "00 00 00 00 00 00 00 00 00 00 00 00 C0 5C E8 23 9E 6B C1 01 FE FF FF FF 00 00 00 00 00 00 00 00",
- };
- verifyReadingProperty(0, RawDataUtil.decode(input), 0, "Boot Entry");
- }
-
- private static void verifyReadingProperty(int index, byte[] input, int offset, String name) {
- DirectoryProperty property = new DirectoryProperty(index, input, offset);
- ByteArrayOutputStream stream = new ByteArrayOutputStream(128);
- byte[] expected = Arrays.copyOfRange(input, offset, offset+128);
- try {
- property.writeData(stream);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- byte[] output = stream.toByteArray();
-
- assertEquals(128, output.length);
- for (int j = 0; j < 128; j++) {
- assertEquals(expected[j], output[j], "mismatch at offset " + j);
- }
- assertEquals(index, property.getIndex());
- assertEquals(name, property.getName());
- assertFalse(property.getChildren().hasNext());
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java b/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java
deleted file mode 100644
index 17145cd9db..0000000000
--- a/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.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.poifs.property;
-
-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.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.poi.hpsf.DocumentSummaryInformation;
-import org.apache.poi.hpsf.SummaryInformation;
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test DocumentProperty functionality
- */
-final class TestDocumentProperty {
-
- @Test
- void testConstructor() throws IOException {
- // test with short name, small file
- verifyProperty("foo", 1234);
-
- // test with just long enough name, small file
- verifyProperty("A.really.long.long.long.name123", 2345);
-
- // test with longer name, just small enough file
- verifyProperty("A.really.long.long.long.name1234", 4095);
-
- // test with just long enough file
- verifyProperty("A.really.long.long.long.name123", 4096);
- }
-
- @Test
- void testReadingConstructor() throws IOException {
- String[] hexData = {
- "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "16 00 05 01 FF FF FF FF FF FF FF FF 02 00 00 00 20 08 02 00 00 00 00 00 C0 00 00 00 00 00 00 46",
- "00 00 00 00 00 00 00 00 00 00 00 00 C0 5C E8 23 9E 6B C1 01 FE FF FF FF 00 00 00 00 00 00 00 00",
- "57 00 6F 00 72 00 6B 00 62 00 6F 00 6F 00 6B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "12 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00",
- "05 00 53 00 75 00 6D 00 6D 00 61 00 72 00 79 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00",
- "69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "28 00 02 01 01 00 00 00 03 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 10 00 00 00 00 00 00",
- "05 00 44 00 6F 00 63 00 75 00 6D 00 65 00 6E 00 74 00 53 00 75 00 6D 00 6D 00 61 00 72 00 79 00",
- "49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00",
- "38 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 10 00 00 00 00 00 00",
- };
- byte[] input = RawDataUtil.decode(hexData);
-
- verifyReadingProperty(1, input, 128, "Workbook");
- verifyReadingProperty(2, input, 256, SummaryInformation.DEFAULT_STREAM_NAME);
- verifyReadingProperty(3, input, 384, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
- }
-
- private void verifyReadingProperty(int index, byte[] input, int offset, String name)
- throws IOException {
- DocumentProperty property = new DocumentProperty(index, input,
- offset);
- ByteArrayOutputStream stream = new ByteArrayOutputStream(128);
- byte[] expected = Arrays.copyOfRange(input, offset, offset+128);
- property.writeData(stream);
- byte[] output = stream.toByteArray();
-
- assertEquals(128, output.length);
- for (int j = 0; j < 128; j++) {
- assertEquals(expected[ j ], output[ j ], "mismatch at offset " + j);
- }
- assertEquals(index, property.getIndex());
- assertEquals(name, property.getName());
- }
-
- private void verifyProperty(String name, int size) throws IOException {
- DocumentProperty property = new DocumentProperty(name, size);
-
- if (size >= 4096)
- {
- assertFalse(property.shouldUseSmallBlocks());
- }
- else
- {
- assertTrue(property.shouldUseSmallBlocks());
- }
- byte[] testblock = new byte[ 128 ];
- int index = 0;
-
- for (; index < 0x40; index++)
- {
- testblock[ index ] = ( byte ) 0;
- }
- int limit = Math.min(31, name.length());
-
- testblock[ index++ ] = ( byte ) (2 * (limit + 1));
- testblock[ index++ ] = ( byte ) 0;
- testblock[ index++ ] = ( byte ) 2;
- testblock[ index++ ] = ( byte ) 1;
- for (; index < 0x50; index++)
- {
- testblock[ index ] = ( byte ) 0xFF;
- }
- for (; index < 0x78; index++)
- {
- testblock[ index ] = ( byte ) 0;
- }
- int sz = size;
-
- testblock[ index++ ] = ( byte ) sz;
- sz /= 256;
- testblock[ index++ ] = ( byte ) sz;
- sz /= 256;
- testblock[ index++ ] = ( byte ) sz;
- sz /= 256;
- testblock[ index++ ] = ( byte ) sz;
- for (; index < 0x80; index++)
- {
- testblock[ index ] = ( byte ) 0x0;
- }
- byte[] name_bytes = name.getBytes(LocaleUtil.CHARSET_1252);
-
- for (index = 0; index < limit; index++)
- {
- testblock[ index * 2 ] = name_bytes[ index ];
- }
- ByteArrayOutputStream stream = new ByteArrayOutputStream(512);
-
- property.writeData(stream);
- byte[] output = stream.toByteArray();
-
- assertEquals(testblock.length, output.length);
- for (int j = 0; j < testblock.length; j++)
- {
- assertEquals(testblock[ j ], output[ j ], "mismatch at offset " + j);
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java b/src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java
deleted file mode 100644
index 6d67310ff6..0000000000
--- a/src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.property;
-
-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.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test PropertyFactory functionality
- */
-final class TestPropertyFactory {
-
- @Test
- void testConvertToProperties() throws IOException {
-
- // real data from a real file!
- String hexData =
- "H4sIAAAAAAAAANWZ624TRxTHxymXcm2ahjRNUrJAoCGESxFCCPEB22lSqoRECbGE+slxNvEqcYx2bUQ/lUfphz5BnwBegw88" +
- "Ac8A/M/ZWe/E3svMbKjEseIdbyz/zpk5cy6z66KNV0c44jdxgKsv/hImMiaOi09SzuV8983Sv+8/uG9L32D8+Gx4bwH0huiK" +
- "lnCZ7+COi2tdeGJfBLn8y0KUPimS9J1//r7+7fPa29Ib51e+qv+rwmIXtA54bWjgiKf4RNroyZQGv18+4nvzqfwF/vSl+afl" +
- "eBm0gOd9A6OX4G4b6eAU5EckRyzyihPfRMYK8/v9r4aRjzkJ1yNPdPwviX9Mjiuwv4FXEzoE0vvrmAfyQ9Jqi7VJl9mC/EH7" +
- "l/nOnuZKOEfOj2fgGWLRixwvvGbJP5HKL+PTNla/o/NT4qIGP4o7r39/OBB/NrHqtMIqlyz3ZQTME1v/q8hxlb28w7wGs5d4" +
- "Jly+E0elJ3jfwbhf7mrwI7uT7I9XOyL4WIuYnG9/qcf/KeU7Pf5/6xl8GgWYAx/kFwb8IYpB5IdCd/4p9pyS4w2mu7z3yzIX" +
- "OLwq25rxd6g0guucAf8M/uL9F9lfhf/5rMEBZkG3CpgCf5L10OdT6j8px6ugdhDl2rgecO4JfZ8y0b6SidIqgXnwr+L6iwGf" +
- "6pRLcryC33+FtW5xDKAsSLWHfg00Af4orsMG/PP4O57Dd8Qa70GPPSFdZuF/47heMeB/J5LWXyfaDsoo+BdYD33+sMLfgN1b" +
- "StQ3lRHM/y1cpw343yt82mktvDx4WNCLdjXWpasxG9j/xvF3ROEvguRz/WM//6b8Hw7xNzH3FPXJ18Laz5PZMJqPrCp81sL+" +
- "0Uy+WR6YA5/8eULor/9H5XsLHHm2OAbHXuiBuCt1oZzcYE3aCZXYXfDJny4Z8C8o9le47vM44wacBcz8YMpi/ccU/ibXmD5H" +
- "233OPcuszR7rUpcxeY27hIC9YlfWx6E8suCr81/m36MKJDDuvUjGLfg/KvarVbaDFd7JtHZQ5iz44wq/jPmuKhk/v+M9LDb7" +
- "X53/qtzh5Nu01+qGujiF+U2uc7d7Ga8h/aHOcx/dbXFl3BnoSu5j/80IqgP09x/VidH8JzNDP3gOpsu6pcushf0TQvU/l6vu" +
- "dVxbsvrPtniAX7ouuA/Qtn9S4YfRtt7rvTyugcNqTEeXe+DflGxd/pQBPy8TU/2HHkzcNrD/Z4X/DDNfwy607z+GSneEmf0X" +
- "RVb8/4PvEH+nl3nSdbllkX+nxeH6y+fzB6pDdm3qjxLFU5pTXb4jVP8n+7qyBgr3XY118bRWwWb/Ua5ek+NVMJoy+tMe3FH6" +
- "EBeVed4pwAzsp3qeaipdPtXqcf1Z534ryr9xx72Ie25KVIzlgYX9M0Z8Opd7Jc8FB3fjQ9h/Q4R7Wpd/1Yif3Zfes7CfevWo" +
- "/wzjLvnbnnHuJRkumP9U/6uyHj5nHZ97QZfPZNoZFci8BZ965Tj/+fz70Sls1A9FNVmeXC5oP+W/XX4C4Ymk86a8aHxH5/xJ" +
- "nvsknf+sc9zt8Kw3ZIbrXwmKytdkb97fDd0veP5ZBi889QstjM5idFeh6Pkv2f+SOV1e/xXej2GUic9E0/V58L/ww8js9qKA" +
- "Gn+K8Vc49xY5/ynGj5//hJ5XMX7+ZseflONV3m0V0Jvse5R/V/GuK0Xtj8+f1nrVd5nPBJvKs4is/suOPyzHSxz/uui4Y26b" +
- "d35wdOffMu48fvfnQPyJn7894fqvK/1A1SvrSZAOP8n+6PlHGkc3F9o+f9T8eS0x5R+1fM38zxmfK1AAIAAA";
-
- final byte[] testdata = RawDataUtil.decompress(hexData);
- final ByteArrayInputStream stream = new ByteArrayInputStream(testdata);
- final List properties = new ArrayList<>();
-
- final byte[] buf = new byte[512];
- for (int readBytes; (readBytes = stream.read(buf)) != -1; ) {
- byte[] bbuf = buf;
- if (readBytes < 512) {
- bbuf = Arrays.copyOf(buf, readBytes);
- }
-
- PropertyFactory.convertToProperties(bbuf, properties);
- }
-
- assertEquals(64, properties.size());
- String[] names = {
- "Root Entry", null, null, null, null, null, null, null, null,
- null, null, null, null, "Deal Information", "Deal Description",
- "Sales Area Code", "Deal Currency", "Outbound Travel Dates",
- "Maximum Stay", "Maximum Stay Period", "Deal Type", "Sub Deal",
- "Commission Value", "Fare Type", "FUD Grid Dimensions",
- "FUD Grid Information", "Double Dealing Indicator",
- "Business Type", "Umbrella Links and Passengers", "Agents Name",
- "Number of Passengers", "ALC Codes", "Consortia Codes",
- "Child Percentage Permitted", "Percentage of Yield",
- "Net Remit Permitted", "Infant Discount Permitted",
- "Infant Discount Value", "TRVA Information",
- "Business Justification", "Surcharge", "Nature of Variation",
- "Other Refund Text", "Cancellation Fee Percentage",
- "Cancellation Fee Fixed Value", "Cancellation Fee Currency",
- "Remarks", "Other Carrier Sectors", "Prorate Comments", null,
- null, null, null, null, null, null, null, null, null, null, null,
- null, null, null
- };
- assertEquals(64, names.length);
-
- boolean[] isRoot = {
- true, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false
- };
- assertEquals(64, isRoot.length);
-
- boolean[] isDocument = {
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, true, true, true, true, true,
- true, true, true, true, true, true, true, true, true, true, true,
- true, true, true, true, true, true, true, true, true, true, true,
- true, true, true, true, true, true, true, true, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false
- };
- assertEquals(64, isDocument.length);
-
- boolean[] isDirectory = {
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, true, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false
- };
- assertEquals(64, isDirectory.length);
-
- boolean[] isNull = {
- false, true, true, true, true, true, true, true, true, true, true,
- true, true, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false, false, true, true, true, true, true, true, true, true,
- true, true, true, true, true, true, true
- };
- assertEquals(64, isNull.length);
-
- for (int j = 0; j < 64; j++) {
- if (isNull[j]) {
- assertNull(properties.get(j), "Checking property " + j);
- } else {
- assertNotNull(properties.get(j), "Checking property " + j);
- if (isRoot[j]) {
- assertTrue(properties.get(j) instanceof RootProperty, "Checking property " + j);
- }
- if (isDirectory[j]) {
- assertTrue(properties.get(j) instanceof DirectoryProperty, "Checking property " + j);
- }
- if (isDocument[j]) {
- assertTrue(properties.get(j) instanceof DocumentProperty, "Checking property " + j);
- }
- assertEquals(names[j], properties.get(j).getName(), "Checking property " + j);
- }
- }
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java b/src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java
deleted file mode 100644
index e6ce6610f5..0000000000
--- a/src/testcases/org/apache/poi/poifs/property/TestPropertyTable.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.poifs.property;
-
-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.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.poi.hpsf.DocumentSummaryInformation;
-import org.apache.poi.hpsf.SummaryInformation;
-import org.apache.poi.poifs.common.POIFSConstants;
-import org.apache.poi.poifs.filesystem.POIFSStream;
-import org.apache.poi.poifs.storage.HeaderBlock;
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test PropertyTable functionality
- */
-final class TestPropertyTable {
-
- private static void confirmBlockEncoding(String expectedDataStr, PropertyTable table) throws IOException {
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- byte[] expectedData = RawDataUtil.decompress(expectedDataStr);
-
- POIFSStream stream = new POIFSStream(null) {
- @Override
- public OutputStream getOutputStream() {
- return bos;
- }
- };
-
- table.write(stream);
-
- assertArrayEquals(expectedData, bos.toByteArray());
- }
-
- /**
- * Test PropertyTable
- *
- * Running individual tests of the PropertyTable methods, which is the
- * traditional way to write unit tests (at least for me), seems somewhat
- * useless in this case. Of greater relevance: if one follows the normal
- * steps of creating a PropertyTable, and then checking the output, does it
- * make sense? In other words, more of an integration test.
- *
- * So, the test consists of creating a PropertyTable instance, adding three
- * DocumentProperty instances to it, and then getting the output (including
- * the preWrite phase first), and comparing it against a real property table
- * extracted from a file known to be acceptable to Excel.
- */
- @Test
- void testWriterPropertyTable() throws IOException {
-
- // create the PropertyTable
- HeaderBlock headerBlock = new HeaderBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS);
- PropertyTable table = new PropertyTable(headerBlock);
-
- // create three DocumentProperty instances and add them to the
- // PropertyTable
- DocumentProperty workbook = new DocumentProperty("Workbook", 0x00046777);
-
- workbook.setStartBlock(0);
- DocumentProperty summary1 = new DocumentProperty(SummaryInformation.DEFAULT_STREAM_NAME, 0x00001000);
-
- summary1.setStartBlock(0x00000234);
- DocumentProperty summary2 = new DocumentProperty(DocumentSummaryInformation.DEFAULT_STREAM_NAME, 0x00001000);
-
- summary2.setStartBlock(0x0000023C);
- table.addProperty(workbook);
- RootProperty root = table.getRoot();
-
- root.addChild(workbook);
- table.addProperty(summary1);
- root = table.getRoot();
- root.addChild(summary1);
- table.addProperty(summary2);
- root = table.getRoot();
- root.addChild(summary2);
- table.preWrite();
-
- final String testblock =
- "H4sIAAAAAAAAAAtiyAfCEgYFBleGPCBdxFDJQAoQY2Bl/A8FTETq+QdUC2OHA20vYshmSAK7I5sku0FAiIEJbv9/JHMJgfJ0FjDN" +
- "yhDMUMqQC4SJYL97AkMhDewmkEgJQyaQnYfHHA2g/YxAmhmIibXfBBRQAgxQ+12ANiSD3ZAKjgHS3GNBhv9tkOwHAFGXmbcAAgAA";
- confirmBlockEncoding(testblock, table);
-
- table.removeProperty(summary1);
- root = table.getRoot();
- root.deleteChild(summary1);
- table.preWrite();
-
- final String testblock2 =
- "H4sIAAAAAAAAAAtiyAfCEgYFBleGPCBdxFDJQAoQY2Bl/A8FTETq+QdUC2OHA20vYshmSAK7I5sku0FAiIEJbv9/JHMJ" +
- "gfJ0FjDNyuACtDeZoZQhlyEVHALBYHYuQyI4LDyBYmlgN4JEShgygew8JHMsgPYzAmlS7LcBBZQAhA0Ae5Y5UIABAAA=";
- // (N)POIFS only returns 384 bytes here, instead of 512
- confirmBlockEncoding(testblock2, table);
-
- table.addProperty(summary1);
- root = table.getRoot();
- root.addChild(summary1);
- table.preWrite();
-
- final String testblock3 =
- "H4sIAAAAAAAAAAtiyAfCEgYFBleGPCBdxFDJQAoQY2Bl/A8FzETq+QdUC2OHA20vYshmSAK7I5sku0FAiIEJbv9/JHMJgfJ0FjDNyu" +
- "ACtDeZoZQhlyEVHALBYHYuQyI4LDyBYmlgN4JEShgygew8JHMsyLDfhglICDBA7SfNPnSgAbSfEUiDjCTWfhMk+wEk2TJjAAIAAA==";
- confirmBlockEncoding(testblock3, table);
- }
-
- @Test
- void testReadingConstructor() throws IOException {
-
- // first, we need the raw data blocks
- String raw_data_array =
- "H4sIAAAAAAAAAO2Z608TQRDA5wqVlreIyFMP5AMaMUAMMcYvQIVoUAivxI9HOeCkpaS9GvjmX67OzO61S1930zOpJJ2muUd" +
- "u9zfv3V4PoIAfH2z4BNd4LMIdSGQCktYfLVbEMf34/dWnzjPgggM55H9G/jnqUoQ83vHBw/Pr0LkWwKrwn4o0V7INx6iDDT" +
- "vI9eBMrMdrSDB/GM/pKOVncPYynKIHXGQH3vCQeKF1OcOrLGtCOtXKmuanhfxefdyCS5w/x5bvI72ILJczwUEN3MrdPD7l4" +
- "8fFJ01Z1/w+Ad+6x3eQRswcfqr+tjEyLvO38c4tc204Ye+U8SqQD5r/SMBPGPxjtOwU7Qv4Nuyy96+ghOcO+5984OB1iT1z" +
- "wf4o6fEfNT+QKHxTwu1vFJWqvNf8pMD+HsN+le0Oz03556FlWc5Jdad19AHeaX6vgN8LkvhvoS5FjhA9V9udAn5KwCdf6fY" +
- "Dezi7jxmgLKZYHyHLgZ+sEXnEYbtLTeZ6o/kDAj7l6rw+30RuiTPO5Qyz4QvfIT+cVyq/eQ96q/k9Aj7ZHjX+9RXX2P4hAT" +
- "9l8PeQcsk5ZnMuFLkPq+tDPGZ13wvzf7+Anzb439A26gCKWEBftKr2egn6/6CA32/wD9m/Lkd+g7PcYU8UMBeb+dwUG/mzm" +
- "h2VPwCN/X+Ax3OjDlzsu37IXIvIfybkDxr8r2jvLUY8z3GgmFOPu6t0Ho890VyWtP/HIbr/h8CMv8t5TrarLhfe8xrxnwj4" +
- "wwa/8Zqr8vA7V0IuEj8h4I+AaT/1lzJnXsA94Tr0Iu3CAv6YgD/Kdiup339lOBvIHyVNb159ik/zPRbwSdfA/ur+M8NVmGU" +
- "9bgT7z4Q1BbL8p1xJ6/MjzLwTrPz2978Ja1LIp1qp5l+RmWqVU50nr/3vt/R8lT8h5JsS8DzuuMHaH7bq3OePCPn0OyGs/0" +
- "SVaeTbQj75K6nPq/nXep/TTGaRPyfkU78O9j9busIoB3yu+erqEx59tf7MCPmm1O9/jtD2m0hrHwnZPy3kU73U17+MG8g48" +
- "l8K+VNgrv9l7v+X3HMv2uLPC/nTBn+DmarWbV4N8iIdJpH/QsifMfjbbLcby//PhfxZuO//U+OXt1TGkL8o5M+B6f9drDdZ" +
- "zZlC9i8I+aaofQ/F4ErMJhmN+fs3rgT7ni6/PX7teKnEHZ/q8Pj4+vfAzuZ+jPFzsLTxanV9eS/rL6+trKzafsE2LkPHP3T" +
- "/Pezx8evH6rj+Kd0H/sVRzp+MaX8Sfjh5t9Tm+M7nrwVhNd56fNz+063/OOPj2t9p+R3zS+9d2hnXlf9DLN27g/+E6L0E/T" +
- "/Rp/t5WseX3hnTe9uhmnh35WHLX544XEIAIAAA";
-
- // Fake up a header
- HeaderBlock header_block = new HeaderBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS);
- header_block.setPropertyStart(0);
-
- List data_blocks = new ArrayList<>();
- try (InputStream is = new ByteArrayInputStream(RawDataUtil.decompress(raw_data_array))) {
- byte[] buf = new byte[header_block.getBigBlockSize().getBigBlockSize()];
-
- for (int readBytes; (readBytes = is.read(buf)) != -1; ) {
- data_blocks.add(ByteBuffer.wrap(buf.clone(), 0, readBytes));
- }
- }
-
-
- // get property table from the document
- PropertyTable table = new PropertyTable(header_block, data_blocks);
-
- assertEquals(30 * 64, table.getRoot().getSize());
- int count = 0;
- Property lastChild = null;
- for (Property p : table.getRoot()) {
- assertNotNull(p);
- lastChild = p;
- ++count;
- }
-
- assertNotNull(lastChild, "no children found");
- assertEquals(1, count);
- assertTrue(lastChild.isDirectory());
- count = 0;
- for (Property p : (DirectoryProperty) lastChild) {
- assertNotNull(p);
- ++count;
- }
- assertEquals(35, count);
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java b/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java
deleted file mode 100644
index 4b311a8ec8..0000000000
--- a/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF 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.property;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.apache.poi.poifs.common.POIFSConstants;
-import org.apache.poi.poifs.storage.RawDataUtil;
-import org.apache.poi.util.LocaleUtil;
-import org.junit.jupiter.api.Test;
-
-/**
- * Class to test RootProperty functionality
- *
- * @author Marc Johnson
- */
-final class TestRootProperty {
- private RootProperty _property;
- private byte[] _testblock;
-
- @Test
- void testConstructor() throws IOException {
- createBasicRootProperty();
- verifyProperty();
- }
-
- private void createBasicRootProperty() {
- _property = new RootProperty();
- _testblock = new byte[128];
- int index = 0;
-
- for (; index < 0x40; index++) {
- _testblock[index] = (byte) 0;
- }
- String name = "Root Entry";
- int limit = name.length();
-
- _testblock[index++] = (byte) (2 * (limit + 1));
- _testblock[index++] = (byte) 0;
- _testblock[index++] = (byte) 5;
- _testblock[index++] = (byte) 1;
- for (; index < 0x50; index++) {
- _testblock[index] = (byte) 0xff;
- }
- for (; index < 0x74; index++) {
- _testblock[index] = (byte) 0;
- }
- _testblock[index++] = (byte) POIFSConstants.END_OF_CHAIN;
- for (; index < 0x78; index++) {
- _testblock[index] = (byte) 0xff;
- }
- for (; index < 0x80; index++) {
- _testblock[index] = (byte) 0;
- }
- byte[] name_bytes = name.getBytes(LocaleUtil.CHARSET_1252);
-
- for (index = 0; index < limit; index++) {
- _testblock[index * 2] = name_bytes[index];
- }
- }
-
- private void verifyProperty() throws IOException {
- ByteArrayOutputStream stream = new ByteArrayOutputStream(512);
-
- _property.writeData(stream);
- byte[] output = stream.toByteArray();
-
- assertEquals(_testblock.length, output.length);
- for (int j = 0; j < _testblock.length; j++) {
- assertEquals(_testblock[j], output[j], "mismatch at offset " + j);
- }
- }
-
- @Test
- void testSetSize() {
- for (int j = 0; j < 10; j++) {
- createBasicRootProperty();
- _property.setSize(j);
- assertEquals(j * 64, _property.getSize(), "trying block count of " + j);
- }
- }
-
- @Test
- void testReadingConstructor() {
- String[] input = {
- "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",
- "16 00 05 01 FF FF FF FF FF FF FF FF 02 00 00 00 20 08 02 00 00 00 00 00 C0 00 00 00 00 00 00 46",
- "00 00 00 00 00 00 00 00 00 00 00 00 C0 5C E8 23 9E 6B C1 01 FE FF FF FF 00 00 00 00 00 00 00 00",
- };
- verifyReadingProperty(0, RawDataUtil.decode(input), 0, "Root Entry",
- "{00020820-0000-0000-C000-000000000046}");
- }
-
- private void verifyReadingProperty(int index, byte[] input, int offset, String name,
- String sClsId) {
- RootProperty property = new RootProperty(index, input, offset);
- ByteArrayOutputStream stream = new ByteArrayOutputStream(128);
- byte[] expected = Arrays.copyOfRange(input, offset, offset+128);
- try {
- property.writeData(stream);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- byte[] output = stream.toByteArray();
-
- assertEquals(128, output.length);
- for (int j = 0; j < 128; j++) {
- assertEquals(expected[j], output[j], "mismatch at offset " + j);
- }
- assertEquals(index, property.getIndex());
- assertEquals(name, property.getName());
- assertFalse(property.getChildren().hasNext());
- assertEquals(property.getStorageClsid().toString(), sClsId);
- }
-}
diff --git a/src/testcases/org/apache/poi/poifs/storage/LocalProperty.java b/src/testcases/org/apache/poi/poifs/storage/LocalProperty.java
deleted file mode 100644
index 13a1c52306..0000000000
--- a/src/testcases/org/apache/poi/poifs/storage/LocalProperty.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.poifs.storage;
-
-import org.apache.poi.poifs.property.Property;
-
-class LocalProperty
- extends Property
-{
-
- /**
- * Constructor TestProperty
- *
- * @param name name of the property
- */
-
- LocalProperty(String name)
- {
- super();
- setName(name);
- }
-
- /**
- * do nothing
- */
-
- @Override
- protected void preWrite()
- {
- }
-
- /**
- * @return false
- */
-
- @Override
- public boolean isDirectory()
- {
- return false;
- }
-} // end package scope class LocalProperty
-
diff --git a/src/testcases/org/apache/poi/poifs/storage/RawDataUtil.java b/src/testcases/org/apache/poi/poifs/storage/RawDataUtil.java
deleted file mode 100644
index b04741fb06..0000000000
--- a/src/testcases/org/apache/poi/poifs/storage/RawDataUtil.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.poifs.storage;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.Base64;
-import java.util.zip.GZIPInputStream;
-
-import org.apache.poi.util.HexRead;
-import org.apache.poi.util.IOUtils;
-
-/**
- * Test utility class. | | | |