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 19KB

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