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

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