Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TestPOIXMLDocument.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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.ooxml;
  16. import static org.junit.Assert.assertEquals;
  17. import static org.junit.Assert.assertFalse;
  18. import static org.junit.Assert.assertNotNull;
  19. import static org.junit.Assert.assertNull;
  20. import static org.junit.Assert.assertSame;
  21. import static org.junit.Assert.fail;
  22. import java.io.File;
  23. import java.io.FileOutputStream;
  24. import java.io.IOException;
  25. import java.io.InputStream;
  26. import java.lang.Thread.UncaughtExceptionHandler;
  27. import java.lang.reflect.InvocationTargetException;
  28. import java.util.ArrayList;
  29. import java.util.HashMap;
  30. import java.util.HashSet;
  31. import java.util.List;
  32. import org.apache.poi.POIDataSamples;
  33. import org.apache.poi.ooxml.POIXMLDocumentPart.RelationPart;
  34. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  35. import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException;
  36. import org.apache.poi.openxml4j.opc.OPCPackage;
  37. import org.apache.poi.openxml4j.opc.PackagePart;
  38. import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
  39. import org.apache.poi.util.IOUtils;
  40. import org.apache.poi.util.NullOutputStream;
  41. import org.apache.poi.ooxml.util.PackageHelper;
  42. import org.apache.poi.util.TempFile;
  43. import org.apache.poi.xslf.usermodel.XMLSlideShow;
  44. import org.apache.poi.xssf.usermodel.XSSFRelation;
  45. import org.apache.poi.xwpf.usermodel.XWPFRelation;
  46. import org.junit.Test;
  47. /**
  48. * Test recursive read and write of OPC packages
  49. */
  50. public final class TestPOIXMLDocument {
  51. private static class OPCParser extends POIXMLDocument {
  52. public OPCParser(OPCPackage pkg) {
  53. super(pkg);
  54. }
  55. public OPCParser(OPCPackage pkg, String coreDocumentRel) {
  56. super(pkg, coreDocumentRel);
  57. }
  58. @Override
  59. public List<PackagePart> getAllEmbeddedParts() {
  60. throw new RuntimeException("not supported");
  61. }
  62. public void parse(POIXMLFactory factory) throws IOException{
  63. load(factory);
  64. }
  65. }
  66. private static final class TestFactory extends POIXMLFactory {
  67. public TestFactory() {
  68. //
  69. }
  70. @Override
  71. protected POIXMLRelation getDescriptor(String relationshipType) {
  72. return null;
  73. }
  74. /**
  75. * @since POI 3.14-Beta1
  76. */
  77. @Override
  78. protected POIXMLDocumentPart createDocumentPart
  79. (Class<? extends POIXMLDocumentPart> cls, Class<?>[] classes, Object[] values)
  80. throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
  81. return null;
  82. }
  83. }
  84. private static void traverse(POIXMLDocument doc) throws IOException{
  85. HashMap<String,POIXMLDocumentPart> context = new HashMap<>();
  86. for (RelationPart p : doc.getRelationParts()){
  87. traverse(p, context);
  88. }
  89. }
  90. /**
  91. * Recursively traverse a OOXML document and assert that same logical parts have the same physical instances
  92. */
  93. private static void traverse(RelationPart rp, HashMap<String,POIXMLDocumentPart> context) throws IOException{
  94. POIXMLDocumentPart dp = rp.getDocumentPart();
  95. assertEquals(rp.getRelationship().getTargetURI().toString(), dp.getPackagePart().getPartName().getName());
  96. context.put(dp.getPackagePart().getPartName().getName(), dp);
  97. for(RelationPart p : dp.getRelationParts()){
  98. assertNotNull(p.getRelationship().toString());
  99. String uri = p.getDocumentPart().getPackagePart().getPartName().getURI().toString();
  100. assertEquals(uri, p.getRelationship().getTargetURI().toString());
  101. if (!context.containsKey(uri)) {
  102. traverse(p, context);
  103. } else {
  104. POIXMLDocumentPart prev = context.get(uri);
  105. assertSame("Duplicate POIXMLDocumentPart instance for targetURI=" + uri, prev, p.getDocumentPart());
  106. }
  107. }
  108. }
  109. public void assertReadWrite(OPCPackage pkg1) throws Exception {
  110. OPCParser doc = new OPCParser(pkg1);
  111. doc.parse(new TestFactory());
  112. traverse(doc);
  113. File tmp = TempFile.createTempFile("poi-ooxml", ".tmp");
  114. FileOutputStream out = new FileOutputStream(tmp);
  115. doc.write(out);
  116. out.close();
  117. // Should not be able to write to an output stream that has been closed
  118. try {
  119. doc.write(out);
  120. fail("Should not be able to write to an output stream that has been closed.");
  121. } catch (final OpenXML4JRuntimeException e) {
  122. // FIXME: A better exception class (IOException?) and message should be raised
  123. // indicating that the document could not be written because the output stream is closed.
  124. // see {@link org.apache.poi.openxml4j.opc.ZipPackage#saveImpl(java.io.OutputStream)}
  125. if (e.getMessage().matches("Fail to save: an error occurs while saving the package : The part .+ failed to be saved in the stream with marshaller .+")) {
  126. // expected
  127. } else {
  128. throw e;
  129. }
  130. }
  131. // Should not be able to write a document that has been closed
  132. doc.close();
  133. try {
  134. doc.write(new NullOutputStream());
  135. fail("Should not be able to write a document that has been closed.");
  136. } catch (final IOException e) {
  137. if (e.getMessage().equals("Cannot write data, document seems to have been closed already")) {
  138. // expected
  139. } else {
  140. throw e;
  141. }
  142. }
  143. // Should be able to close a document multiple times, though subsequent closes will have no effect.
  144. doc.close();
  145. @SuppressWarnings("resource")
  146. OPCPackage pkg2 = OPCPackage.open(tmp.getAbsolutePath());
  147. doc = new OPCParser(pkg1);
  148. try {
  149. doc.parse(new TestFactory());
  150. traverse(doc);
  151. assertEquals(pkg1.getRelationships().size(), pkg2.getRelationships().size());
  152. ArrayList<PackagePart> l1 = pkg1.getParts();
  153. ArrayList<PackagePart> l2 = pkg2.getParts();
  154. assertEquals(l1.size(), l2.size());
  155. for (int i=0; i < l1.size(); i++){
  156. PackagePart p1 = l1.get(i);
  157. PackagePart p2 = l2.get(i);
  158. assertEquals(p1.getContentType(), p2.getContentType());
  159. assertEquals(p1.hasRelationships(), p2.hasRelationships());
  160. if(p1.hasRelationships()){
  161. assertEquals(p1.getRelationships().size(), p2.getRelationships().size());
  162. }
  163. assertEquals(p1.getPartName(), p2.getPartName());
  164. }
  165. } finally {
  166. doc.close();
  167. pkg1.close();
  168. pkg2.close();
  169. }
  170. }
  171. @Test
  172. public void testPPTX() throws Exception {
  173. POIDataSamples pds = POIDataSamples.getSlideShowInstance();
  174. assertReadWrite(PackageHelper.open(pds.openResourceAsStream("PPTWithAttachments.pptm")));
  175. }
  176. @Test
  177. public void testXLSX() throws Exception {
  178. POIDataSamples pds = POIDataSamples.getSpreadSheetInstance();
  179. assertReadWrite(PackageHelper.open(pds.openResourceAsStream("ExcelWithAttachments.xlsm")));
  180. }
  181. @Test
  182. public void testDOCX() throws Exception {
  183. POIDataSamples pds = POIDataSamples.getDocumentInstance();
  184. assertReadWrite(PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx")));
  185. }
  186. @Test
  187. public void testRelationOrder() throws Exception {
  188. POIDataSamples pds = POIDataSamples.getDocumentInstance();
  189. @SuppressWarnings("resource")
  190. OPCPackage pkg = PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx"));
  191. OPCParser doc = new OPCParser(pkg);
  192. try {
  193. doc.parse(new TestFactory());
  194. for(POIXMLDocumentPart rel : doc.getRelations()){
  195. //TODO finish me
  196. assertNotNull(rel);
  197. }
  198. } finally {
  199. doc.close();
  200. }
  201. }
  202. @Test
  203. public void testGetNextPartNumber() throws Exception {
  204. POIDataSamples pds = POIDataSamples.getDocumentInstance();
  205. @SuppressWarnings("resource")
  206. OPCPackage pkg = PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx"));
  207. OPCParser doc = new OPCParser(pkg);
  208. try {
  209. doc.parse(new TestFactory());
  210. // Non-indexed parts: Word is taken, Excel is not
  211. assertEquals(-1, doc.getNextPartNumber(XWPFRelation.DOCUMENT, 0));
  212. assertEquals(-1, doc.getNextPartNumber(XWPFRelation.DOCUMENT, -1));
  213. assertEquals(-1, doc.getNextPartNumber(XWPFRelation.DOCUMENT, 99));
  214. assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, 0));
  215. assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, -1));
  216. assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, 99));
  217. // Indexed parts:
  218. // Has 2 headers
  219. assertEquals(0, doc.getNextPartNumber(XWPFRelation.HEADER, 0));
  220. assertEquals(3, doc.getNextPartNumber(XWPFRelation.HEADER, -1));
  221. assertEquals(3, doc.getNextPartNumber(XWPFRelation.HEADER, 1));
  222. assertEquals(8, doc.getNextPartNumber(XWPFRelation.HEADER, 8));
  223. // Has no Excel Sheets
  224. assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKSHEET, 0));
  225. assertEquals(1, doc.getNextPartNumber(XSSFRelation.WORKSHEET, -1));
  226. assertEquals(1, doc.getNextPartNumber(XSSFRelation.WORKSHEET, 1));
  227. } finally {
  228. doc.close();
  229. }
  230. }
  231. @Test
  232. public void testCommitNullPart() throws IOException, InvalidFormatException {
  233. POIXMLDocumentPart part = new POIXMLDocumentPart();
  234. part.prepareForCommit();
  235. part.commit();
  236. part.onSave(new HashSet<>());
  237. assertNull(part.getRelationById(null));
  238. assertNull(part.getRelationId(null));
  239. assertFalse(part.removeRelation(null, true));
  240. part.removeRelation((POIXMLDocumentPart)null);
  241. assertEquals("",part.toString());
  242. part.onDocumentCreate();
  243. //part.getTargetPart(null);
  244. }
  245. @Test
  246. public void testVSDX() throws Exception {
  247. POIDataSamples pds = POIDataSamples.getDiagramInstance();
  248. @SuppressWarnings("resource")
  249. OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx"));
  250. POIXMLDocument part = new OPCParser(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT);
  251. assertNotNull(part);
  252. assertEquals(0, part.getRelationCounter());
  253. part.close();
  254. }
  255. @Test
  256. public void testVSDXPart() throws IOException {
  257. POIDataSamples pds = POIDataSamples.getDiagramInstance();
  258. OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx"));
  259. POIXMLDocumentPart part = new POIXMLDocumentPart(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT);
  260. assertNotNull(part);
  261. assertEquals(0, part.getRelationCounter());
  262. open.close();
  263. }
  264. @Test(expected=POIXMLException.class)
  265. public void testInvalidCoreRel() throws IOException {
  266. POIDataSamples pds = POIDataSamples.getDiagramInstance();
  267. OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx"));
  268. try {
  269. new POIXMLDocumentPart(open, "somethingillegal");
  270. } finally {
  271. open.close();
  272. }
  273. }
  274. @Test
  275. public void dontParseEmbeddedDocuments() throws IOException {
  276. // bug #62513
  277. POIDataSamples pds = POIDataSamples.getSlideShowInstance();
  278. try (InputStream is = pds.openResourceAsStream("bug62513.pptx");
  279. XMLSlideShow ppt = new XMLSlideShow(is)) {
  280. POIXMLDocumentPart doc = ppt.getSlides().get(12).getRelationById("rId3");
  281. assertEquals(POIXMLDocumentPart.class, doc.getClass());
  282. }
  283. }
  284. @Test
  285. public void testOSGIClassLoading() {
  286. // the schema type loader is cached per thread in POIXMLTypeLoader.
  287. // So create a new Thread and change the context class loader (which would normally be used)
  288. // to not contain the OOXML classes
  289. Runnable run = new Runnable() {
  290. public void run() {
  291. InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream("table_test.pptx");
  292. XMLSlideShow ppt = null;
  293. try {
  294. ppt = new XMLSlideShow(is);
  295. ppt.getSlides().get(0).getShapes();
  296. } catch (IOException e) {
  297. fail("failed to load XMLSlideShow");
  298. } finally {
  299. IOUtils.closeQuietly(ppt);
  300. IOUtils.closeQuietly(is);
  301. }
  302. }
  303. };
  304. Thread thread = Thread.currentThread();
  305. ClassLoader cl = thread.getContextClassLoader();
  306. UncaughtHandler uh = new UncaughtHandler();
  307. // check schema type loading and check if we could run in an OOM
  308. Thread ta[] = new Thread[30];
  309. for (int j=0; j<10; j++) {
  310. for (int i=0; i<ta.length; i++) {
  311. ta[i] = new Thread(run);
  312. ta[i].setContextClassLoader(cl.getParent());
  313. ta[i].setUncaughtExceptionHandler(uh);
  314. ta[i].start();
  315. }
  316. for (int i=0; i<ta.length; i++) {
  317. try {
  318. ta[i].join();
  319. } catch (InterruptedException e) {
  320. fail("failed to join thread");
  321. }
  322. }
  323. }
  324. assertFalse(uh.hasException());
  325. }
  326. private static class UncaughtHandler implements UncaughtExceptionHandler {
  327. Throwable e;
  328. public synchronized void uncaughtException(Thread t, Throwable e) {
  329. this.e = e;
  330. }
  331. public synchronized boolean hasException() {
  332. return e != null;
  333. }
  334. }
  335. }