Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ZipPackage.java 22KB

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