Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ZipPackage.java 22KB

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