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.

ZipPackage.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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.File;
  17. import java.io.FileInputStream;
  18. import java.io.FileNotFoundException;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.util.Enumeration;
  23. import java.util.zip.ZipEntry;
  24. import java.util.zip.ZipFile;
  25. import java.util.zip.ZipOutputStream;
  26. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  27. import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
  28. import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException;
  29. import org.apache.poi.openxml4j.exceptions.ODFNotOfficeXmlFileException;
  30. import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
  31. import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException;
  32. import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
  33. import org.apache.poi.openxml4j.opc.internal.FileHelper;
  34. import org.apache.poi.openxml4j.opc.internal.MemoryPackagePart;
  35. import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
  36. import org.apache.poi.openxml4j.opc.internal.ZipContentTypeManager;
  37. import org.apache.poi.openxml4j.opc.internal.ZipHelper;
  38. import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPartMarshaller;
  39. import org.apache.poi.openxml4j.util.ZipEntrySource;
  40. import org.apache.poi.openxml4j.util.ZipFileZipEntrySource;
  41. import org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource;
  42. import org.apache.poi.openxml4j.util.ZipSecureFile.ThresholdInputStream;
  43. import org.apache.poi.util.IOUtils;
  44. import org.apache.poi.util.POILogFactory;
  45. import org.apache.poi.util.POILogger;
  46. import org.apache.poi.util.TempFile;
  47. /**
  48. * Physical zip package.
  49. */
  50. public final class ZipPackage extends OPCPackage {
  51. private static final String MIMETYPE = "mimetype";
  52. private static final String SETTINGS_XML = "settings.xml";
  53. private static final POILogger LOG = POILogFactory.getLogger(ZipPackage.class);
  54. /**
  55. * Zip archive, as either a file on disk,
  56. * or a stream
  57. */
  58. private final ZipEntrySource zipArchive;
  59. /**
  60. * Constructor. Creates a new, empty ZipPackage.
  61. */
  62. public ZipPackage() {
  63. super(defaultPackageAccess);
  64. this.zipArchive = null;
  65. try {
  66. this.contentTypeManager = new ZipContentTypeManager(null, this);
  67. } catch (InvalidFormatException e) {
  68. LOG.log(POILogger.WARN,"Could not parse ZipPackage", e);
  69. }
  70. }
  71. /**
  72. * Constructor. Opens a Zip based Open XML document from
  73. * an InputStream.
  74. *
  75. * @param in
  76. * Zip input stream to load.
  77. * @param access
  78. * The package access mode.
  79. * @throws IllegalArgumentException
  80. * If the specified input stream not an instance of
  81. * ZipInputStream.
  82. * @throws IOException
  83. * if input stream cannot be opened, read, or closed
  84. */
  85. ZipPackage(InputStream in, PackageAccess access) throws IOException {
  86. super(access);
  87. ThresholdInputStream zis = ZipHelper.openZipStream(in);
  88. try {
  89. this.zipArchive = new ZipInputStreamZipEntrySource(zis);
  90. } catch (final IOException e) {
  91. IOUtils.closeQuietly(zis);
  92. throw new IOException("Failed to read zip entry source", e);
  93. }
  94. }
  95. /**
  96. * Constructor. Opens a Zip based Open XML document from a file.
  97. *
  98. * @param path
  99. * The path of the file to open or create.
  100. * @param access
  101. * The package access mode.
  102. * @throws InvalidOperationException If the zip file cannot be opened.
  103. */
  104. ZipPackage(String path, PackageAccess access) throws InvalidOperationException {
  105. this(new File(path), access);
  106. }
  107. /**
  108. * Constructor. Opens a Zip based Open XML document from a File.
  109. *
  110. * @param file
  111. * The file to open or create.
  112. * @param access
  113. * The package access mode.
  114. * @throws InvalidOperationException If the zip file cannot be opened.
  115. */
  116. ZipPackage(File file, PackageAccess access) throws InvalidOperationException {
  117. super(access);
  118. ZipEntrySource ze;
  119. try {
  120. final ZipFile zipFile = ZipHelper.openZipFile(file); // NOSONAR
  121. ze = new ZipFileZipEntrySource(zipFile);
  122. } catch (IOException e) {
  123. // probably not happening with write access - not sure how to handle the default read-write access ...
  124. if (access == PackageAccess.WRITE) {
  125. throw new InvalidOperationException("Can't open the specified file: '" + file + "'", e);
  126. }
  127. LOG.log(POILogger.ERROR, "Error in zip file "+file+" - falling back to stream processing (i.e. ignoring zip central directory)");
  128. ze = openZipEntrySourceStream(file);
  129. }
  130. this.zipArchive = ze;
  131. }
  132. private static ZipEntrySource openZipEntrySourceStream(File file) throws InvalidOperationException {
  133. final FileInputStream fis;
  134. // Acquire a resource that is needed to read the next level of openZipEntrySourceStream
  135. try {
  136. // open the file input stream
  137. fis = new FileInputStream(file); // NOSONAR
  138. } catch (final FileNotFoundException e) {
  139. // If the source cannot be acquired, abort (no resources to free at this level)
  140. throw new InvalidOperationException("Can't open the specified file input stream from file: '" + file + "'", e);
  141. }
  142. // If an error occurs while reading the next level of openZipEntrySourceStream, free the acquired resource
  143. try {
  144. // read from the file input stream
  145. return openZipEntrySourceStream(fis);
  146. } catch (final Exception e) {
  147. // abort: close the file input stream
  148. IOUtils.closeQuietly(fis);
  149. if (e instanceof InvalidOperationException) {
  150. throw (InvalidOperationException)e;
  151. } else {
  152. throw new InvalidOperationException("Failed to read the file input stream from file: '" + file + "'", e);
  153. }
  154. }
  155. }
  156. private static ZipEntrySource openZipEntrySourceStream(FileInputStream fis) throws InvalidOperationException {
  157. final ThresholdInputStream zis;
  158. // Acquire a resource that is needed to read the next level of openZipEntrySourceStream
  159. try {
  160. // open the zip input stream
  161. zis = ZipHelper.openZipStream(fis); // NOSONAR
  162. } catch (final IOException e) {
  163. // If the source cannot be acquired, abort (no resources to free at this level)
  164. throw new InvalidOperationException("Could not open the file input stream", e);
  165. }
  166. // If an error occurs while reading the next level of openZipEntrySourceStream, free the acquired resource
  167. try {
  168. // read from the zip input stream
  169. return openZipEntrySourceStream(zis);
  170. } catch (final Exception e) {
  171. // abort: close the zip input stream
  172. IOUtils.closeQuietly(zis);
  173. if (e instanceof InvalidOperationException) {
  174. throw (InvalidOperationException)e;
  175. } else {
  176. throw new InvalidOperationException("Failed to read the zip entry source stream", e);
  177. }
  178. }
  179. }
  180. private static ZipEntrySource openZipEntrySourceStream(ThresholdInputStream zis) throws InvalidOperationException {
  181. // Acquire the final level resource. If this is acquired successfully, the zip package was read successfully from the input stream
  182. try {
  183. // open the zip entry source stream
  184. return new ZipInputStreamZipEntrySource(zis);
  185. } catch (IOException e) {
  186. throw new InvalidOperationException("Could not open the specified zip entry source stream", e);
  187. }
  188. }
  189. /**
  190. * Constructor. Opens a Zip based Open XML document from
  191. * a custom ZipEntrySource, typically an open archive
  192. * from another system
  193. *
  194. * @param zipEntry
  195. * Zip data to load.
  196. * @param access
  197. * The package access mode.
  198. */
  199. ZipPackage(ZipEntrySource zipEntry, PackageAccess access) {
  200. super(access);
  201. this.zipArchive = zipEntry;
  202. }
  203. /**
  204. * Retrieves the parts from this package. We assume that the package has not
  205. * been yet inspect to retrieve all the parts, this method will open the
  206. * archive and look for all parts contain inside it. If the package part
  207. * list is not empty, it will be emptied.
  208. *
  209. * @return All parts contain in this package.
  210. * @throws InvalidFormatException if the package is not valid.
  211. */
  212. @Override
  213. protected PackagePart[] getPartsImpl() throws InvalidFormatException {
  214. if (this.partList == null) {
  215. // The package has just been created, we create an empty part
  216. // list.
  217. this.partList = new PackagePartCollection();
  218. }
  219. if (this.zipArchive == null) {
  220. return this.partList.values().toArray(
  221. new PackagePart[this.partList.values().size()]);
  222. }
  223. // First we need to parse the content type part
  224. Enumeration<? extends ZipEntry> entries = this.zipArchive.getEntries();
  225. while (entries.hasMoreElements()) {
  226. ZipEntry entry = entries.nextElement();
  227. if (entry.getName().equalsIgnoreCase(
  228. ContentTypeManager.CONTENT_TYPES_PART_NAME)) {
  229. try {
  230. this.contentTypeManager = new ZipContentTypeManager(
  231. getZipArchive().getInputStream(entry), this);
  232. } catch (IOException e) {
  233. throw new InvalidFormatException(e.getMessage(), e);
  234. }
  235. break;
  236. }
  237. }
  238. // At this point, we should have loaded the content type part
  239. if (this.contentTypeManager == null) {
  240. // Is it a different Zip-based format?
  241. int numEntries = 0;
  242. boolean hasMimetype = false;
  243. boolean hasSettingsXML = false;
  244. entries = this.zipArchive.getEntries();
  245. while (entries.hasMoreElements()) {
  246. final ZipEntry entry = entries.nextElement();
  247. final String name = entry.getName();
  248. if (MIMETYPE.equals(name)) {
  249. hasMimetype = true;
  250. }
  251. if (SETTINGS_XML.equals(name)) {
  252. hasSettingsXML = true;
  253. }
  254. numEntries++;
  255. }
  256. if (hasMimetype && hasSettingsXML) {
  257. throw new ODFNotOfficeXmlFileException(
  258. "The supplied data appears to be in ODF (Open Document) Format. " +
  259. "Formats like these (eg ODS, ODP) are not supported, try Apache ODFToolkit");
  260. }
  261. if (numEntries == 0) {
  262. throw new NotOfficeXmlFileException(
  263. "No valid entries or contents found, this is not a valid OOXML " +
  264. "(Office Open XML) file");
  265. }
  266. // Fallback exception
  267. throw new InvalidFormatException(
  268. "Package should contain a content type part [M1.13]");
  269. }
  270. // Now create all the relationships
  271. // (Need to create relationships before other
  272. // parts, otherwise we might create a part before
  273. // its relationship exists, and then it won't tie up)
  274. entries = this.zipArchive.getEntries();
  275. while (entries.hasMoreElements()) {
  276. ZipEntry entry = entries.nextElement();
  277. PackagePartName partName = buildPartName(entry);
  278. if(partName == null) {
  279. continue;
  280. }
  281. // Only proceed for Relationships at this stage
  282. String contentType = contentTypeManager.getContentType(partName);
  283. if (contentType != null && contentType.equals(ContentTypes.RELATIONSHIPS_PART)) {
  284. try {
  285. PackagePart part = new ZipPackagePart(this, entry, partName, contentType);
  286. partList.put(partName, part);
  287. } catch (InvalidOperationException e) {
  288. throw new InvalidFormatException(e.getMessage(), e);
  289. }
  290. }
  291. }
  292. // Then we can go through all the other parts
  293. entries = this.zipArchive.getEntries();
  294. while (entries.hasMoreElements()) {
  295. ZipEntry entry = entries.nextElement();
  296. PackagePartName partName = buildPartName(entry);
  297. if(partName == null) {
  298. continue;
  299. }
  300. String contentType = contentTypeManager.getContentType(partName);
  301. if (contentType != null && contentType.equals(ContentTypes.RELATIONSHIPS_PART)) {
  302. // Already handled
  303. }
  304. else if (contentType != null) {
  305. try {
  306. PackagePart part = new ZipPackagePart(this, entry, partName, contentType);
  307. partList.put(partName, part);
  308. } catch (InvalidOperationException e) {
  309. throw new InvalidFormatException(e.getMessage(), e);
  310. }
  311. } else {
  312. throw new InvalidFormatException(
  313. "The part " + partName.getURI().getPath()
  314. + " does not have any content type ! Rule: Package require content types when retrieving a part from a package. [M.1.14]");
  315. }
  316. }
  317. return partList.values().toArray(new ZipPackagePart[partList.size()]);
  318. }
  319. /**
  320. * Builds a PackagePartName for the given ZipEntry,
  321. * or null if it's the content types / invalid part
  322. */
  323. private PackagePartName buildPartName(ZipEntry entry) {
  324. try {
  325. // We get an error when we parse [Content_Types].xml
  326. // because it's not a valid URI.
  327. if (entry.getName().equalsIgnoreCase(
  328. ContentTypeManager.CONTENT_TYPES_PART_NAME)) {
  329. return null;
  330. }
  331. return PackagingURIHelper.createPartName(ZipHelper
  332. .getOPCNameFromZipItemName(entry.getName()));
  333. } catch (Exception e) {
  334. // We assume we can continue, even in degraded mode ...
  335. LOG.log(POILogger.WARN,"Entry "
  336. + entry.getName()
  337. + " is not valid, so this part won't be add to the package.", e);
  338. return null;
  339. }
  340. }
  341. /**
  342. * Create a new MemoryPackagePart from the specified URI and content type
  343. *
  344. *
  345. * aram partName The part URI.
  346. *
  347. * @param contentType
  348. * The part content type.
  349. * @return The newly created zip package part, else <b>null</b>.
  350. */
  351. @Override
  352. protected PackagePart createPartImpl(PackagePartName partName,
  353. String contentType, boolean loadRelationships) {
  354. if (contentType == null) {
  355. throw new IllegalArgumentException("contentType");
  356. }
  357. if (partName == null) {
  358. throw new IllegalArgumentException("partName");
  359. }
  360. try {
  361. return new MemoryPackagePart(this, partName, contentType, loadRelationships);
  362. } catch (InvalidFormatException e) {
  363. LOG.log(POILogger.WARN, e);
  364. return null;
  365. }
  366. }
  367. /**
  368. * Delete a part from the package
  369. *
  370. * @throws IllegalArgumentException
  371. * Throws if the part URI is nulll or invalid.
  372. */
  373. @Override
  374. protected void removePartImpl(PackagePartName partName) {
  375. if (partName == null) {
  376. throw new IllegalArgumentException("partUri");
  377. }
  378. }
  379. /**
  380. * Flush the package. Do nothing.
  381. */
  382. @Override
  383. protected void flushImpl() {
  384. // Do nothing
  385. }
  386. /**
  387. * Close and save the package.
  388. *
  389. * @see #close()
  390. */
  391. @Override
  392. protected void closeImpl() throws IOException {
  393. // Flush the package
  394. flush();
  395. if (this.originalPackagePath == null || "".equals(this.originalPackagePath)) {
  396. return;
  397. }
  398. // Save the content
  399. File targetFile = new File(this.originalPackagePath);
  400. if (!targetFile.exists()) {
  401. throw new InvalidOperationException(
  402. "Can't close a package not previously open with the open() method !");
  403. }
  404. // Case of a package previously open
  405. String tempFileName = generateTempFileName(FileHelper.getDirectory(targetFile));
  406. File tempFile = TempFile.createTempFile(tempFileName, ".tmp");
  407. // Save the final package to a temporary file
  408. try {
  409. save(tempFile);
  410. } finally {
  411. // Close the current zip file, so we can overwrite it on all platforms
  412. IOUtils.closeQuietly(this.zipArchive);
  413. try {
  414. // Copy the new file over the old one
  415. FileHelper.copyFile(tempFile, targetFile);
  416. } finally {
  417. // Either the save operation succeed or not, we delete the temporary file
  418. if (!tempFile.delete()) {
  419. LOG.log(POILogger.WARN, "The temporary file: '"
  420. + targetFile.getAbsolutePath()
  421. + "' cannot be deleted ! Make sure that no other application use it.");
  422. }
  423. }
  424. }
  425. }
  426. /**
  427. * Create a unique identifier to be use as a temp file name.
  428. *
  429. * @return A unique identifier use to be use as a temp file name.
  430. */
  431. private synchronized String generateTempFileName(File directory) {
  432. File tmpFilename;
  433. do {
  434. tmpFilename = new File(directory.getAbsoluteFile() + File.separator
  435. + "OpenXML4J" + System.nanoTime());
  436. } while (tmpFilename.exists());
  437. return FileHelper.getFilename(tmpFilename.getAbsoluteFile());
  438. }
  439. /**
  440. * Close the package without saving the document. Discard all the changes
  441. * made to this package.
  442. */
  443. @Override
  444. protected void revertImpl() {
  445. try {
  446. if (this.zipArchive != null) {
  447. this.zipArchive.close();
  448. }
  449. } catch (IOException e) {
  450. // Do nothing, user dont have to know
  451. }
  452. }
  453. /**
  454. * Implement the getPart() method to retrieve a part from its URI in the
  455. * current package
  456. *
  457. *
  458. * @see #getPart(PackageRelationship)
  459. */
  460. @Override
  461. protected PackagePart getPartImpl(PackagePartName partName) {
  462. if (partList.containsKey(partName)) {
  463. return partList.get(partName);
  464. }
  465. return null;
  466. }
  467. /**
  468. * Save this package into the specified stream
  469. *
  470. *
  471. * @param outputStream
  472. * The stream use to save this package.
  473. *
  474. * @see #save(OutputStream)
  475. */
  476. @Override
  477. public void saveImpl(OutputStream outputStream) {
  478. // Check that the document was open in write mode
  479. throwExceptionIfReadOnly();
  480. final ZipOutputStream zos;
  481. try {
  482. if (!(outputStream instanceof ZipOutputStream)) {
  483. zos = new ZipOutputStream(outputStream);
  484. } else {
  485. zos = (ZipOutputStream) outputStream;
  486. }
  487. // If the core properties part does not exist in the part list,
  488. // we save it as well
  489. if (this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size() == 0 &&
  490. this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES_ECMA376).size() == 0 ) {
  491. LOG.log(POILogger.DEBUG,"Save core properties part");
  492. // Ensure that core properties are added if missing
  493. getPackageProperties();
  494. // Add core properties to part list ...
  495. addPackagePart(this.packageProperties);
  496. // ... and to add its relationship ...
  497. this.relationships.addRelationship(this.packageProperties
  498. .getPartName().getURI(), TargetMode.INTERNAL,
  499. PackageRelationshipTypes.CORE_PROPERTIES, null);
  500. // ... and the content if it has not been added yet.
  501. if (!this.contentTypeManager
  502. .isContentTypeRegister(ContentTypes.CORE_PROPERTIES_PART)) {
  503. this.contentTypeManager.addContentType(
  504. this.packageProperties.getPartName(),
  505. ContentTypes.CORE_PROPERTIES_PART);
  506. }
  507. }
  508. // Save package relationships part.
  509. LOG.log(POILogger.DEBUG,"Save package relationships");
  510. ZipPartMarshaller.marshallRelationshipPart(this.getRelationships(),
  511. PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME,
  512. zos);
  513. // Save content type part.
  514. LOG.log(POILogger.DEBUG,"Save content types part");
  515. this.contentTypeManager.save(zos);
  516. // Save parts.
  517. for (PackagePart part : getParts()) {
  518. // If the part is a relationship part, we don't save it, it's
  519. // the source part that will do the job.
  520. if (part.isRelationshipPart()) {
  521. continue;
  522. }
  523. final PackagePartName ppn = part.getPartName();
  524. LOG.log(POILogger.DEBUG,"Save part '" + ZipHelper.getZipItemNameFromOPCName(ppn.getName()) + "'");
  525. PartMarshaller marshaller = partMarshallers.get(part._contentType);
  526. String errMsg = "The part " + ppn.getURI() + " failed to be saved in the stream with marshaller ";
  527. if (marshaller != null) {
  528. if (!marshaller.marshall(part, zos)) {
  529. throw new OpenXML4JException(errMsg + marshaller);
  530. }
  531. } else {
  532. if (!defaultPartMarshaller.marshall(part, zos)) {
  533. throw new OpenXML4JException(errMsg + defaultPartMarshaller);
  534. }
  535. }
  536. }
  537. zos.close();
  538. } catch (OpenXML4JRuntimeException e) {
  539. // no need to wrap this type of Exception
  540. throw e;
  541. } catch (Exception e) {
  542. throw new OpenXML4JRuntimeException(
  543. "Fail to save: an error occurs while saving the package : "
  544. + e.getMessage(), e);
  545. }
  546. }
  547. /**
  548. * Get the zip archive
  549. *
  550. * @return The zip archive.
  551. */
  552. public ZipEntrySource getZipArchive() {
  553. return zipArchive;
  554. }
  555. }