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.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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.junit.Assert.assertFalse;
  17. import static org.junit.Assert.assertNotNull;
  18. import java.io.*;
  19. import java.util.HashSet;
  20. import java.util.Iterator;
  21. import java.util.Locale;
  22. import java.util.Set;
  23. import javax.xml.parsers.ParserConfigurationException;
  24. import javax.xml.transform.TransformerException;
  25. import org.apache.poi.POIXMLException;
  26. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  27. import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException;
  28. import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException;
  29. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  30. import org.apache.poi.openxml4j.opc.OPCPackage;
  31. import org.apache.poi.util.IOUtils;
  32. import org.apache.poi.xssf.eventusermodel.XLSX2CSV;
  33. import org.apache.poi.xssf.eventusermodel.XSSFReader;
  34. import org.apache.poi.xssf.eventusermodel.examples.FromHowTo;
  35. import org.apache.poi.xssf.extractor.XSSFExportToXml;
  36. import org.apache.poi.xssf.usermodel.XSSFMap;
  37. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  38. import org.junit.Test;
  39. import org.xml.sax.SAXException;
  40. public class XSSFFileHandler extends SpreadsheetHandler {
  41. @Override
  42. public void handleFile(InputStream stream) throws Exception {
  43. // ignore password protected files
  44. if (POIXMLDocumentHandler.isEncrypted(stream)) return;
  45. ByteArrayOutputStream out = new ByteArrayOutputStream();
  46. IOUtils.copy(stream, out);
  47. final byte[] bytes = out.toByteArray();
  48. final XSSFWorkbook wb;
  49. wb = new XSSFWorkbook(new ByteArrayInputStream(bytes));
  50. // use the combined handler for HSSF/XSSF
  51. handleWorkbook(wb);
  52. // TODO: some documents fail currently...
  53. //XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(wb);
  54. //evaluator.evaluateAll();
  55. // also verify general POIFS-stuff
  56. new POIXMLDocumentHandler().handlePOIXMLDocument(wb);
  57. // and finally ensure that exporting to XML works
  58. exportToXML(wb);
  59. checkXSSFReader(OPCPackage.open(new ByteArrayInputStream(bytes)));
  60. wb.close();
  61. }
  62. private void checkXSSFReader(OPCPackage p) throws IOException, OpenXML4JException {
  63. XSSFReader reader = new XSSFReader(p);
  64. // these can be null...
  65. InputStream sharedStringsData = reader.getSharedStringsData();
  66. if(sharedStringsData != null) {
  67. sharedStringsData.close();
  68. }
  69. reader.getSharedStringsTable();
  70. InputStream stylesData = reader.getStylesData();
  71. if(stylesData != null) {
  72. stylesData.close();
  73. }
  74. reader.getStylesTable();
  75. InputStream themesData = reader.getThemesData();
  76. if(themesData != null) {
  77. themesData.close();
  78. }
  79. assertNotNull(reader.getWorkbookData());
  80. Iterator<InputStream> sheetsData = reader.getSheetsData();
  81. while(sheetsData.hasNext()) {
  82. InputStream str = sheetsData.next();
  83. str.close();
  84. }
  85. }
  86. private void exportToXML(XSSFWorkbook wb) throws SAXException,
  87. ParserConfigurationException, TransformerException {
  88. for (XSSFMap map : wb.getCustomXMLMappings()) {
  89. XSSFExportToXml exporter = new XSSFExportToXml(map);
  90. ByteArrayOutputStream os = new ByteArrayOutputStream();
  91. exporter.exportToXML(os, true);
  92. }
  93. }
  94. private static final Set<String> EXPECTED_ADDITIONAL_FAILURES = new HashSet<String>();
  95. static {
  96. // expected sheet-id not found
  97. // EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/52348.xlsx");
  98. // EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/59021.xlsx");
  99. // zip-bomb
  100. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/54764.xlsx");
  101. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/54764-2.xlsx");
  102. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/54764.xlsx");
  103. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/poc-xmlbomb.xlsx");
  104. // strict OOXML
  105. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/57914.xlsx");
  106. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/SampleSS.strict.xlsx");
  107. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/SimpleStrict.xlsx");
  108. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/sample.strict.xlsx");
  109. // binary format
  110. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/Simple.xlsb");
  111. // TODO: good to ignore?
  112. EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/sample-beta.xlsx");
  113. // corrupt/invalid
  114. EXPECTED_ADDITIONAL_FAILURES.add("openxml4j/invalid.xlsx");
  115. }
  116. @SuppressWarnings("resource")
  117. @Override
  118. public void handleAdditional(File file) throws Exception {
  119. // redirect stdout as the examples often write lots of text
  120. PrintStream oldOut = System.out;
  121. try {
  122. System.setOut(new NullPrintStream());
  123. FromHowTo.main(new String[]{file.getAbsolutePath()});
  124. XLSX2CSV.main(new String[]{file.getAbsolutePath()});
  125. assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!",
  126. EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName()));
  127. } catch (OLE2NotOfficeXmlFileException e) {
  128. // we have some files that are not actually OOXML and thus cannot be tested here
  129. } catch (IllegalArgumentException e) {
  130. if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
  131. throw e;
  132. }
  133. } catch (InvalidFormatException e) {
  134. if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
  135. throw e;
  136. }
  137. } catch (IOException e) {
  138. if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
  139. throw e;
  140. }
  141. } catch (POIXMLException e) {
  142. if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) {
  143. throw e;
  144. }
  145. } finally {
  146. System.setOut(oldOut);
  147. }
  148. }
  149. // a test-case to test this locally without executing the full TestAllFiles
  150. @Test
  151. public void test() throws Exception {
  152. InputStream stream = new BufferedInputStream(new FileInputStream("test-data/spreadsheet/ref-56737.xlsx"));
  153. try {
  154. handleFile(stream);
  155. } finally {
  156. stream.close();
  157. }
  158. }
  159. // a test-case to test this locally without executing the full TestAllFiles
  160. @Test
  161. public void testExtractor() throws Exception {
  162. handleExtracting(new File("test-data/spreadsheet/ref-56737.xlsx"));
  163. }
  164. @Test
  165. public void testAdditional() throws Exception {
  166. handleAdditional(new File("test-data/spreadsheet/poc-xmlbomb.xlsx"));
  167. }
  168. // need to override all methods to omit calls to UTF-handling methods
  169. static class NullPrintStream extends PrintStream {
  170. @SuppressWarnings("resource")
  171. NullPrintStream() {
  172. super(new OutputStream() {
  173. public void write(int b) {}
  174. public void write(byte[] b) {}
  175. public void write(byte[] b, int off, int len) {}
  176. });
  177. }
  178. public void write(int b) {}
  179. public void write(byte[] buf, int off, int len) {}
  180. public void print(boolean b) {}
  181. public void print(char c) {}
  182. public void print(int i) {}
  183. public void print(long l) {}
  184. public void print(float f) {}
  185. public void print(double d) {}
  186. public void print(char[] s) {}
  187. public void print(String s) {}
  188. public void print(Object obj) {}
  189. public void println() {}
  190. public void println(boolean x) {}
  191. public void println(char x) {}
  192. public void println(int x) {}
  193. public void println(long x) {}
  194. public void println(float x) {}
  195. public void println(double x) {}
  196. public void println(char[] x) {}
  197. public void println(String x) {}
  198. public void println(Object x) {}
  199. public PrintStream printf(String format, Object... args) { return this; }
  200. public PrintStream printf(Locale l, String format, Object... args) { return this; }
  201. public PrintStream format(String format, Object... args) { return this; }
  202. public PrintStream format(Locale l, String format, Object... args) { return this; }
  203. public PrintStream append(CharSequence csq) { return this; }
  204. public PrintStream append(CharSequence csq, int start, int end) { return this; }
  205. public PrintStream append(char c) { return this; }
  206. public void write(byte[] b) {}
  207. }
  208. }