You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

XSSFFileHandler.java 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.stress;
  16. import static org.apache.poi.xssf.XSSFTestDataSamples.getSampleFile;
  17. import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
  18. import static org.junit.jupiter.api.Assertions.assertFalse;
  19. import static org.junit.jupiter.api.Assertions.assertNotNull;
  20. import static org.junit.jupiter.api.Assertions.assertTrue;
  21. import static org.junit.jupiter.api.Assumptions.assumeFalse;
  22. import java.io.BufferedInputStream;
  23. import java.io.File;
  24. import java.io.FileInputStream;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.io.OutputStream;
  28. import java.io.PrintStream;
  29. import java.util.HashSet;
  30. import java.util.Iterator;
  31. import java.util.Set;
  32. import javax.xml.transform.TransformerException;
  33. import org.apache.commons.io.output.NullOutputStream;
  34. import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
  35. import org.apache.poi.EncryptedDocumentException;
  36. import org.apache.poi.examples.ss.ExcelComparator;
  37. import org.apache.poi.examples.xssf.eventusermodel.FromHowTo;
  38. import org.apache.poi.examples.xssf.eventusermodel.XLSX2CSV;
  39. import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
  40. import org.apache.poi.ooxml.POIXMLException;
  41. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  42. import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException;
  43. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  44. import org.apache.poi.openxml4j.opc.OPCPackage;
  45. import org.apache.poi.poifs.crypt.Decryptor;
  46. import org.apache.poi.poifs.crypt.EncryptionInfo;
  47. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  48. import org.apache.poi.ss.usermodel.Sheet;
  49. import org.apache.poi.util.IOUtils;
  50. import org.apache.poi.xssf.eventusermodel.XSSFReader;
  51. import org.apache.poi.xssf.extractor.XSSFExportToXml;
  52. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  53. import org.apache.poi.xssf.usermodel.XSSFMap;
  54. import org.apache.poi.xssf.usermodel.XSSFSheet;
  55. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  56. import org.junit.jupiter.api.Test;
  57. import org.xml.sax.SAXException;
  58. public class XSSFFileHandler extends SpreadsheetHandler {
  59. @Override
  60. public void handleFile(InputStream stream, String path) throws Exception {
  61. // ignore password protected files if password is unknown
  62. String pass = Biff8EncryptionKey.getCurrentUserPassword();
  63. assumeFalse(pass == null && POIXMLDocumentHandler.isEncrypted(stream));
  64. final XSSFWorkbook wb;
  65. // make sure the potentially large byte-array is freed up quickly again
  66. {
  67. UnsynchronizedByteArrayOutputStream out = UnsynchronizedByteArrayOutputStream.builder().get();
  68. IOUtils.copy(stream, out);
  69. if (pass != null) {
  70. POIFSFileSystem poifs = new POIFSFileSystem(out.toInputStream());
  71. EncryptionInfo ei = new EncryptionInfo(poifs);
  72. Decryptor dec = ei.getDecryptor();
  73. try {
  74. boolean b = dec.verifyPassword(pass);
  75. assertTrue( b, "password mismatch" );
  76. } catch (EncryptedDocumentException e) {
  77. String msg = "Export Restrictions in place - please install JCE Unlimited Strength Jurisdiction Policy files";
  78. assumeFalse(msg.equals(e.getMessage()));
  79. throw e;
  80. }
  81. InputStream is = dec.getDataStream(poifs);
  82. out.reset();
  83. IOUtils.copy(is, out);
  84. is.close();
  85. poifs.close();
  86. }
  87. checkXSSFReader(OPCPackage.open(out.toInputStream()));
  88. wb = new XSSFWorkbook(out.toInputStream());
  89. }
  90. // use the combined handler for HSSF/XSSF
  91. handleWorkbook(wb);
  92. // TODO: some documents fail currently...
  93. //XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(wb);
  94. //evaluator.evaluateAll();
  95. // also verify general POIFS-stuff
  96. new POIXMLDocumentHandler().handlePOIXMLDocument(wb);
  97. POIXMLDocumentHandler.cursorRecursive(wb.getCTWorkbook());
  98. for (Sheet sh : wb) {
  99. POIXMLDocumentHandler.cursorRecursive(((XSSFSheet)sh).getCTWorksheet());
  100. }
  101. // and finally ensure that exporting to XML works
  102. exportToXML(wb);
  103. // also try to read and write the sheet via SXSSF
  104. try (SXSSFWorkbook swb = new SXSSFWorkbook(wb)) {
  105. try (OutputStream out = NullOutputStream.INSTANCE) {
  106. swb.write(out);
  107. }
  108. }
  109. // this allows to trigger a heap-dump at this point to see which memory is still allocated
  110. //HeapDump.dumpHeap("/tmp/poi.hprof", false);
  111. wb.close();
  112. }
  113. private void checkXSSFReader(OPCPackage p) throws IOException, OpenXML4JException {
  114. XSSFReader reader = new XSSFReader(p);
  115. // these can be null...
  116. InputStream sharedStringsData = reader.getSharedStringsData();
  117. if(sharedStringsData != null) {
  118. sharedStringsData.close();
  119. }
  120. reader.getSharedStringsTable();
  121. InputStream stylesData = reader.getStylesData();
  122. if(stylesData != null) {
  123. stylesData.close();
  124. }
  125. reader.getStylesTable();
  126. InputStream themesData = reader.getThemesData();
  127. if(themesData != null) {
  128. themesData.close();
  129. }
  130. assertNotNull(reader.getWorkbookData());
  131. Iterator<InputStream> sheetsData = reader.getSheetsData();
  132. while(sheetsData.hasNext()) {
  133. InputStream str = sheetsData.next();
  134. str.close();
  135. }
  136. }
  137. private void exportToXML(XSSFWorkbook wb) throws SAXException,
  138. TransformerException {
  139. for (XSSFMap map : wb.getCustomXMLMappings()) {
  140. XSSFExportToXml exporter = new XSSFExportToXml(map);
  141. exporter.exportToXML(NullOutputStream.INSTANCE, true);
  142. }
  143. }
  144. private static final Set<String> EXPECTED_ADDITIONAL_FAILURES = new HashSet<>();
  145. static {
  146. // expected sheet-id not found
  147. // EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/52348.xlsx");
  148. // EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/59021.xlsx");
  149. // zip-bomb
  150. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/54764.xlsx");
  151. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/54764-2.xlsx");
  152. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/poc-xmlbomb.xlsx");
  153. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/poc-xmlbomb-empty.xlsx");
  154. // strict OOXML
  155. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/57914.xlsx");
  156. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/SampleSS.strict.xlsx");
  157. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/SimpleStrict.xlsx");
  158. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/sample.strict.xlsx");
  159. // TODO: good to ignore?
  160. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/sample-beta.xlsx");
  161. // corrupt/invalid
  162. EXPECTED_ADDITIONAL_FAILURES.add("openxml4j/invalid.xlsx");
  163. }
  164. @SuppressWarnings("resource")
  165. @Override
  166. public void handleAdditional(File file) throws Exception {
  167. // redirect stdout as the examples often write lots of text
  168. PrintStream oldOut = System.out;
  169. String testFile = file.getParentFile().getName() + "/" + file.getName();
  170. try {
  171. System.setOut(new OptimizedNullPrintStream());
  172. FromHowTo.main(new String[]{file.getAbsolutePath()});
  173. XLSX2CSV.main(new String[]{file.getAbsolutePath()});
  174. ExcelComparator.main(new String[]{file.getAbsolutePath(), file.getAbsolutePath()});
  175. assertFalse( EXPECTED_ADDITIONAL_FAILURES.contains(testFile), "Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!" );
  176. } catch (OLE2NotOfficeXmlFileException e) {
  177. // we have some files that are not actually OOXML and thus cannot be tested here
  178. } catch (IllegalArgumentException | InvalidFormatException | POIXMLException | IOException e) {
  179. if(!EXPECTED_ADDITIONAL_FAILURES.contains(testFile)) {
  180. throw e;
  181. }
  182. } finally {
  183. System.setOut(oldOut);
  184. }
  185. }
  186. // a test-case to test this locally without executing the full TestAllFiles
  187. @Test
  188. void test() throws Exception {
  189. File file = new File("test-data/spreadsheet/ref-56737.xlsx");
  190. try (InputStream stream = new BufferedInputStream(new FileInputStream(file))) {
  191. handleFile(stream, file.getPath());
  192. }
  193. handleExtracting(file);
  194. handleAdditional(file);
  195. }
  196. @Test
  197. void testExtracting() {
  198. File testFile = getSampleFile("ref-56737.xlsx");
  199. assertDoesNotThrow(() -> handleExtracting(testFile));
  200. }
  201. @Test
  202. void testAdditional() {
  203. File testFile = getSampleFile("poc-xmlbomb.xlsx");
  204. assertDoesNotThrow(() -> handleAdditional(testFile));
  205. }
  206. }