PageRenderTime 26ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/projects/poi-3.6/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 452 lines | 292 code | 75 blank | 85 comment | 9 complexity | 078fc40e502c3079462defa9d3e17e65 MD5 | raw file
  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.openxml4j.opc;
  16. import java.io.ByteArrayOutputStream;
  17. import java.io.File;
  18. import java.io.FileInputStream;
  19. import java.io.FileOutputStream;
  20. import java.io.IOException;
  21. import java.io.OutputStream;
  22. import java.lang.reflect.Field;
  23. import java.net.URI;
  24. import java.util.TreeMap;
  25. import java.util.Iterator;
  26. import junit.framework.TestCase;
  27. import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
  28. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  29. import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
  30. import org.apache.poi.openxml4j.opc.internal.FileHelper;
  31. import org.apache.poi.util.TempFile;
  32. import org.apache.poi.util.POILogger;
  33. import org.apache.poi.util.POILogFactory;
  34. import org.dom4j.Document;
  35. import org.dom4j.DocumentHelper;
  36. import org.dom4j.Element;
  37. import org.dom4j.Namespace;
  38. import org.dom4j.QName;
  39. import org.dom4j.io.SAXReader;
  40. public final class TestPackage extends TestCase {
  41. private static final POILogger logger = POILogFactory.getLogger(TestPackage.class);
  42. /**
  43. * Test that just opening and closing the file doesn't alter the document.
  44. */
  45. public void testOpenSave() throws Exception {
  46. String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
  47. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
  48. OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
  49. p.save(targetFile.getAbsoluteFile());
  50. // Compare the original and newly saved document
  51. assertTrue(targetFile.exists());
  52. //ZipFileAssert.assertEquals(originalFile, targetFile);
  53. assertTrue(targetFile.delete());
  54. }
  55. /**
  56. * Test that when we create a new Package, we give it
  57. * the correct default content types
  58. */
  59. public void testCreateGetsContentTypes() throws Exception {
  60. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
  61. // Zap the target file, in case of an earlier run
  62. if(targetFile.exists()) targetFile.delete();
  63. OPCPackage pkg = OPCPackage.create(targetFile);
  64. // Check it has content types for rels and xml
  65. ContentTypeManager ctm = getContentTypeManager(pkg);
  66. assertEquals(
  67. "application/xml",
  68. ctm.getContentType(
  69. PackagingURIHelper.createPartName("/foo.xml")
  70. )
  71. );
  72. assertEquals(
  73. ContentTypes.RELATIONSHIPS_PART,
  74. ctm.getContentType(
  75. PackagingURIHelper.createPartName("/foo.rels")
  76. )
  77. );
  78. assertNull(
  79. ctm.getContentType(
  80. PackagingURIHelper.createPartName("/foo.txt")
  81. )
  82. );
  83. }
  84. /**
  85. * Test package creation.
  86. */
  87. public void testCreatePackageAddPart() throws Exception {
  88. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
  89. File expectedFileFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageOUTPUT.docx");
  90. // Zap the target file, in case of an earlier run
  91. if(targetFile.exists()) targetFile.delete();
  92. // Create a package
  93. OPCPackage pkg = OPCPackage.create(targetFile);
  94. PackagePartName corePartName = PackagingURIHelper
  95. .createPartName("/word/document.xml");
  96. pkg.addRelationship(corePartName, TargetMode.INTERNAL,
  97. PackageRelationshipTypes.CORE_DOCUMENT, "rId1");
  98. PackagePart corePart = pkg
  99. .createPart(
  100. corePartName,
  101. "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
  102. Document doc = DocumentHelper.createDocument();
  103. Namespace nsWordprocessinML = new Namespace("w",
  104. "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
  105. Element elDocument = doc.addElement(new QName("document",
  106. nsWordprocessinML));
  107. Element elBody = elDocument.addElement(new QName("body",
  108. nsWordprocessinML));
  109. Element elParagraph = elBody.addElement(new QName("p",
  110. nsWordprocessinML));
  111. Element elRun = elParagraph
  112. .addElement(new QName("r", nsWordprocessinML));
  113. Element elText = elRun.addElement(new QName("t", nsWordprocessinML));
  114. elText.setText("Hello Open XML !");
  115. StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
  116. pkg.close();
  117. //ZipFileAssert.assertEquals(expectedFile, targetFile);
  118. assertTrue(targetFile.delete());
  119. }
  120. /**
  121. * Tests that we can create a new package, add a core
  122. * document and another part, save and re-load and
  123. * have everything setup as expected
  124. */
  125. public void testCreatePackageWithCoreDocument() throws Exception {
  126. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  127. OPCPackage pkg = OPCPackage.create(baos);
  128. // Add a core document
  129. PackagePartName corePartName = PackagingURIHelper.createPartName("/xl/workbook.xml");
  130. // Create main part relationship
  131. pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT, "rId1");
  132. // Create main document part
  133. PackagePart corePart = pkg.createPart(corePartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml");
  134. // Put in some dummy content
  135. OutputStream coreOut = corePart.getOutputStream();
  136. coreOut.write("<dummy-xml />".getBytes());
  137. coreOut.close();
  138. // And another bit
  139. PackagePartName sheetPartName = PackagingURIHelper.createPartName("/xl/worksheets/sheet1.xml");
  140. PackageRelationship rel =
  141. corePart.addRelationship(sheetPartName, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", "rSheet1");
  142. PackagePart part = pkg.createPart(sheetPartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml");
  143. // Dummy content again
  144. coreOut = corePart.getOutputStream();
  145. coreOut.write("<dummy-xml2 />".getBytes());
  146. coreOut.close();
  147. //add a relationship with internal target: "#Sheet1!A1"
  148. corePart.addRelationship(new URI("#Sheet1!A1"), TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", "rId2");
  149. // Check things are as expected
  150. PackageRelationshipCollection coreRels =
  151. pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
  152. assertEquals(1, coreRels.size());
  153. PackageRelationship coreRel = coreRels.getRelationship(0);
  154. assertEquals("/", coreRel.getSourceURI().toString());
  155. assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString());
  156. assertNotNull(pkg.getPart(coreRel));
  157. // Save and re-load
  158. pkg.close();
  159. File tmp = TempFile.createTempFile("testCreatePackageWithCoreDocument", ".zip");
  160. FileOutputStream fout = new FileOutputStream(tmp);
  161. fout.write(baos.toByteArray());
  162. fout.close();
  163. pkg = OPCPackage.open(tmp.getPath());
  164. //tmp.delete();
  165. // Check still right
  166. coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
  167. assertEquals(1, coreRels.size());
  168. coreRel = coreRels.getRelationship(0);
  169. assertEquals("/", coreRel.getSourceURI().toString());
  170. assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString());
  171. corePart = pkg.getPart(coreRel);
  172. assertNotNull(corePart);
  173. PackageRelationshipCollection rels = corePart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
  174. assertEquals(1, rels.size());
  175. rel = rels.getRelationship(0);
  176. assertEquals("Sheet1!A1", rel.getTargetURI().getRawFragment());
  177. assertMSCompatibility(pkg);
  178. }
  179. private void assertMSCompatibility(OPCPackage pkg) throws Exception {
  180. PackagePartName relName = PackagingURIHelper.createPartName(PackageRelationship.getContainerPartRelationship());
  181. PackagePart relPart = pkg.getPart(relName);
  182. SAXReader reader = new SAXReader();
  183. Document xmlRelationshipsDoc = reader
  184. .read(relPart.getInputStream());
  185. Element root = xmlRelationshipsDoc.getRootElement();
  186. for (Iterator i = root
  187. .elementIterator(PackageRelationship.RELATIONSHIP_TAG_NAME); i
  188. .hasNext();) {
  189. Element element = (Element) i.next();
  190. String value = element.attribute(
  191. PackageRelationship.TARGET_ATTRIBUTE_NAME)
  192. .getValue();
  193. assertTrue("Root target must not start with a leadng slash ('/'): " + value, value.charAt(0) != '/');
  194. }
  195. }
  196. /**
  197. * Test package opening.
  198. */
  199. public void testOpenPackage() throws Exception {
  200. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageTMP.docx");
  201. File inputFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageINPUT.docx");
  202. File expectedFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageOUTPUT.docx");
  203. // Copy the input file in the output directory
  204. FileHelper.copyFile(inputFile, targetFile);
  205. // Create a package
  206. OPCPackage pkg = OPCPackage.open(targetFile.getAbsolutePath());
  207. // Modify core part
  208. PackagePartName corePartName = PackagingURIHelper
  209. .createPartName("/word/document.xml");
  210. PackagePart corePart = pkg.getPart(corePartName);
  211. // Delete some part to have a valid document
  212. for (PackageRelationship rel : corePart.getRelationships()) {
  213. corePart.removeRelationship(rel.getId());
  214. pkg.removePart(PackagingURIHelper.createPartName(PackagingURIHelper
  215. .resolvePartUri(corePart.getPartName().getURI(), rel
  216. .getTargetURI())));
  217. }
  218. // Create a content
  219. Document doc = DocumentHelper.createDocument();
  220. Namespace nsWordprocessinML = new Namespace("w",
  221. "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
  222. Element elDocument = doc.addElement(new QName("document",
  223. nsWordprocessinML));
  224. Element elBody = elDocument.addElement(new QName("body",
  225. nsWordprocessinML));
  226. Element elParagraph = elBody.addElement(new QName("p",
  227. nsWordprocessinML));
  228. Element elRun = elParagraph
  229. .addElement(new QName("r", nsWordprocessinML));
  230. Element elText = elRun.addElement(new QName("t", nsWordprocessinML));
  231. elText.setText("Hello Open XML !");
  232. StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
  233. // Save and close
  234. try {
  235. pkg.close();
  236. } catch (IOException e) {
  237. fail();
  238. }
  239. //ZipFileAssert.assertEquals(expectedFile, targetFile);
  240. assertTrue(targetFile.delete());
  241. }
  242. /**
  243. * Checks that we can write a package to a simple
  244. * OutputStream, in addition to the normal writing
  245. * to a file
  246. */
  247. public void testSaveToOutputStream() throws Exception {
  248. String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
  249. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
  250. OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
  251. FileOutputStream fout = new FileOutputStream(targetFile);
  252. p.save(fout);
  253. fout.close();
  254. // Compare the original and newly saved document
  255. assertTrue(targetFile.exists());
  256. //ZipFileAssert.assertEquals(originalFile, targetFile);
  257. assertTrue(targetFile.delete());
  258. }
  259. /**
  260. * Checks that we can open+read a package from a
  261. * simple InputStream, in addition to the normal
  262. * reading from a file
  263. */
  264. public void testOpenFromInputStream() throws Exception {
  265. String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
  266. FileInputStream finp = new FileInputStream(originalFile);
  267. OPCPackage p = OPCPackage.open(finp);
  268. assertNotNull(p);
  269. assertNotNull(p.getRelationships());
  270. assertEquals(12, p.getParts().size());
  271. // Check it has the usual bits
  272. assertTrue(p.hasRelationships());
  273. assertTrue(p.containPart(PackagingURIHelper.createPartName("/_rels/.rels")));
  274. }
  275. /**
  276. * TODO: fix and enable
  277. */
  278. public void disabled_testRemovePartRecursive() throws Exception {
  279. String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
  280. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx");
  281. File tempFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveTMP.docx");
  282. OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
  283. p.removePartRecursive(PackagingURIHelper.createPartName(new URI(
  284. "/word/document.xml")));
  285. p.save(tempFile.getAbsoluteFile());
  286. // Compare the original and newly saved document
  287. assertTrue(targetFile.exists());
  288. //ZipFileAssert.assertEquals(targetFile, tempFile);
  289. assertTrue(targetFile.delete());
  290. }
  291. public void testDeletePart() throws InvalidFormatException {
  292. TreeMap<PackagePartName, String> expectedValues;
  293. TreeMap<PackagePartName, String> values;
  294. values = new TreeMap<PackagePartName, String>();
  295. // Expected values
  296. expectedValues = new TreeMap<PackagePartName, String>();
  297. expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"),
  298. "application/vnd.openxmlformats-package.relationships+xml");
  299. expectedValues
  300. .put(PackagingURIHelper.createPartName("/docProps/app.xml"),
  301. "application/vnd.openxmlformats-officedocument.extended-properties+xml");
  302. expectedValues.put(PackagingURIHelper
  303. .createPartName("/docProps/core.xml"),
  304. "application/vnd.openxmlformats-package.core-properties+xml");
  305. expectedValues
  306. .put(PackagingURIHelper.createPartName("/word/fontTable.xml"),
  307. "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml");
  308. expectedValues.put(PackagingURIHelper
  309. .createPartName("/word/media/image1.gif"), "image/gif");
  310. expectedValues
  311. .put(PackagingURIHelper.createPartName("/word/settings.xml"),
  312. "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml");
  313. expectedValues
  314. .put(PackagingURIHelper.createPartName("/word/styles.xml"),
  315. "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml");
  316. expectedValues.put(PackagingURIHelper
  317. .createPartName("/word/theme/theme1.xml"),
  318. "application/vnd.openxmlformats-officedocument.theme+xml");
  319. expectedValues
  320. .put(
  321. PackagingURIHelper
  322. .createPartName("/word/webSettings.xml"),
  323. "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml");
  324. String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
  325. OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
  326. // Remove the core part
  327. p.deletePart(PackagingURIHelper.createPartName("/word/document.xml"));
  328. for (PackagePart part : p.getParts()) {
  329. values.put(part.getPartName(), part.getContentType());
  330. logger.log(POILogger.DEBUG, part.getPartName());
  331. }
  332. // Compare expected values with values return by the package
  333. for (PackagePartName partName : expectedValues.keySet()) {
  334. assertNotNull(values.get(partName));
  335. assertEquals(expectedValues.get(partName), values.get(partName));
  336. }
  337. // Don't save modifications
  338. p.revert();
  339. }
  340. public void testDeletePartRecursive() throws InvalidFormatException {
  341. TreeMap<PackagePartName, String> expectedValues;
  342. TreeMap<PackagePartName, String> values;
  343. values = new TreeMap<PackagePartName, String>();
  344. // Expected values
  345. expectedValues = new TreeMap<PackagePartName, String>();
  346. expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"),
  347. "application/vnd.openxmlformats-package.relationships+xml");
  348. expectedValues
  349. .put(PackagingURIHelper.createPartName("/docProps/app.xml"),
  350. "application/vnd.openxmlformats-officedocument.extended-properties+xml");
  351. expectedValues.put(PackagingURIHelper
  352. .createPartName("/docProps/core.xml"),
  353. "application/vnd.openxmlformats-package.core-properties+xml");
  354. String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
  355. OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
  356. // Remove the core part
  357. p.deletePartRecursive(PackagingURIHelper.createPartName("/word/document.xml"));
  358. for (PackagePart part : p.getParts()) {
  359. values.put(part.getPartName(), part.getContentType());
  360. logger.log(POILogger.DEBUG, part.getPartName());
  361. }
  362. // Compare expected values with values return by the package
  363. for (PackagePartName partName : expectedValues.keySet()) {
  364. assertNotNull(values.get(partName));
  365. assertEquals(expectedValues.get(partName), values.get(partName));
  366. }
  367. // Don't save modifications
  368. p.revert();
  369. }
  370. private static ContentTypeManager getContentTypeManager(OPCPackage pkg) throws Exception {
  371. Field f = OPCPackage.class.getDeclaredField("contentTypeManager");
  372. f.setAccessible(true);
  373. return (ContentTypeManager)f.get(pkg);
  374. }
  375. }