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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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.IOException;
  18. import java.io.InputStream;
  19. import java.io.OutputStream;
  20. import java.util.Enumeration;
  21. import java.util.zip.ZipEntry;
  22. import java.util.zip.ZipFile;
  23. import java.util.zip.ZipInputStream;
  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.OpenXML4JException;
  28. import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
  29. import org.apache.poi.openxml4j.opc.internal.FileHelper;
  30. import org.apache.poi.openxml4j.opc.internal.MemoryPackagePart;
  31. import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
  32. import org.apache.poi.openxml4j.opc.internal.ZipContentTypeManager;
  33. import org.apache.poi.openxml4j.opc.internal.ZipHelper;
  34. import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPackagePropertiesMarshaller;
  35. import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPartMarshaller;
  36. import org.apache.poi.openxml4j.util.ZipEntrySource;
  37. import org.apache.poi.openxml4j.util.ZipFileZipEntrySource;
  38. import org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource;
  39. import org.apache.poi.util.POILogger;
  40. import org.apache.poi.util.POILogFactory;
  41. /**
  42. * Physical zip package.
  43. *
  44. * @author Julien Chable
  45. */
  46. public final class ZipPackage extends Package {
  47. private static POILogger logger = POILogFactory.getLogger(ZipPackage.class);
  48. /**
  49. * Zip archive, as either a file on disk,
  50. * or a stream
  51. */
  52. private final ZipEntrySource zipArchive;
  53. /**
  54. * Constructor. Creates a new ZipPackage.
  55. */
  56. public ZipPackage() {
  57. super(defaultPackageAccess);
  58. this.zipArchive = null;
  59. }
  60. /**
  61. * Constructor. <b>Operation not supported.</b>
  62. *
  63. * @param in
  64. * Zip input stream to load.
  65. * @param access
  66. * @throws IllegalArgumentException
  67. * If the specified input stream not an instance of
  68. * ZipInputStream.
  69. */
  70. ZipPackage(InputStream in, PackageAccess access) throws IOException {
  71. super(access);
  72. this.zipArchive = new ZipInputStreamZipEntrySource(
  73. new ZipInputStream(in)
  74. );
  75. }
  76. /**
  77. * Constructor. Opens a Zip based Open XML document.
  78. *
  79. * @param path
  80. * The path of the file to open or create.
  81. * @param access
  82. * The package access mode.
  83. * @throws InvalidFormatException
  84. * If the content type part parsing encounters an error.
  85. */
  86. ZipPackage(String path, PackageAccess access) {
  87. super(access);
  88. ZipFile zipFile = ZipHelper.openZipFile(path);
  89. if (zipFile == null)
  90. throw new InvalidOperationException(
  91. "Can't open the specified file: '" + path + "'");
  92. this.zipArchive = new ZipFileZipEntrySource(zipFile);
  93. }
  94. /**
  95. * Retrieves the parts from this package. We assume that the package has not
  96. * been yet inspect to retrieve all the parts, this method will open the
  97. * archive and look for all parts contain inside it. If the package part
  98. * list is not empty, it will be emptied.
  99. *
  100. * @return All parts contain in this package.
  101. * @throws InvalidFormatException
  102. * Throws if the package is not valid.
  103. */
  104. @Override
  105. protected PackagePart[] getPartsImpl() throws InvalidFormatException {
  106. if (this.partList == null) {
  107. // The package has just been created, we create an empty part
  108. // list.
  109. this.partList = new PackagePartCollection();
  110. }
  111. if (this.zipArchive == null) {
  112. return this.partList.values().toArray(
  113. new PackagePart[this.partList.values().size()]);
  114. }
  115. // First we need to parse the content type part
  116. Enumeration<? extends ZipEntry> entries = this.zipArchive.getEntries();
  117. while (entries.hasMoreElements()) {
  118. ZipEntry entry = entries.nextElement();
  119. if (entry.getName().equalsIgnoreCase(
  120. ContentTypeManager.CONTENT_TYPES_PART_NAME)) {
  121. try {
  122. this.contentTypeManager = new ZipContentTypeManager(
  123. getZipArchive().getInputStream(entry), this);
  124. } catch (IOException e) {
  125. throw new InvalidFormatException(e.getMessage());
  126. }
  127. break;
  128. }
  129. }
  130. // At this point, we should have loaded the content type part
  131. if (this.contentTypeManager == null) {
  132. throw new InvalidFormatException(
  133. "Package should contain a content type part [M1.13]");
  134. }
  135. // Now create all the relationships
  136. // (Need to create relationships before other
  137. // parts, otherwise we might create a part before
  138. // its relationship exists, and then it won't tie up)
  139. entries = this.zipArchive.getEntries();
  140. while (entries.hasMoreElements()) {
  141. ZipEntry entry = entries.nextElement();
  142. PackagePartName partName = buildPartName(entry);
  143. if(partName == null) continue;
  144. // Only proceed for Relationships at this stage
  145. String contentType = contentTypeManager.getContentType(partName);
  146. if (contentType != null && contentType.equals(ContentTypes.RELATIONSHIPS_PART)) {
  147. try {
  148. partList.put(partName, new ZipPackagePart(this, entry,
  149. partName, contentType));
  150. } catch (InvalidOperationException e) {
  151. throw new InvalidFormatException(e.getMessage());
  152. }
  153. }
  154. }
  155. // Then we can go through all the other parts
  156. entries = this.zipArchive.getEntries();
  157. while (entries.hasMoreElements()) {
  158. ZipEntry entry = entries.nextElement();
  159. PackagePartName partName = buildPartName(entry);
  160. if(partName == null) continue;
  161. String contentType = contentTypeManager
  162. .getContentType(partName);
  163. if (contentType != null && contentType.equals(ContentTypes.RELATIONSHIPS_PART)) {
  164. // Already handled
  165. }
  166. else if (contentType != null) {
  167. try {
  168. partList.put(partName, new ZipPackagePart(this, entry,
  169. partName, contentType));
  170. } catch (InvalidOperationException e) {
  171. throw new InvalidFormatException(e.getMessage());
  172. }
  173. } else {
  174. throw new InvalidFormatException(
  175. "The part "
  176. + partName.getURI().getPath()
  177. + " does not have any content type ! Rule: Package require content types when retrieving a part from a package. [M.1.14]");
  178. }
  179. }
  180. return partList.values().toArray(new ZipPackagePart[partList.size()]);
  181. }
  182. /**
  183. * Builds a PackagePartName for the given ZipEntry,
  184. * or null if it's the content types / invalid part
  185. */
  186. private PackagePartName buildPartName(ZipEntry entry) {
  187. try {
  188. // We get an error when we parse [Content_Types].xml
  189. // because it's not a valid URI.
  190. if (entry.getName().equalsIgnoreCase(
  191. ContentTypeManager.CONTENT_TYPES_PART_NAME)) {
  192. return null;
  193. }
  194. return PackagingURIHelper.createPartName(ZipHelper
  195. .getOPCNameFromZipItemName(entry.getName()));
  196. } catch (Exception e) {
  197. // We assume we can continue, even in degraded mode ...
  198. logger.log(POILogger.WARN,"Entry "
  199. + entry.getName()
  200. + " is not valid, so this part won't be add to the package.", e);
  201. return null;
  202. }
  203. }
  204. /**
  205. * Create a new MemoryPackagePart from the specified URI and content type
  206. *
  207. *
  208. * aram partName The part URI.
  209. *
  210. * @param contentType
  211. * The part content type.
  212. * @return The newly created zip package part, else <b>null</b>.
  213. */
  214. @Override
  215. protected PackagePart createPartImpl(PackagePartName partName,
  216. String contentType, boolean loadRelationships) {
  217. if (contentType == null)
  218. throw new IllegalArgumentException("contentType");
  219. if (partName == null)
  220. throw new IllegalArgumentException("partName");
  221. try {
  222. return new MemoryPackagePart(this, partName, contentType,
  223. loadRelationships);
  224. } catch (InvalidFormatException e) {
  225. logger.log(POILogger.WARN, e);
  226. return null;
  227. }
  228. }
  229. /**
  230. * Delete a part from the package
  231. *
  232. * @throws IllegalArgumentException
  233. * Throws if the part URI is nulll or invalid.
  234. */
  235. @Override
  236. protected void removePartImpl(PackagePartName partName) {
  237. if (partName == null)
  238. throw new IllegalArgumentException("partUri");
  239. }
  240. /**
  241. * Flush the package. Do nothing.
  242. */
  243. @Override
  244. protected void flushImpl() {
  245. // Do nothing
  246. }
  247. /**
  248. * Close and save the package.
  249. *
  250. * @see #close()
  251. */
  252. @Override
  253. protected void closeImpl() throws IOException {
  254. // Flush the package
  255. flush();
  256. // Save the content
  257. if (this.originalPackagePath != null
  258. && !"".equals(this.originalPackagePath)) {
  259. File targetFile = new File(this.originalPackagePath);
  260. if (targetFile.exists()) {
  261. // Case of a package previously open
  262. File tempFile = File.createTempFile(
  263. generateTempFileName(FileHelper
  264. .getDirectory(targetFile)), ".tmp");
  265. // Save the final package to a temporary file
  266. try {
  267. save(tempFile);
  268. this.zipArchive.close(); // Close the zip archive to be
  269. // able to delete it
  270. FileHelper.copyFile(tempFile, targetFile);
  271. } finally {
  272. // Either the save operation succeed or not, we delete the
  273. // temporary file
  274. if (!tempFile.delete()) {
  275. logger
  276. .log(POILogger.WARN,"The temporary file: '"
  277. + targetFile.getAbsolutePath()
  278. + "' cannot be deleted ! Make sure that no other application use it.");
  279. }
  280. }
  281. } else {
  282. throw new InvalidOperationException(
  283. "Can't close a package not previously open with the open() method !");
  284. }
  285. }
  286. }
  287. /**
  288. * Create a unique identifier to be use as a temp file name.
  289. *
  290. * @return A unique identifier use to be use as a temp file name.
  291. */
  292. private synchronized String generateTempFileName(File directory) {
  293. File tmpFilename;
  294. do {
  295. tmpFilename = new File(directory.getAbsoluteFile() + File.separator
  296. + "OpenXML4J" + System.nanoTime());
  297. } while (tmpFilename.exists());
  298. return FileHelper.getFilename(tmpFilename.getAbsoluteFile());
  299. }
  300. /**
  301. * Close the package without saving the document. Discard all the changes
  302. * made to this package.
  303. */
  304. @Override
  305. protected void revertImpl() {
  306. try {
  307. if (this.zipArchive != null)
  308. this.zipArchive.close();
  309. } catch (IOException e) {
  310. // Do nothing, user dont have to know
  311. }
  312. }
  313. /**
  314. * Implement the getPart() method to retrieve a part from its URI in the
  315. * current package
  316. *
  317. *
  318. * @see #getPart(PackageRelationship)
  319. */
  320. @Override
  321. protected PackagePart getPartImpl(PackagePartName partName) {
  322. if (partList.containsKey(partName)) {
  323. return partList.get(partName);
  324. }
  325. return null;
  326. }
  327. /**
  328. * Save this package into the specified stream
  329. *
  330. *
  331. * @param outputStream
  332. * The stream use to save this package.
  333. *
  334. * @see #save(OutputStream)
  335. */
  336. @Override
  337. public void saveImpl(OutputStream outputStream) {
  338. // Check that the document was open in write mode
  339. throwExceptionIfReadOnly();
  340. ZipOutputStream zos = null;
  341. try {
  342. if (!(outputStream instanceof ZipOutputStream))
  343. zos = new ZipOutputStream(outputStream);
  344. else
  345. zos = (ZipOutputStream) outputStream;
  346. // If the core properties part does not exist in the part list,
  347. // we save it as well
  348. if (this.getPartsByRelationshipType(
  349. PackageRelationshipTypes.CORE_PROPERTIES).size() == 0) {
  350. logger.log(POILogger.DEBUG,"Save core properties part");
  351. // We have to save the core properties part ...
  352. new ZipPackagePropertiesMarshaller().marshall(
  353. this.packageProperties, zos);
  354. // ... and to add its relationship ...
  355. this.relationships.addRelationship(this.packageProperties
  356. .getPartName().getURI(), TargetMode.INTERNAL,
  357. PackageRelationshipTypes.CORE_PROPERTIES, null);
  358. // ... and the content if it has not been added yet.
  359. if (!this.contentTypeManager
  360. .isContentTypeRegister(ContentTypes.CORE_PROPERTIES_PART)) {
  361. this.contentTypeManager.addContentType(
  362. this.packageProperties.getPartName(),
  363. ContentTypes.CORE_PROPERTIES_PART);
  364. }
  365. }
  366. // Save package relationships part.
  367. logger.log(POILogger.DEBUG,"Save package relationships");
  368. ZipPartMarshaller.marshallRelationshipPart(this.getRelationships(),
  369. PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME,
  370. zos);
  371. // Save content type part.
  372. logger.log(POILogger.DEBUG,"Save content types part");
  373. this.contentTypeManager.save(zos);
  374. // Save parts.
  375. for (PackagePart part : getParts()) {
  376. // If the part is a relationship part, we don't save it, it's
  377. // the source part that will do the job.
  378. if (part.isRelationshipPart())
  379. continue;
  380. logger.log(POILogger.DEBUG,"Save part '"
  381. + ZipHelper.getZipItemNameFromOPCName(part
  382. .getPartName().getName()) + "'");
  383. PartMarshaller marshaller = partMarshallers
  384. .get(part._contentType);
  385. if (marshaller != null) {
  386. if (!marshaller.marshall(part, zos)) {
  387. throw new OpenXML4JException(
  388. "The part "
  389. + part.getPartName().getURI()
  390. + " fail to be saved in the stream with marshaller "
  391. + marshaller);
  392. }
  393. } else {
  394. if (!defaultPartMarshaller.marshall(part, zos))
  395. throw new OpenXML4JException(
  396. "The part "
  397. + part.getPartName().getURI()
  398. + " fail to be saved in the stream with marshaller "
  399. + defaultPartMarshaller);
  400. }
  401. }
  402. zos.close();
  403. } catch (Exception e) {
  404. logger
  405. .log(POILogger.ERROR,"Fail to save: an error occurs while saving the package : "
  406. + e.getMessage());
  407. }
  408. }
  409. /**
  410. * Get the zip archive
  411. *
  412. * @return The zip archive.
  413. */
  414. public ZipEntrySource getZipArchive() {
  415. return zipArchive;
  416. }
  417. }