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