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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
|
/* ====================================================================
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 com.google.common.hash.Hashing;
import com.google.common.io.Files;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.POIDataSamples;
import org.apache.poi.POITestCase;
import org.apache.poi.UnsupportedFileFormatException;
import org.apache.poi.extractor.POITextExtractor;
import org.apache.poi.ooxml.POIXMLException;
import org.apache.poi.ooxml.extractor.ExtractorFactory;
import org.apache.poi.ooxml.util.DocumentHelper;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException;
import org.apache.poi.openxml4j.exceptions.ODFNotOfficeXmlFileException;
import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
import org.apache.poi.openxml4j.opc.internal.FileHelper;
import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
import org.apache.poi.openxml4j.opc.internal.ZipHelper;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.apache.poi.util.TempFile;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFRelation;
import org.apache.xmlbeans.XmlException;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public final class TestPackage {
private static final POILogger logger = POILogFactory.getLogger(TestPackage.class);
@Rule
public ExpectedException expectedEx = ExpectedException.none();
/**
* Test that just opening and closing the file doesn't alter the document.
*/
@Test
public void openSave() throws IOException, InvalidFormatException {
String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
try {
p.save(targetFile.getAbsoluteFile());
// Compare the original and newly saved document
assertTrue(targetFile.exists());
ZipFileAssert.assertEquals(new File(originalFile), targetFile);
assertTrue(targetFile.delete());
} finally {
// use revert to not re-write the input file
p.revert();
}
}
/**
* Test that when we create a new Package, we give it
* the correct default content types
*/
@Test
public void createGetsContentTypes()
throws IOException, InvalidFormatException, SecurityException, IllegalArgumentException {
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
// Zap the target file, in case of an earlier run
if(targetFile.exists()) {
assertTrue(targetFile.delete());
}
@SuppressWarnings("resource")
OPCPackage pkg = OPCPackage.create(targetFile);
// Check it has content types for rels and xml
ContentTypeManager ctm = getContentTypeManager(pkg);
assertEquals(
"application/xml",
ctm.getContentType(
PackagingURIHelper.createPartName("/foo.xml")
)
);
assertEquals(
ContentTypes.RELATIONSHIPS_PART,
ctm.getContentType(
PackagingURIHelper.createPartName("/foo.rels")
)
);
assertNull(
ctm.getContentType(
PackagingURIHelper.createPartName("/foo.txt")
)
);
pkg.revert();
}
/**
* Test package creation.
*/
@Test
public void createPackageAddPart() throws IOException, InvalidFormatException {
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx");
File expectedFile = OpenXML4JTestDataSamples.getSampleFile("TestCreatePackageOUTPUT.docx");
// Zap the target file, in case of an earlier run
if(targetFile.exists()) {
assertTrue(targetFile.delete());
}
// Create a package
OPCPackage pkg = OPCPackage.create(targetFile);
PackagePartName corePartName = PackagingURIHelper
.createPartName("/word/document.xml");
pkg.addRelationship(corePartName, TargetMode.INTERNAL,
PackageRelationshipTypes.CORE_DOCUMENT, "rId1");
PackagePart corePart = pkg
.createPart(
corePartName,
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
Document doc = DocumentHelper.createDocument();
Element elDocument = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:document");
doc.appendChild(elDocument);
Element elBody = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:body");
elDocument.appendChild(elBody);
Element elParagraph = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:p");
elBody.appendChild(elParagraph);
Element elRun = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:r");
elParagraph.appendChild(elRun);
Element elText = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:t");
elRun.appendChild(elText);
elText.setTextContent("Hello Open XML !");
StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
pkg.close();
ZipFileAssert.assertEquals(expectedFile, targetFile);
assertTrue(targetFile.delete());
}
/**
* Tests that we can create a new package, add a core
* document and another part, save and re-load and
* have everything setup as expected
*/
@Test
public void createPackageWithCoreDocument() throws IOException, InvalidFormatException, URISyntaxException, SAXException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OPCPackage pkg = OPCPackage.create(baos);
// Add a core document
PackagePartName corePartName = PackagingURIHelper.createPartName("/xl/workbook.xml");
// Create main part relationship
pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT, "rId1");
// Create main document part
PackagePart corePart = pkg.createPart(corePartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml");
// Put in some dummy content
OutputStream coreOut = corePart.getOutputStream();
coreOut.write("<dummy-xml />".getBytes(StandardCharsets.UTF_8));
coreOut.close();
// And another bit
PackagePartName sheetPartName = PackagingURIHelper.createPartName("/xl/worksheets/sheet1.xml");
PackageRelationship rel =
corePart.addRelationship(sheetPartName, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", "rSheet1");
assertNotNull(rel);
PackagePart part = pkg.createPart(sheetPartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml");
assertNotNull(part);
// Dummy content again
coreOut = corePart.getOutputStream();
coreOut.write("<dummy-xml2 />".getBytes(StandardCharsets.UTF_8));
coreOut.close();
//add a relationship with internal target: "#Sheet1!A1"
corePart.addRelationship(new URI("#Sheet1!A1"), TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", "rId2");
// Check things are as expected
PackageRelationshipCollection coreRels =
pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
assertEquals(1, coreRels.size());
PackageRelationship coreRel = coreRels.getRelationship(0);
assertNotNull(coreRel);
assertEquals("/", coreRel.getSourceURI().toString());
assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString());
assertNotNull(pkg.getPart(coreRel));
// Save and re-load
pkg.close();
File tmp = TempFile.createTempFile("testCreatePackageWithCoreDocument", ".zip");
try (OutputStream fout = new FileOutputStream(tmp)) {
fout.write(baos.toByteArray());
}
pkg = OPCPackage.open(tmp.getPath());
//tmp.delete();
try {
// Check still right
coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
assertEquals(1, coreRels.size());
coreRel = coreRels.getRelationship(0);
assertNotNull(coreRel);
assertEquals("/", coreRel.getSourceURI().toString());
assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString());
corePart = pkg.getPart(coreRel);
assertNotNull(corePart);
PackageRelationshipCollection rels = corePart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
assertEquals(1, rels.size());
rel = rels.getRelationship(0);
assertNotNull(rel);
assertEquals("Sheet1!A1", rel.getTargetURI().getRawFragment());
assertMSCompatibility(pkg);
} finally {
pkg.close();
}
}
private void assertMSCompatibility(OPCPackage pkg) throws IOException, InvalidFormatException, SAXException {
PackagePartName relName = PackagingURIHelper.createPartName(PackageRelationship.getContainerPartRelationship());
PackagePart relPart = pkg.getPart(relName);
Document xmlRelationshipsDoc = DocumentHelper.readDocument(relPart.getInputStream());
Element root = xmlRelationshipsDoc.getDocumentElement();
NodeList nodeList = root.getElementsByTagName(PackageRelationship.RELATIONSHIP_TAG_NAME);
int nodeCount = nodeList.getLength();
for (int i = 0; i < nodeCount; i++) {
Element element = (Element) nodeList.item(i);
String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME);
assertTrue("Root target must not start with a leading slash ('/'): " + value, value.charAt(0) != '/');
}
}
/**
* Test package opening.
*/
@Test
public void openPackage() throws IOException, InvalidFormatException {
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageTMP.docx");
File inputFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageINPUT.docx");
File expectedFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageOUTPUT.docx");
// Copy the input file in the output directory
FileHelper.copyFile(inputFile, targetFile);
// Create a package
OPCPackage pkg = OPCPackage.open(targetFile.getAbsolutePath());
// Modify core part
PackagePartName corePartName = PackagingURIHelper
.createPartName("/word/document.xml");
PackagePart corePart = pkg.getPart(corePartName);
// Delete some part to have a valid document
for (PackageRelationship rel : corePart.getRelationships()) {
corePart.removeRelationship(rel.getId());
pkg.removePart(PackagingURIHelper.createPartName(PackagingURIHelper
.resolvePartUri(corePart.getPartName().getURI(), rel
.getTargetURI())));
}
// Create a content
Document doc = DocumentHelper.createDocument();
Element elDocument = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:document");
doc.appendChild(elDocument);
Element elBody = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:body");
elDocument.appendChild(elBody);
Element elParagraph = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:p");
elBody.appendChild(elParagraph);
Element elRun = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:r");
elParagraph.appendChild(elRun);
Element elText = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:t");
elRun.appendChild(elText);
elText.setTextContent("Hello Open XML !");
StreamHelper.saveXmlInStream(doc, corePart.getOutputStream());
// Save and close
try {
pkg.close();
} catch (IOException e) {
fail();
}
ZipFileAssert.assertEquals(expectedFile, targetFile);
assertTrue(targetFile.delete());
}
/**
* Checks that we can write a package to a simple
* OutputStream, in addition to the normal writing
* to a file
*/
@Test
public void saveToOutputStream() throws IOException, InvalidFormatException {
String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx");
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
try {
try (FileOutputStream fout = new FileOutputStream(targetFile)) {
p.save(fout);
}
// Compare the original and newly saved document
assertTrue(targetFile.exists());
ZipFileAssert.assertEquals(new File(originalFile), targetFile);
assertTrue(targetFile.delete());
} finally {
// use revert to not re-write the input file
p.revert();
}
}
/**
* Checks that we can open+read a package from a
* simple InputStream, in addition to the normal
* reading from a file
*/
@Test
public void openFromInputStream() throws IOException, InvalidFormatException {
String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
try (FileInputStream finp = new FileInputStream(originalFile)) {
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(finp);
try {
assertNotNull(p);
assertNotNull(p.getRelationships());
assertEquals(12, p.getParts().size());
// Check it has the usual bits
assertTrue(p.hasRelationships());
assertTrue(p.containPart(PackagingURIHelper.createPartName("/_rels/.rels")));
} finally {
p.revert();
}
}
}
/**
* TODO: fix and enable
*/
@Test
@Ignore
public void removePartRecursive() throws IOException, InvalidFormatException, URISyntaxException {
String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx");
File tempFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveTMP.docx");
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE);
try {
p.removePartRecursive(PackagingURIHelper.createPartName(new URI(
"/word/document.xml")));
p.save(tempFile.getAbsoluteFile());
// Compare the original and newly saved document
assertTrue(targetFile.exists());
ZipFileAssert.assertEquals(targetFile, tempFile);
assertTrue(targetFile.delete());
} finally {
p.revert();
}
}
@Test
public void deletePart() throws InvalidFormatException {
TreeMap<PackagePartName, String> expectedValues;
TreeMap<PackagePartName, String> values;
values = new TreeMap<>();
// Expected values
expectedValues = new TreeMap<>();
expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"),
"application/vnd.openxmlformats-package.relationships+xml");
expectedValues
.put(PackagingURIHelper.createPartName("/docProps/app.xml"),
"application/vnd.openxmlformats-officedocument.extended-properties+xml");
expectedValues.put(PackagingURIHelper
.createPartName("/docProps/core.xml"),
"application/vnd.openxmlformats-package.core-properties+xml");
expectedValues
.put(PackagingURIHelper.createPartName("/word/fontTable.xml"),
"application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml");
expectedValues.put(PackagingURIHelper
.createPartName("/word/media/image1.gif"), "image/gif");
expectedValues
.put(PackagingURIHelper.createPartName("/word/settings.xml"),
"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml");
expectedValues
.put(PackagingURIHelper.createPartName("/word/styles.xml"),
"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml");
expectedValues.put(PackagingURIHelper
.createPartName("/word/theme/theme1.xml"),
"application/vnd.openxmlformats-officedocument.theme+xml");
expectedValues
.put(
PackagingURIHelper
.createPartName("/word/webSettings.xml"),
"application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml");
String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
// Remove the core part
p.deletePart(PackagingURIHelper.createPartName("/word/document.xml"));
for (PackagePart part : p.getParts()) {
values.put(part.getPartName(), part.getContentType());
logger.log(POILogger.DEBUG, part.getPartName());
}
// Compare expected values with values return by the package
for (PackagePartName partName : expectedValues.keySet()) {
assertNotNull(values.get(partName));
assertEquals(expectedValues.get(partName), values.get(partName));
}
// Don't save modifications
p.revert();
}
@Test
public void deletePartRecursive() throws InvalidFormatException {
TreeMap<PackagePartName, String> expectedValues;
TreeMap<PackagePartName, String> values;
values = new TreeMap<>();
// Expected values
expectedValues = new TreeMap<>();
expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"),
"application/vnd.openxmlformats-package.relationships+xml");
expectedValues
.put(PackagingURIHelper.createPartName("/docProps/app.xml"),
"application/vnd.openxmlformats-officedocument.extended-properties+xml");
expectedValues.put(PackagingURIHelper
.createPartName("/docProps/core.xml"),
"application/vnd.openxmlformats-package.core-properties+xml");
String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
// Remove the core part
p.deletePartRecursive(PackagingURIHelper.createPartName("/word/document.xml"));
for (PackagePart part : p.getParts()) {
values.put(part.getPartName(), part.getContentType());
logger.log(POILogger.DEBUG, part.getPartName());
}
// Compare expected values with values return by the package
for (PackagePartName partName : expectedValues.keySet()) {
assertNotNull(values.get(partName));
assertEquals(expectedValues.get(partName), values.get(partName));
}
// Don't save modifications
p.revert();
}
/**
* Test that we can open a file by path, and then
* write changes to it.
*/
@Test
public void openFileThenOverwrite() throws IOException, InvalidFormatException {
File tempFile = TempFile.createTempFile("poiTesting","tmp");
File origFile = OpenXML4JTestDataSamples.getSampleFile("TestPackageCommon.docx");
FileHelper.copyFile(origFile, tempFile);
// Open the temp file
OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE);
// Close it
p.close();
// Delete it
assertTrue(tempFile.delete());
// Reset
FileHelper.copyFile(origFile, tempFile);
p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE);
// Save it to the same file - not allowed
try {
p.save(tempFile);
fail("You shouldn't be able to call save(File) to overwrite the current file");
} catch(InvalidOperationException e) {
// expected here
}
p.close();
// Delete it
assertTrue(tempFile.delete());
// Open it read only, then close and delete - allowed
FileHelper.copyFile(origFile, tempFile);
p = OPCPackage.open(tempFile.toString(), PackageAccess.READ);
p.close();
assertTrue(tempFile.delete());
}
/**
* Test that we can open a file by path, save it
* to another file, then delete both
*/
@Test
public void openFileThenSaveDelete() throws IOException, InvalidFormatException {
File tempFile = TempFile.createTempFile("poiTesting","tmp");
File tempFile2 = TempFile.createTempFile("poiTesting","tmp");
File origFile = OpenXML4JTestDataSamples.getSampleFile("TestPackageCommon.docx");
FileHelper.copyFile(origFile, tempFile);
// Open the temp file
try (OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE)) {
// Save it to a different file
p.save(tempFile2);
}
// Delete both the files
assertTrue(tempFile.delete());
assertTrue(tempFile2.delete());
}
private static ContentTypeManager getContentTypeManager(OPCPackage pkg) {
return POITestCase.getFieldValue(OPCPackage.class, pkg, ContentTypeManager.class, "contentTypeManager");
}
@Test
public void getPartsByName() throws InvalidFormatException {
String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
@SuppressWarnings("resource")
OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE);
try {
List<PackagePart> rs = pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml"));
HashMap<String, PackagePart> selected = new HashMap<>();
for(PackagePart p : rs)
selected.put(p.getPartName().getName(), p);
assertEquals(6, selected.size());
assertTrue(selected.containsKey("/word/document.xml"));
assertTrue(selected.containsKey("/word/fontTable.xml"));
assertTrue(selected.containsKey("/word/settings.xml"));
assertTrue(selected.containsKey("/word/styles.xml"));
assertTrue(selected.containsKey("/word/theme/theme1.xml"));
assertTrue(selected.containsKey("/word/webSettings.xml"));
} finally {
// use revert to not re-write the input file
pkg.revert();
}
}
@Test
public void getPartSize() throws IOException, InvalidFormatException {
String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
try (OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ)) {
int checked = 0;
for (PackagePart part : pkg.getParts()) {
// Can get the size of zip parts
if (part.getPartName().getName().equals("/word/document.xml")) {
checked++;
assertEquals(ZipPackagePart.class, part.getClass());
assertEquals(6031L, part.getSize());
}
if (part.getPartName().getName().equals("/word/fontTable.xml")) {
checked++;
assertEquals(ZipPackagePart.class, part.getClass());
assertEquals(1312L, part.getSize());
}
// But not from the others
if (part.getPartName().getName().equals("/docProps/core.xml")) {
checked++;
assertEquals(PackagePropertiesPart.class, part.getClass());
assertEquals(-1, part.getSize());
}
}
// Ensure we actually found the parts we want to check
assertEquals(3, checked);
}
}
@Test
public void replaceContentType()
throws IOException, InvalidFormatException, SecurityException, IllegalArgumentException {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.xlsx");
@SuppressWarnings("resource")
OPCPackage p = OPCPackage.open(is);
ContentTypeManager mgr = getContentTypeManager(p);
assertTrue(mgr.isContentTypeRegister("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"));
assertFalse(mgr.isContentTypeRegister("application/vnd.ms-excel.sheet.macroEnabled.main+xml"));
assertTrue(
p.replaceContentType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
"application/vnd.ms-excel.sheet.macroEnabled.main+xml")
);
assertFalse(mgr.isContentTypeRegister("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"));
assertTrue(mgr.isContentTypeRegister("application/vnd.ms-excel.sheet.macroEnabled.main+xml"));
p.revert();
is.close();
}
/**
* Verify we give helpful exceptions (or as best we can) when
* supplied with non-OOXML file types (eg OLE2, ODF)
*/
@Test
public void NonOOXMLFileTypes() throws Exception {
// Spreadsheet has a good mix of alternate file types
POIDataSamples files = POIDataSamples.getSpreadSheetInstance();
// OLE2 - Stream
try {
try (InputStream stream = files.openResourceAsStream("SampleSS.xls")) {
OPCPackage.open(stream);
}
fail("Shouldn't be able to open OLE2");
} catch (OLE2NotOfficeXmlFileException e) {
assertTrue(e.getMessage().contains("The supplied data appears to be in the OLE2 Format"));
assertTrue(e.getMessage().contains("You are calling the part of POI that deals with OOXML"));
}
// OLE2 - File
try {
OPCPackage.open(files.getFile("SampleSS.xls"));
fail("Shouldn't be able to open OLE2");
} catch (OLE2NotOfficeXmlFileException e) {
assertTrue(e.getMessage().contains("The supplied data appears to be in the OLE2 Format"));
assertTrue(e.getMessage().contains("You are calling the part of POI that deals with OOXML"));
}
// Raw XML - Stream
try {
try (InputStream stream = files.openResourceAsStream("SampleSS.xml")) {
OPCPackage.open(stream);
}
fail("Shouldn't be able to open XML");
} catch (NotOfficeXmlFileException e) {
assertTrue(e.getMessage().contains("The supplied data appears to be a raw XML file"));
assertTrue(e.getMessage().contains("Formats such as Office 2003 XML"));
}
// Raw XML - File
try {
OPCPackage.open(files.getFile("SampleSS.xml"));
fail("Shouldn't be able to open XML");
} catch (NotOfficeXmlFileException e) {
assertTrue(e.getMessage().contains("The supplied data appears to be a raw XML file"));
assertTrue(e.getMessage().contains("Formats such as Office 2003 XML"));
}
// ODF / ODS - Stream
try {
try (InputStream stream = files.openResourceAsStream("SampleSS.ods")) {
OPCPackage.open(stream);
}
fail("Shouldn't be able to open ODS");
} catch (ODFNotOfficeXmlFileException e) {
assertTrue(e.toString().contains("The supplied data appears to be in ODF"));
assertTrue(e.toString().contains("Formats like these (eg ODS"));
}
// ODF / ODS - File
try {
OPCPackage.open(files.getFile("SampleSS.ods"));
fail("Shouldn't be able to open ODS");
} catch (ODFNotOfficeXmlFileException e) {
assertTrue(e.toString().contains("The supplied data appears to be in ODF"));
assertTrue(e.toString().contains("Formats like these (eg ODS"));
}
// Plain Text - Stream
try {
try (InputStream stream = files.openResourceAsStream("SampleSS.txt")) {
OPCPackage.open(stream);
}
fail("Shouldn't be able to open Plain Text");
} catch (NotOfficeXmlFileException e) {
assertTrue(e.getMessage().contains("No valid entries or contents found"));
assertTrue(e.getMessage().contains("not a valid OOXML"));
}
// Plain Text - File
try {
OPCPackage.open(files.getFile("SampleSS.txt"));
fail("Shouldn't be able to open Plain Text");
} catch (UnsupportedFileFormatException e) {
// Unhelpful low-level error, sorry
}
}
/**
* Zip bomb handling test
*
* see bug #50090 / #56865
*/
@Test
public void zipBombCreateAndHandle()
throws IOException, EncryptedDocumentException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(2500000);
try (ZipFile zipFile = ZipHelper.openZipFile(OpenXML4JTestDataSamples.getSampleFile("sample.xlsx"));
ZipArchiveOutputStream append = new ZipArchiveOutputStream(bos)) {
assertNotNull(zipFile);
// first, copy contents from existing war
Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
while (entries.hasMoreElements()) {
final ZipArchiveEntry eIn = entries.nextElement();
final ZipArchiveEntry eOut = new ZipArchiveEntry(eIn.getName());
eOut.setTime(eIn.getTime());
eOut.setComment(eIn.getComment());
eOut.setSize(eIn.getSize());
append.putArchiveEntry(eOut);
if (!eOut.isDirectory()) {
try (InputStream is = zipFile.getInputStream(eIn)) {
if (eOut.getName().equals("[Content_Types].xml")) {
ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
IOUtils.copy(is, bos2);
long size = bos2.size() - "</Types>".length();
append.write(bos2.toByteArray(), 0, (int) size);
byte[] spam = new byte[0x7FFF];
Arrays.fill(spam, (byte) ' ');
// 0x7FFF0000 is the maximum for 32-bit zips, but less still works
while (size < 0x7FFF00) {
append.write(spam);
size += spam.length;
}
append.write("</Types>".getBytes(StandardCharsets.UTF_8));
size += 8;
eOut.setSize(size);
} else {
IOUtils.copy(is, append);
}
}
}
append.closeArchiveEntry();
}
}
expectedEx.expect(IOException.class);
expectedEx.expectMessage("Zip bomb detected!");
try (Workbook wb = WorkbookFactory.create(new ByteArrayInputStream(bos.toByteArray()))) {
wb.getSheetAt(0);
}
}
@Test
public void testZipEntityExpansionTerminates() throws IOException, OpenXML4JException, XmlException {
expectedEx.expect(IllegalStateException.class);
expectedEx.expectMessage("The text would exceed the max allowed overall size of extracted text.");
openXmlBombFile("poc-shared-strings.xlsx");
}
@Test
public void testZipEntityExpansionSharedStringTableEvents() throws IOException, OpenXML4JException, XmlException {
boolean before = ExtractorFactory.getThreadPrefersEventExtractors();
ExtractorFactory.setThreadPrefersEventExtractors(true);
try {
expectedEx.expect(IllegalStateException.class);
expectedEx.expectMessage("The text would exceed the max allowed overall size of extracted text.");
openXmlBombFile("poc-shared-strings.xlsx");
} finally {
ExtractorFactory.setThreadPrefersEventExtractors(before);
}
}
@Test
public void testZipEntityExpansionExceedsMemory() throws IOException, OpenXML4JException, XmlException {
expectedEx.expect(POIXMLException.class);
expectedEx.expectMessage("unable to parse shared strings table");
expectedEx.expectCause(getCauseMatcher(SAXParseException.class, "The parser has encountered more than"));
openXmlBombFile("poc-xmlbomb.xlsx");
}
@Test
public void testZipEntityExpansionExceedsMemory2() throws IOException, OpenXML4JException, XmlException {
expectedEx.expect(POIXMLException.class);
expectedEx.expectMessage("unable to parse shared strings table");
expectedEx.expectCause(getCauseMatcher(SAXParseException.class, "The parser has encountered more than"));
openXmlBombFile("poc-xmlbomb-empty.xlsx");
}
private void openXmlBombFile(String file) throws IOException, OpenXML4JException, XmlException {
final double minInf = ZipSecureFile.getMinInflateRatio();
ZipSecureFile.setMinInflateRatio(0.002);
try (POITextExtractor extractor = ExtractorFactory.createExtractor(XSSFTestDataSamples.getSampleFile(file))) {
assertNotNull(extractor);
extractor.getText();
} finally {
ZipSecureFile.setMinInflateRatio(minInf);
}
}
@Test
public void zipBombCheckSizesWithinLimits() throws IOException, EncryptedDocumentException {
getZipStatsAndConsume((max_size, min_ratio) -> {
// use values close to, but within the limits
ZipSecureFile.setMinInflateRatio(min_ratio - 0.002);
assertEquals(min_ratio - 0.002, ZipSecureFile.getMinInflateRatio(), 0.00001);
ZipSecureFile.setMaxEntrySize(max_size + 1);
assertEquals(max_size + 1, ZipSecureFile.getMaxEntrySize());
});
}
@Test
public void zipBombCheckSizesRatioTooSmall() throws IOException, EncryptedDocumentException {
expectedEx.expect(POIXMLException.class);
expectedEx.expectMessage("You can adjust this limit via ZipSecureFile.setMinInflateRatio()");
getZipStatsAndConsume((max_size, min_ratio) -> {
// check ratio out of bounds
ZipSecureFile.setMinInflateRatio(min_ratio+0.002);
});
}
@Test
public void zipBombCheckSizesSizeTooBig() throws IOException, EncryptedDocumentException {
expectedEx.expect(POIXMLException.class);
expectedEx.expectMessage("You can adjust this limit via ZipSecureFile.setMaxEntrySize()");
getZipStatsAndConsume((max_size, min_ratio) -> {
// check max entry size ouf of bounds
ZipSecureFile.setMinInflateRatio(min_ratio-0.002);
ZipSecureFile.setMaxEntrySize(max_size-200);
});
}
private void getZipStatsAndConsume(BiConsumer<Long,Double> ratioCon) throws IOException {
// use a test file with a xml file bigger than 100k (ZipArchiveThresholdInputStream.GRACE_ENTRY_SIZE)
final File file = XSSFTestDataSamples.getSampleFile("poc-shared-strings.xlsx");
double min_ratio = Double.MAX_VALUE;
long max_size = 0;
try (ZipFile zf = ZipHelper.openZipFile(file)) {
assertNotNull(zf);
Enumeration<? extends ZipArchiveEntry> entries = zf.getEntries();
while (entries.hasMoreElements()) {
ZipArchiveEntry ze = entries.nextElement();
if (ze.getSize() == 0) {
continue;
}
// add zip entry header ~ 128 bytes
long size = ze.getSize()+128;
double ratio = ze.getCompressedSize() / (double)size;
min_ratio = Math.min(min_ratio, ratio);
max_size = Math.max(max_size, size);
}
}
ratioCon.accept(max_size, min_ratio);
//noinspection EmptyTryBlock,unused
try (Workbook wb = WorkbookFactory.create(file, null, true)) {
} finally {
// reset otherwise a lot of ooxml tests will fail
ZipSecureFile.setMinInflateRatio(0.01d);
ZipSecureFile.setMaxEntrySize(0xFFFFFFFFL);
}
}
@Test
public void testConstructors() throws IOException {
// verify the various ways to construct a ZipSecureFile
File file = OpenXML4JTestDataSamples.getSampleFile("sample.xlsx");
ZipSecureFile zipFile = new ZipSecureFile(file);
assertNotNull(zipFile.getName());
zipFile.close();
zipFile = new ZipSecureFile(file.getAbsolutePath());
assertNotNull(zipFile.getName());
zipFile.close();
}
@Test
public void testMaxTextSize() {
long before = ZipSecureFile.getMaxTextSize();
try {
ZipSecureFile.setMaxTextSize(12345);
assertEquals(12345, ZipSecureFile.getMaxTextSize());
} finally {
ZipSecureFile.setMaxTextSize(before);
}
}
// bug 60128
@Test(expected=NotOfficeXmlFileException.class)
public void testCorruptFile() throws InvalidFormatException {
File file = OpenXML4JTestDataSamples.getSampleFile("invalid.xlsx");
OPCPackage.open(file, PackageAccess.READ);
}
// bug 61381
@Test
public void testTooShortFilterStreams() throws IOException {
File xssf = OpenXML4JTestDataSamples.getSampleFile("sample.xlsx");
File hssf = POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xls");
InputStream[] isList = {
new PushbackInputStream(new FileInputStream(xssf), 2),
new BufferedInputStream(new FileInputStream(xssf), 2),
new PushbackInputStream(new FileInputStream(hssf), 2),
new BufferedInputStream(new FileInputStream(hssf), 2),
};
try {
for (InputStream is : isList) {
WorkbookFactory.create(is).close();
}
} finally {
for (InputStream is : isList) {
IOUtils.closeQuietly(is);
}
}
}
@Test
public void testBug56479() throws Exception {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("dcterms_bug_56479.zip");
OPCPackage p = OPCPackage.open(is);
// Check we found the contents of it
boolean foundCoreProps = false, foundDocument = false, foundTheme1 = false;
for (final PackagePart part : p.getParts()) {
final String partName = part.getPartName().toString();
final String contentType = part.getContentType();
if ("/docProps/core.xml".equals(partName)) {
assertEquals(ContentTypes.CORE_PROPERTIES_PART, contentType);
foundCoreProps = true;
}
if ("/word/document.xml".equals(partName)) {
assertEquals(XWPFRelation.DOCUMENT.getContentType(), contentType);
foundDocument = true;
}
if ("/word/theme/theme1.xml".equals(partName)) {
assertEquals(XWPFRelation.THEME.getContentType(), contentType);
foundTheme1 = true;
}
}
assertTrue("Core not found in " + p.getParts(), foundCoreProps);
assertFalse("Document should not be found in " + p.getParts(), foundDocument);
assertFalse("Theme1 should not found in " + p.getParts(), foundTheme1);
p.close();
is.close();
}
@Test
public void unparseableCentralDirectory() throws IOException {
File f = OpenXML4JTestDataSamples.getSampleFile("at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx");
SlideShow<?,?> ppt = SlideShowFactory.create(f, null, true);
ppt.close();
}
@Test
public void testClosingStreamOnException() throws IOException {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("dcterms_bug_56479.zip");
File tmp = File.createTempFile("poi-test-truncated-zip", "");
// create a corrupted zip file by truncating a valid zip file to the first 100 bytes
OutputStream os = new FileOutputStream(tmp);
for (int i = 0; i < 100; i++) {
os.write(is.read());
}
os.flush();
os.close();
is.close();
// feed the corrupted zip file to OPCPackage
try {
OPCPackage.open(tmp, PackageAccess.READ);
} catch (Exception e) {
// expected: the zip file is invalid
// this test does not care if open() throws an exception or not.
}
// If the stream is not closed on exception, it will keep a file descriptor to tmp,
// and requests to the OS to delete the file will fail.
assertTrue("Can't delete tmp file", tmp.delete());
}
/**
* If ZipPackage is passed an invalid file, a call to close
* (eg from the OPCPackage open method) should tidy up the
* stream / file the broken file is being read from.
* See bug #60128 for more
*/
@Test(expected = NotOfficeXmlFileException.class)
public void testTidyStreamOnInvalidFile1() throws Exception {
openInvalidFile("SampleSS.ods", false);
}
@Test(expected = NotOfficeXmlFileException.class)
public void testTidyStreamOnInvalidFile2() throws Exception {
openInvalidFile("SampleSS.ods", true);
}
@Test(expected = NotOfficeXmlFileException.class)
public void testTidyStreamOnInvalidFile3() throws Exception {
openInvalidFile("SampleSS.txt", false);
}
@Test(expected = NotOfficeXmlFileException.class)
public void testTidyStreamOnInvalidFile4() throws Exception {
openInvalidFile("SampleSS.txt", true);
}
@Test(expected = InvalidFormatException.class)
public void testBug62592() throws Exception {
InputStream is = OpenXML4JTestDataSamples.openSampleStream("62592.thmx");
/*OPCPackage p =*/ OPCPackage.open(is);
}
@Test
public void testBug62592SequentialCallsToGetParts() throws Exception {
//make absolutely certain that sequential calls don't throw InvalidFormatExceptions
String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx");
try (OPCPackage p2 = OPCPackage.open(originalFile, PackageAccess.READ)) {
p2.getParts();
p2.getParts();
}
}
@Test
public void testDoNotCloseStream() throws IOException {
// up to JDK 10 we did use Mockito here, but OutputStream is
// an abstract class and fails mocking with some changes in JDK 11
// so we use a simple empty output stream implementation instead
OutputStream os = new OutputStream() {
@Override
public void write(int b) {
}
@Override
public void close() {
throw new IllegalStateException("close should not be called here");
}
};
try (XSSFWorkbook wb = new XSSFWorkbook()) {
wb.createSheet();
wb.write(os);
}
try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
wb.createSheet();
wb.write(os);
}
}
private static void openInvalidFile(final String name, final boolean useStream) throws IOException, InvalidFormatException {
// Spreadsheet has a good mix of alternate file types
final POIDataSamples files = POIDataSamples.getSpreadSheetInstance();
ZipPackage pkgTest = null;
try (final InputStream is = (useStream) ? files.openResourceAsStream(name) : null) {
try (final ZipPackage pkg = (useStream) ? new ZipPackage(is, PackageAccess.READ) : new ZipPackage(files.getFile(name), PackageAccess.READ)) {
pkgTest = pkg;
assertNotNull(pkg.getZipArchive());
assertFalse(pkg.getZipArchive().isClosed());
pkg.getParts();
fail("Shouldn't work");
}
} finally {
if (pkgTest != null) {
assertNotNull(pkgTest.getZipArchive());
assertTrue(pkgTest.getZipArchive().isClosed());
}
}
}
@SuppressWarnings("SameParameterValue")
private static <T extends Throwable> AnyCauseMatcher<T> getCauseMatcher(Class<T> cause, String message) {
// junit is only using hamcrest-core, so instead of adding hamcrest-beans, we provide the throwable
// search with the basics...
// see https://stackoverflow.com/a/47703937/2066598
return new AnyCauseMatcher<>(cause, message);
}
private static class AnyCauseMatcher<T extends Throwable> extends TypeSafeMatcher<T> {
private final Class<T> expectedType;
private final String expectedMessage;
AnyCauseMatcher(Class<T> expectedType, String expectedMessage) {
this.expectedType = expectedType;
this.expectedMessage = expectedMessage;
}
@Override
protected boolean matchesSafely(final Throwable root) {
for (Throwable t = root; t != null; t = t.getCause()) {
if (t.getClass().isAssignableFrom(expectedType) && t.getMessage().contains(expectedMessage)) {
return true;
}
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("expects type ")
.appendValue(expectedType)
.appendText(" and a message ")
.appendValue(expectedMessage);
}
}
@SuppressWarnings("UnstableApiUsage")
@Test
public void testBug63029() throws Exception {
File testFile = OpenXML4JTestDataSamples.getSampleFile("sample.docx");
File tmpFile = OpenXML4JTestDataSamples.getOutputFile("Bug63029.docx");
Files.copy(testFile, tmpFile);
int numPartsBefore = 0;
String md5Before = Files.hash(tmpFile, Hashing.md5()).toString();
RuntimeException ex = null;
try(OPCPackage pkg = OPCPackage.open(tmpFile, PackageAccess.READ_WRITE))
{
numPartsBefore = pkg.getParts().size();
// add a marshaller that will throw an exception on save
pkg.addMarshaller("poi/junit", (part, out) -> {
throw new RuntimeException("Bugzilla 63029");
});
pkg.createPart(PackagingURIHelper.createPartName("/poi/test.xml"), "poi/junit");
} catch (RuntimeException e){
ex = e;
}
// verify there was an exception while closing the file
assertNotNull("Fail to save: an error occurs while saving the package : Bugzilla 63029", ex);
assertEquals("Fail to save: an error occurs while saving the package : Bugzilla 63029", ex.getMessage());
// assert that md5 after closing is the same, i.e. the source is left intact
String md5After = Files.hash(tmpFile, Hashing.md5()).toString();
assertEquals(md5Before, md5After);
// try to read the source file once again
try ( OPCPackage pkg = OPCPackage.open(tmpFile, PackageAccess.READ_WRITE)){
// the source is still a valid zip archive.
// prior to the fix this used to throw NotOfficeXmlFileException("archive is not a ZIP archive")
// assert that the number of parts remained the same
assertEquals(pkg.getParts().size(), numPartsBefore);
}
}
}
|