Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

TestPackage.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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.InputStream;
  22. import java.io.OutputStream;
  23. import java.lang.reflect.Field;
  24. import java.net.URI;
  25. import java.util.HashMap;
  26. import java.util.List;
  27. import java.util.TreeMap;
  28. import java.util.regex.Pattern;
  29. import junit.framework.TestCase;
  30. import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
  31. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  32. import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
  33. import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
  34. import org.apache.poi.openxml4j.opc.internal.FileHelper;
  35. import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
  36. import org.apache.poi.util.DocumentHelper;
  37. import org.apache.poi.util.POILogFactory;
  38. import org.apache.poi.util.POILogger;
  39. import org.apache.poi.util.TempFile;
  40. import org.w3c.dom.Document;
  41. import org.w3c.dom.Element;
  42. import org.w3c.dom.NodeList;
  43. public final class TestPackage extends TestCase {
  44. private static final POILogger logger = POILogFactory.getLogger(TestPackage.class);
  45. /**
  46. * Test that just opening and closing the file doesn't alter the document.
  47. */
  48. public void testOpenSave() throws Exception {
  49. String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
  50. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
  51. OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
  52. p.save(targetFile.getAbsoluteFile());
  53. // Compare the original and newly saved document
  54. assertTrue(targetFile.exists());
  55. ZipFileAssert.assertEquals(new File(originalFile), targetFile);
  56. assertTrue(targetFile.delete());
  57. }
  58. /**
  59. * Test that when we create a new Package, we give it
  60. * the correct default content types
  61. */
  62. public void testCreateGetsContentTypes() throws Exception {
  63. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
  64. // Zap the target file, in case of an earlier run
  65. if(targetFile.exists()) targetFile.delete();
  66. OPCPackage pkg = OPCPackage.create(targetFile);
  67. // Check it has content types for rels and xml
  68. ContentTypeManager ctm = getContentTypeManager(pkg);
  69. assertEquals(
  70. "application/xml",
  71. ctm.getContentType(
  72. PackagingURIHelper.createPartName("/foo.xml")
  73. )
  74. );
  75. assertEquals(
  76. ContentTypes.RELATIONSHIPS_PART,
  77. ctm.getContentType(
  78. PackagingURIHelper.createPartName("/foo.rels")
  79. )
  80. );
  81. assertNull(
  82. ctm.getContentType(
  83. PackagingURIHelper.createPartName("/foo.txt")
  84. )
  85. );
  86. }
  87. /**
  88. * Test package creation.
  89. */
  90. public void testCreatePackageAddPart() throws Exception {
  91. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
  92. File expectedFile = OpenXML4JTestDataSamples.getSampleFile("TestCreatePackageOUTPUT.docx");
  93. // Zap the target file, in case of an earlier run
  94. if(targetFile.exists()) targetFile.delete();
  95. // Create a package
  96. OPCPackage pkg = OPCPackage.create(targetFile);
  97. PackagePartName corePartName = PackagingURIHelper
  98. .createPartName("/word/document.xml");
  99. pkg.addRelationship(corePartName, TargetMode.INTERNAL,
  100. PackageRelationshipTypes.CORE_DOCUMENT, "rId1");
  101. PackagePart corePart = pkg
  102. .createPart(
  103. corePartName,
  104. "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
  105. Document doc = DocumentHelper.createDocument();
  106. Element elDocument = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:document");
  107. doc.appendChild(elDocument);
  108. Element elBody = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:body");
  109. elDocument.appendChild(elBody);
  110. Element elParagraph = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:p");
  111. elBody.appendChild(elParagraph);
  112. Element elRun = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:r");
  113. elParagraph.appendChild(elRun);
  114. Element elText = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:t");
  115. elRun.appendChild(elText);
  116. elText.setTextContent("Hello Open XML !");
  117. StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
  118. pkg.close();
  119. ZipFileAssert.assertEquals(expectedFile, targetFile);
  120. assertTrue(targetFile.delete());
  121. }
  122. /**
  123. * Tests that we can create a new package, add a core
  124. * document and another part, save and re-load and
  125. * have everything setup as expected
  126. */
  127. public void testCreatePackageWithCoreDocument() throws Exception {
  128. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  129. OPCPackage pkg = OPCPackage.create(baos);
  130. // Add a core document
  131. PackagePartName corePartName = PackagingURIHelper.createPartName("/xl/workbook.xml");
  132. // Create main part relationship
  133. pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT, "rId1");
  134. // Create main document part
  135. PackagePart corePart = pkg.createPart(corePartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml");
  136. // Put in some dummy content
  137. OutputStream coreOut = corePart.getOutputStream();
  138. coreOut.write("<dummy-xml />".getBytes());
  139. coreOut.close();
  140. // And another bit
  141. PackagePartName sheetPartName = PackagingURIHelper.createPartName("/xl/worksheets/sheet1.xml");
  142. PackageRelationship rel =
  143. corePart.addRelationship(sheetPartName, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", "rSheet1");
  144. PackagePart part = pkg.createPart(sheetPartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml");
  145. // Dummy content again
  146. coreOut = corePart.getOutputStream();
  147. coreOut.write("<dummy-xml2 />".getBytes());
  148. coreOut.close();
  149. //add a relationship with internal target: "#Sheet1!A1"
  150. corePart.addRelationship(new URI("#Sheet1!A1"), TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", "rId2");
  151. // Check things are as expected
  152. PackageRelationshipCollection coreRels =
  153. pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
  154. assertEquals(1, coreRels.size());
  155. PackageRelationship coreRel = coreRels.getRelationship(0);
  156. assertEquals("/", coreRel.getSourceURI().toString());
  157. assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString());
  158. assertNotNull(pkg.getPart(coreRel));
  159. // Save and re-load
  160. pkg.close();
  161. File tmp = TempFile.createTempFile("testCreatePackageWithCoreDocument", ".zip");
  162. FileOutputStream fout = new FileOutputStream(tmp);
  163. fout.write(baos.toByteArray());
  164. fout.close();
  165. pkg = OPCPackage.open(tmp.getPath());
  166. //tmp.delete();
  167. // Check still right
  168. coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
  169. assertEquals(1, coreRels.size());
  170. coreRel = coreRels.getRelationship(0);
  171. assertEquals("/", coreRel.getSourceURI().toString());
  172. assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString());
  173. corePart = pkg.getPart(coreRel);
  174. assertNotNull(corePart);
  175. PackageRelationshipCollection rels = corePart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
  176. assertEquals(1, rels.size());
  177. rel = rels.getRelationship(0);
  178. assertEquals("Sheet1!A1", rel.getTargetURI().getRawFragment());
  179. assertMSCompatibility(pkg);
  180. }
  181. private void assertMSCompatibility(OPCPackage pkg) throws Exception {
  182. PackagePartName relName = PackagingURIHelper.createPartName(PackageRelationship.getContainerPartRelationship());
  183. PackagePart relPart = pkg.getPart(relName);
  184. Document xmlRelationshipsDoc = DocumentHelper.readDocument(relPart.getInputStream());
  185. Element root = xmlRelationshipsDoc.getDocumentElement();
  186. NodeList nodeList = root.getElementsByTagName(PackageRelationship.RELATIONSHIP_TAG_NAME);
  187. int nodeCount = nodeList.getLength();
  188. for (int i = 0; i < nodeCount; i++) {
  189. Element element = (Element) nodeList.item(i);
  190. String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME);
  191. assertTrue("Root target must not start with a leading slash ('/'): " + value, value.charAt(0) != '/');
  192. }
  193. }
  194. /**
  195. * Test package opening.
  196. */
  197. public void testOpenPackage() throws Exception {
  198. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageTMP.docx");
  199. File inputFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageINPUT.docx");
  200. File expectedFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageOUTPUT.docx");
  201. // Copy the input file in the output directory
  202. FileHelper.copyFile(inputFile, targetFile);
  203. // Create a package
  204. OPCPackage pkg = OPCPackage.open(targetFile.getAbsolutePath());
  205. // Modify core part
  206. PackagePartName corePartName = PackagingURIHelper
  207. .createPartName("/word/document.xml");
  208. PackagePart corePart = pkg.getPart(corePartName);
  209. // Delete some part to have a valid document
  210. for (PackageRelationship rel : corePart.getRelationships()) {
  211. corePart.removeRelationship(rel.getId());
  212. pkg.removePart(PackagingURIHelper.createPartName(PackagingURIHelper
  213. .resolvePartUri(corePart.getPartName().getURI(), rel
  214. .getTargetURI())));
  215. }
  216. // Create a content
  217. Document doc = DocumentHelper.createDocument();
  218. Element elDocument = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:document");
  219. doc.appendChild(elDocument);
  220. Element elBody = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:body");
  221. elDocument.appendChild(elBody);
  222. Element elParagraph = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:p");
  223. elBody.appendChild(elParagraph);
  224. Element elRun = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:r");
  225. elParagraph.appendChild(elRun);
  226. Element elText = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:t");
  227. elRun.appendChild(elText);
  228. elText.setTextContent("Hello Open XML !");
  229. StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
  230. // Save and close
  231. try {
  232. pkg.close();
  233. } catch (IOException e) {
  234. fail();
  235. }
  236. ZipFileAssert.assertEquals(expectedFile, targetFile);
  237. assertTrue(targetFile.delete());
  238. }
  239. /**
  240. * Checks that we can write a package to a simple
  241. * OutputStream, in addition to the normal writing
  242. * to a file
  243. */
  244. public void testSaveToOutputStream() throws Exception {
  245. String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
  246. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
  247. OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
  248. FileOutputStream fout = new FileOutputStream(targetFile);
  249. p.save(fout);
  250. fout.close();
  251. // Compare the original and newly saved document
  252. assertTrue(targetFile.exists());
  253. ZipFileAssert.assertEquals(new File(originalFile), targetFile);
  254. assertTrue(targetFile.delete());
  255. }
  256. /**
  257. * Checks that we can open+read a package from a
  258. * simple InputStream, in addition to the normal
  259. * reading from a file
  260. */
  261. public void testOpenFromInputStream() throws Exception {
  262. String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
  263. FileInputStream finp = new FileInputStream(originalFile);
  264. OPCPackage p = OPCPackage.open(finp);
  265. assertNotNull(p);
  266. assertNotNull(p.getRelationships());
  267. assertEquals(12, p.getParts().size());
  268. // Check it has the usual bits
  269. assertTrue(p.hasRelationships());
  270. assertTrue(p.containPart(PackagingURIHelper.createPartName("/_rels/.rels")));
  271. }
  272. /**
  273. * TODO: fix and enable
  274. */
  275. public void disabled_testRemovePartRecursive() throws Exception {
  276. String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
  277. File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx");
  278. File tempFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveTMP.docx");
  279. OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
  280. p.removePartRecursive(PackagingURIHelper.createPartName(new URI(
  281. "/word/document.xml")));
  282. p.save(tempFile.getAbsoluteFile());
  283. // Compare the original and newly saved document
  284. assertTrue(targetFile.exists());
  285. ZipFileAssert.assertEquals(targetFile, tempFile);
  286. assertTrue(targetFile.delete());
  287. }
  288. public void testDeletePart() throws InvalidFormatException {
  289. TreeMap<PackagePartName, String> expectedValues;
  290. TreeMap<PackagePartName, String> values;
  291. values = new TreeMap<PackagePartName, String>();
  292. // Expected values
  293. expectedValues = new TreeMap<PackagePartName, String>();
  294. expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"),
  295. "application/vnd.openxmlformats-package.relationships+xml");
  296. expectedValues
  297. .put(PackagingURIHelper.createPartName("/docProps/app.xml"),
  298. "application/vnd.openxmlformats-officedocument.extended-properties+xml");
  299. expectedValues.put(PackagingURIHelper
  300. .createPartName("/docProps/core.xml"),
  301. "application/vnd.openxmlformats-package.core-properties+xml");
  302. expectedValues
  303. .put(PackagingURIHelper.createPartName("/word/fontTable.xml"),
  304. "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml");
  305. expectedValues.put(PackagingURIHelper
  306. .createPartName("/word/media/image1.gif"), "image/gif");
  307. expectedValues
  308. .put(PackagingURIHelper.createPartName("/word/settings.xml"),
  309. "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml");
  310. expectedValues
  311. .put(PackagingURIHelper.createPartName("/word/styles.xml"),
  312. "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml");
  313. expectedValues.put(PackagingURIHelper
  314. .createPartName("/word/theme/theme1.xml"),
  315. "application/vnd.openxmlformats-officedocument.theme+xml");
  316. expectedValues
  317. .put(
  318. PackagingURIHelper
  319. .createPartName("/word/webSettings.xml"),
  320. "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml");
  321. String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
  322. OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
  323. // Remove the core part
  324. p.deletePart(PackagingURIHelper.createPartName("/word/document.xml"));
  325. for (PackagePart part : p.getParts()) {
  326. values.put(part.getPartName(), part.getContentType());
  327. logger.log(POILogger.DEBUG, part.getPartName());
  328. }
  329. // Compare expected values with values return by the package
  330. for (PackagePartName partName : expectedValues.keySet()) {
  331. assertNotNull(values.get(partName));
  332. assertEquals(expectedValues.get(partName), values.get(partName));
  333. }
  334. // Don't save modifications
  335. p.revert();
  336. }
  337. public void testDeletePartRecursive() throws InvalidFormatException {
  338. TreeMap<PackagePartName, String> expectedValues;
  339. TreeMap<PackagePartName, String> values;
  340. values = new TreeMap<PackagePartName, String>();
  341. // Expected values
  342. expectedValues = new TreeMap<PackagePartName, String>();
  343. expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"),
  344. "application/vnd.openxmlformats-package.relationships+xml");
  345. expectedValues
  346. .put(PackagingURIHelper.createPartName("/docProps/app.xml"),
  347. "application/vnd.openxmlformats-officedocument.extended-properties+xml");
  348. expectedValues.put(PackagingURIHelper
  349. .createPartName("/docProps/core.xml"),
  350. "application/vnd.openxmlformats-package.core-properties+xml");
  351. String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
  352. OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
  353. // Remove the core part
  354. p.deletePartRecursive(PackagingURIHelper.createPartName("/word/document.xml"));
  355. for (PackagePart part : p.getParts()) {
  356. values.put(part.getPartName(), part.getContentType());
  357. logger.log(POILogger.DEBUG, part.getPartName());
  358. }
  359. // Compare expected values with values return by the package
  360. for (PackagePartName partName : expectedValues.keySet()) {
  361. assertNotNull(values.get(partName));
  362. assertEquals(expectedValues.get(partName), values.get(partName));
  363. }
  364. // Don't save modifications
  365. p.revert();
  366. }
  367. /**
  368. * Test that we can open a file by path, and then
  369. * write changes to it.
  370. */
  371. public void testOpenFileThenOverwrite() throws Exception {
  372. File tempFile = TempFile.createTempFile("poiTesting","tmp");
  373. File origFile = OpenXML4JTestDataSamples.getSampleFile("TestPackageCommon.docx");
  374. FileHelper.copyFile(origFile, tempFile);
  375. // Open the temp file
  376. OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE);
  377. // Close it
  378. p.close();
  379. // Delete it
  380. assertTrue(tempFile.delete());
  381. // Reset
  382. FileHelper.copyFile(origFile, tempFile);
  383. p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE);
  384. // Save it to the same file - not allowed
  385. try {
  386. p.save(tempFile);
  387. fail("You shouldn't be able to call save(File) to overwrite the current file");
  388. } catch(InvalidOperationException e) {}
  389. p.close();
  390. // Delete it
  391. assertTrue(tempFile.delete());
  392. // Open it read only, then close and delete - allowed
  393. FileHelper.copyFile(origFile, tempFile);
  394. p = OPCPackage.open(tempFile.toString(), PackageAccess.READ);
  395. p.close();
  396. assertTrue(tempFile.delete());
  397. }
  398. /**
  399. * Test that we can open a file by path, save it
  400. * to another file, then delete both
  401. */
  402. public void testOpenFileThenSaveDelete() throws Exception {
  403. File tempFile = TempFile.createTempFile("poiTesting","tmp");
  404. File tempFile2 = TempFile.createTempFile("poiTesting","tmp");
  405. File origFile = OpenXML4JTestDataSamples.getSampleFile("TestPackageCommon.docx");
  406. FileHelper.copyFile(origFile, tempFile);
  407. // Open the temp file
  408. OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE);
  409. // Save it to a different file
  410. p.save(tempFile2);
  411. p.close();
  412. // Delete both the files
  413. assertTrue(tempFile.delete());
  414. assertTrue(tempFile2.delete());
  415. }
  416. private static ContentTypeManager getContentTypeManager(OPCPackage pkg) throws Exception {
  417. Field f = OPCPackage.class.getDeclaredField("contentTypeManager");
  418. f.setAccessible(true);
  419. return (ContentTypeManager)f.get(pkg);
  420. }
  421. public void testGetPartsByName() throws Exception {
  422. String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
  423. OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
  424. List<PackagePart> rs = pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml"));
  425. HashMap<String, PackagePart> selected = new HashMap<String, PackagePart>();
  426. for(PackagePart p : rs)
  427. selected.put(p.getPartName().getName(), p);
  428. assertEquals(6, selected.size());
  429. assertTrue(selected.containsKey("/word/document.xml"));
  430. assertTrue(selected.containsKey("/word/fontTable.xml"));
  431. assertTrue(selected.containsKey("/word/settings.xml"));
  432. assertTrue(selected.containsKey("/word/styles.xml"));
  433. assertTrue(selected.containsKey("/word/theme/theme1.xml"));
  434. assertTrue(selected.containsKey("/word/webSettings.xml"));
  435. }
  436. public void testGetPartSize() throws Exception {
  437. String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
  438. OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ);
  439. int checked = 0;
  440. for (PackagePart part : pkg.getParts()) {
  441. // Can get the size of zip parts
  442. if (part.getPartName().getName().equals("/word/document.xml")) {
  443. checked++;
  444. assertEquals(ZipPackagePart.class, part.getClass());
  445. assertEquals(6031l, part.getSize());
  446. }
  447. if (part.getPartName().getName().equals("/word/fontTable.xml")) {
  448. checked++;
  449. assertEquals(ZipPackagePart.class, part.getClass());
  450. assertEquals(1312l, part.getSize());
  451. }
  452. // But not from the others
  453. if (part.getPartName().getName().equals("/docProps/core.xml")) {
  454. checked++;
  455. assertEquals(PackagePropertiesPart.class, part.getClass());
  456. assertEquals(-1, part.getSize());
  457. }
  458. }
  459. // Ensure we actually found the parts we want to check
  460. assertEquals(3, checked);
  461. }
  462. public void testReplaceContentType() throws Exception {
  463. InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.xlsx");
  464. OPCPackage p = OPCPackage.open(is);
  465. ContentTypeManager mgr = getContentTypeManager(p);
  466. assertTrue(mgr.isContentTypeRegister("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"));
  467. assertFalse(mgr.isContentTypeRegister("application/vnd.ms-excel.sheet.macroEnabled.main+xml"));
  468. assertTrue(
  469. p.replaceContentType(
  470. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
  471. "application/vnd.ms-excel.sheet.macroEnabled.main+xml")
  472. );
  473. assertFalse(mgr.isContentTypeRegister("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"));
  474. assertTrue(mgr.isContentTypeRegister("application/vnd.ms-excel.sheet.macroEnabled.main+xml"));
  475. }
  476. }