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

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