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
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
|
/* ====================================================================
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 static org.apache.poi.openxml4j.opc.ContentTypes.EXTENSION_XML;
import static org.apache.poi.openxml4j.opc.ContentTypes.PLAIN_OLD_XML;
import static org.apache.poi.openxml4j.opc.ContentTypes.RELATIONSHIPS_PART;
import static org.apache.poi.openxml4j.opc.PackagingURIHelper.RELATIONSHIP_PART_EXTENSION_NAME;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.Logger;
import org.apache.poi.logging.PoiLogManager;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException;
import org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException;
import org.apache.poi.openxml4j.opc.internal.ContentType;
import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
import org.apache.poi.openxml4j.opc.internal.InvalidZipException;
import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart;
import org.apache.poi.openxml4j.opc.internal.PartMarshaller;
import org.apache.poi.openxml4j.opc.internal.PartUnmarshaller;
import org.apache.poi.openxml4j.opc.internal.ZipContentTypeManager;
import org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller;
import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPackagePropertiesMarshaller;
import org.apache.poi.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller;
import org.apache.poi.openxml4j.opc.internal.unmarshallers.UnmarshallContext;
import org.apache.poi.openxml4j.util.ZipEntrySource;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.NotImplemented;
import org.apache.poi.util.StringUtil;
/**
* Represents a container that can store multiple data objects.
*/
public abstract class OPCPackage implements RelationshipSource, Closeable {
/**
* Logger.
*/
private static final Logger LOG = PoiLogManager.getLogger(OPCPackage.class);
/**
* Default package access.
*/
protected static final PackageAccess defaultPackageAccess = PackageAccess.READ_WRITE;
/**
* Package access.
*/
private final PackageAccess packageAccess;
/**
* Package parts collection.
*/
private PackagePartCollection partList;
/**
* Package relationships.
*/
protected PackageRelationshipCollection relationships;
/**
* Part marshallers by content type.
*/
protected final Map<ContentType, PartMarshaller> partMarshallers = new HashMap<>(5);
/**
* Default part marshaller.
*/
protected final PartMarshaller defaultPartMarshaller = new DefaultMarshaller();
/**
* Part unmarshallers by content type.
*/
protected final Map<ContentType, PartUnmarshaller> partUnmarshallers = new HashMap<>(2);
/**
* Core package properties.
*/
protected PackagePropertiesPart packageProperties;
/**
* Manage parts content types of this package.
*/
protected ContentTypeManager contentTypeManager;
/**
* Flag if a modification is done to the document.
*/
protected boolean isDirty;
/**
* File path of this package.
*/
protected String originalPackagePath;
/**
* Output stream for writing this package.
*/
protected OutputStream output;
/**
* Constructor.
*
* @param access Package access.
* @throws OpenXML4JRuntimeException if there are issues creating properties part
*/
OPCPackage(PackageAccess access) {
this(access, OPCComplianceFlags.enforceAll());
}
/**
* Constructor.
*
* @param access Package access.
* @param opcComplianceFlags Enable or disable specific OPC compliance flags.
* This is useful to allow parsing of certain non-compliant documents.
* @throws OpenXML4JRuntimeException if there are issues creating properties part
* @since POI 5.4.1
*/
OPCPackage(PackageAccess access, OPCComplianceFlags opcComplianceFlags) {
if (getClass() != ZipPackage.class) {
throw new IllegalArgumentException("PackageBase may not be subclassed");
}
this.packageAccess = access;
final ContentType contentType = newCorePropertiesPart();
// TODO Delocalize specialized marshallers
this.partUnmarshallers.put(contentType, new PackagePropertiesUnmarshaller(opcComplianceFlags));
this.partMarshallers.put(contentType, new ZipPackagePropertiesMarshaller());
}
private static ContentType newCorePropertiesPart() {
try {
return new ContentType(ContentTypes.CORE_PROPERTIES_PART);
} catch (InvalidFormatException e) {
// Should never happen
throw new OpenXML4JRuntimeException(
"Package.init() : this exception should never happen, " +
"if you read this message please send a mail to the developers team. : " +
e.getMessage(), e
);
}
}
/**
* Open a package with read/write permission.
*
* @param path
* The document path.
* @return A Package object, else <b>null</b>.
* @throws InvalidFormatException
* If the specified file doesn't exist, and a parsing error
* occur.
*/
public static OPCPackage open(String path) throws InvalidFormatException {
return open(path, defaultPackageAccess, OPCComplianceFlags.enforceAll());
}
/**
* Open a package with read/write permission.
*
* @param path
* The document path.
* @param opcComplianceFlags
* The level of OPC compliance to enforce when reading the package
* @return A Package object, else <b>null</b>.
* @throws InvalidFormatException
* If the specified file doesn't exist, and a parsing error
* occur.
* @since POI 5.4.1
*/
public static OPCPackage open(String path, OPCComplianceFlags opcComplianceFlags) throws InvalidFormatException {
return open(path, defaultPackageAccess, opcComplianceFlags);
}
/**
* Open a package with read/write permission.
*
* @param file
* The file to open.
* @return A Package object, else <b>null</b>.
* @throws InvalidFormatException
* If the specified file doesn't exist, and a parsing error
* occur.
*/
public static OPCPackage open(File file) throws InvalidFormatException {
return open(file, defaultPackageAccess);
}
/**
* Open a package with read/write permission.
*
* @param file
* The file to open.
* @param opcComplianceFlags
* The level of OPC compliance to enforce when reading the package
* @return A Package object, else <b>null</b>.
* @throws InvalidFormatException
* If the specified file doesn't exist, and a parsing error
* occur.
* @since POI 5.4.1
*/
public static OPCPackage open(File file, OPCComplianceFlags opcComplianceFlags) throws InvalidFormatException {
return open(file, defaultPackageAccess, opcComplianceFlags);
}
/**
* Open a user provided {@link ZipEntrySource} with read-only permission.
* This method can be used to stream data into POI.
* Opposed to other open variants, the data is read as-is, e.g. there aren't
* any zip-bomb protection put in place.
*
* @param zipEntry the custom source
* @return A Package object
* @throws InvalidFormatException if a parsing error occur.
*/
public static OPCPackage open(ZipEntrySource zipEntry) throws InvalidFormatException {
return open(zipEntry, OPCComplianceFlags.enforceAll());
}
/**
* Open a user provided {@link ZipEntrySource} with read-only permission.
* This method can be used to stream data into POI.
* Opposed to other open variants, the data is read as-is, e.g. there aren't
* any zip-bomb protection put in place.
*
* @param zipEntry the custom source
* @param opcComplianceFlags
* The level of OPC compliance to enforce when reading the package
* @return A Package object
* @throws InvalidFormatException if a parsing error occur.
* @since POI 5.4.1
*/
public static OPCPackage open(ZipEntrySource zipEntry, OPCComplianceFlags opcComplianceFlags) throws InvalidFormatException {
OPCPackage pack = new ZipPackage(zipEntry, PackageAccess.READ, opcComplianceFlags);
try {
if (pack.partList == null) {
pack.getParts();
}
// pack.originalPackagePath = file.getAbsolutePath();
return pack;
} catch (InvalidFormatException | RuntimeException e) {
// use revert() to free resources when the package is opened read-only
pack.revert();
throw e;
}
}
/**
* Open a package.
*
* @param path
* The document path.
* @param access
* PackageBase access.
* @return A PackageBase object, else <b>null</b>.
* @throws InvalidFormatException
* If the specified file doesn't exist, and a parsing error
* occur.
* @throws InvalidOperationException If the zip file cannot be opened.
* @throws InvalidFormatException if the package is not valid.
*/
public static OPCPackage open(String path, PackageAccess access)
throws InvalidFormatException, InvalidOperationException {
return open(path, access, OPCComplianceFlags.enforceAll());
}
/**
* Open a package.
*
* @param path
* The document path.
* @param access
* PackageBase access.
* @param opcComplianceFlags
* The level of OPC compliance to enforce when reading the package
* @return A PackageBase object, else <b>null</b>.
* @throws InvalidFormatException
* If the specified file doesn't exist, and a parsing error
* occur.
* @throws InvalidOperationException If the zip file cannot be opened.
* @throws InvalidFormatException if the package is not valid.
* @since POI 5.4.1
*/
public static OPCPackage open(String path, PackageAccess access, OPCComplianceFlags opcComplianceFlags)
throws InvalidFormatException, InvalidOperationException {
if (StringUtil.isBlank(path)) {
throw new IllegalArgumentException("'path' must be given");
}
File file = new File(path);
if (file.exists() && file.isDirectory()) {
throw new IllegalArgumentException("path must not be a directory");
}
OPCPackage pack = new ZipPackage(path, access, opcComplianceFlags); // NOSONAR
boolean success = false;
if (pack.partList == null && access != PackageAccess.WRITE) {
try {
pack.getParts();
success = true;
} finally {
if (! success) {
IOUtils.closeQuietly(pack);
}
}
}
pack.originalPackagePath = new File(path).getAbsolutePath();
return pack;
}
/**
* Open a package.
*
* @param file
* The file to open.
* @param access
* PackageBase access.
* @return A PackageBase object, else <b>null</b>.
* @throws InvalidFormatException
* If the specified file doesn't exist, and a parsing error
* occur.
*/
public static OPCPackage open(File file, PackageAccess access)
throws InvalidFormatException {
return open(file, access, OPCComplianceFlags.enforceAll());
}
/**
* Open a package.
*
* @param file
* The file to open.
* @param access
* PackageBase access.
* @param opcComplianceFlags
* The level of OPC compliance to enforce when reading the package
* @return A PackageBase object, else <b>null</b>.
* @throws InvalidFormatException
* If the specified file doesn't exist, and a parsing error
* occur.
* @since POI 5.4.1
*/
public static OPCPackage open(File file, PackageAccess access, OPCComplianceFlags opcComplianceFlags)
throws InvalidFormatException {
if (file == null) {
throw new IllegalArgumentException("'file' must be given");
}
if (file.exists() && file.isDirectory()) {
throw new IllegalArgumentException("file must not be a directory");
}
final OPCPackage pack;
try {
pack = new ZipPackage(file, access, opcComplianceFlags); //NOSONAR
} catch (InvalidOperationException e) {
throw new InvalidFormatException(e.getMessage(), e);
}
try {
if (pack.partList == null && access != PackageAccess.WRITE) {
pack.getParts();
}
pack.originalPackagePath = file.getAbsolutePath();
return pack;
} catch (InvalidFormatException | RuntimeException e) {
if (access == PackageAccess.READ) {
pack.revert();
} else {
IOUtils.closeQuietly(pack);
}
throw e;
}
}
/**
* Open a package.
*
* Note - uses quite a bit more memory than {@link #open(String)}, which
* doesn't need to hold the whole zip file in memory, and can take advantage
* of native methods
*
* @param in
* The InputStream to read the package from. The stream is closed.
* @return A PackageBase object
*
* @throws InvalidFormatException
* Throws if the specified file exist and is not valid.
* @throws IOException If reading the stream fails
*/
public static OPCPackage open(InputStream in) throws InvalidFormatException,
IOException {
return open(in, OPCComplianceFlags.enforceAll());
}
/**
* Open a package.
*
* Note - uses quite a bit more memory than {@link #open(String)}, which
* doesn't need to hold the whole zip file in memory, and can take advantage
* of native methods
*
* @param in
* The InputStream to read the package from. The stream is closed.
* @param opcComplianceFlags
* The level of OPC compliance to enforce when reading the package
* @return A PackageBase object
*
* @throws InvalidFormatException
* Throws if the specified file exist and is not valid.
* @throws IOException If reading the stream fails
* @since POI 5.4.1
*/
public static OPCPackage open(InputStream in, OPCComplianceFlags opcComplianceFlags) throws InvalidFormatException,
IOException {
final OPCPackage pack;
try {
pack = new ZipPackage(in, PackageAccess.READ_WRITE, opcComplianceFlags);
} catch (InvalidZipException e) {
throw new InvalidFormatException(e.getMessage(), e);
}
try {
if (pack.partList == null) {
pack.getParts();
}
} catch (InvalidFormatException | RuntimeException e) {
IOUtils.closeQuietly(pack);
throw e;
}
return pack;
}
/**
* Open a package.
*
* Note - uses quite a bit more memory than {@link #open(String)}, which
* doesn't need to hold the whole zip file in memory, and can take advantage
* of native methods
*
* @param in
* The InputStream to read the package from.
* @param closeStream
* Whether to close the input stream.
* @return A PackageBase object
*
* @throws InvalidFormatException
* Throws if the specified file exist and is not valid.
* @throws IOException If reading the stream fails
* @since POI 5.2.5
*/
public static OPCPackage open(InputStream in, boolean closeStream) throws InvalidFormatException,
IOException {
return open(in, closeStream, OPCComplianceFlags.enforceAll());
}
/**
* Open a package.
*
* Note - uses quite a bit more memory than {@link #open(String)}, which
* doesn't need to hold the whole zip file in memory, and can take advantage
* of native methods
*
* @param in
* The InputStream to read the package from.
* @param closeStream
* Whether to close the input stream.
* @param opcComplianceFlags
* The level of OPC compliance to enforce when reading the package
* @return A PackageBase object
*
* @throws InvalidFormatException
* Throws if the specified file exist and is not valid.
* @throws IOException If reading the stream fails
* @since POI 5.4.1
*/
public static OPCPackage open(InputStream in, boolean closeStream, OPCComplianceFlags opcComplianceFlags) throws InvalidFormatException,
IOException {
final OPCPackage pack;
try {
pack = new ZipPackage(in, PackageAccess.READ_WRITE, closeStream, opcComplianceFlags);
} catch (InvalidZipException e) {
throw new InvalidFormatException(e.getMessage(), e);
}
try {
if (pack.partList == null) {
pack.getParts();
}
} catch (InvalidFormatException | RuntimeException e) {
IOUtils.closeQuietly(pack);
throw e;
}
return pack;
}
/**
* Opens a package if it exists, else it creates one.
*
* @param file
* The file to open or to create.
* @return A newly created package if the specified file does not exist,
* else the package extract from the file.
* @throws InvalidFormatException
* Throws if the specified file exist and is not valid.
*/
public static OPCPackage openOrCreate(File file) throws InvalidFormatException {
if (file.exists()) {
return open(file.getAbsolutePath());
} else {
return create(file);
}
}
/**
* Creates a new package.
*
* @param path
* Path of the document.
* @return A newly created PackageBase ready to use.
*/
public static OPCPackage create(String path) {
return create(new File(path));
}
/**
* Creates a new package.
*
* @param file
* Path of the document.
* @return A newly created PackageBase ready to use.
*/
public static OPCPackage create(File file) {
if (file == null || (file.exists() && file.isDirectory())) {
throw new IllegalArgumentException("file");
}
if (file.exists()) {
throw new InvalidOperationException(
"This package (or file) already exists : use the open() method or delete the file.");
}
// Creates a new package
OPCPackage pkg = new ZipPackage();
pkg.originalPackagePath = file.getAbsolutePath();
configurePackage(pkg);
return pkg;
}
public static OPCPackage create(OutputStream output) {
OPCPackage pkg = new ZipPackage();
pkg.originalPackagePath = null;
pkg.output = output;
configurePackage(pkg);
return pkg;
}
private static void configurePackage(OPCPackage pkg) {
try {
// Content type manager
pkg.contentTypeManager = new ZipContentTypeManager(null, pkg);
// Add default content types for .xml and .rels
pkg.contentTypeManager.addContentType(
PackagingURIHelper.createPartName(
PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI),
RELATIONSHIPS_PART);
pkg.contentTypeManager.addContentType(
PackagingURIHelper.createPartName("/default.xml"),
PLAIN_OLD_XML);
// Initialise some PackageBase properties
pkg.packageProperties = new PackagePropertiesPart(pkg,
PackagingURIHelper.CORE_PROPERTIES_PART_NAME);
pkg.packageProperties.setCreatorProperty("Generated by Apache POI OpenXML4J");
pkg.packageProperties.setCreatedProperty(Optional.of(new Date()));
} catch (InvalidFormatException e) {
// Should never happen
throw new IllegalStateException(e);
}
}
/**
* Flush the package : save all.
*
* @see #close()
*/
public void flush() {
throwExceptionIfReadOnly();
if (this.packageProperties != null) {
this.packageProperties.flush();
}
this.flushImpl();
}
/**
* Close the open, writable package and save its content.
*
* If your package is open read only, then you should call {@link #revert()}
* when finished with the package.
*
* This method is not thread-safe.
*
* @throws IOException
* If an IO exception occur during the saving process.
*/
@Override
public void close() throws IOException {
if (isClosed()) {
return;
}
if (this.packageAccess == PackageAccess.READ) {
LOG.atDebug().log("The close() method is intended to SAVE a package. This package is open in READ ONLY mode, use the revert() method instead!");
revert();
return;
}
if (this.contentTypeManager == null) {
LOG.atWarn().log("Unable to call close() on a package that hasn't been fully opened yet");
revert();
return;
}
if (StringUtil.isNotBlank(this.originalPackagePath)) {
File targetFile = new File(this.originalPackagePath);
if (!targetFile.exists()
|| !(this.originalPackagePath
.equalsIgnoreCase(targetFile.getAbsolutePath()))) {
// Case of a package created from scratch
save(targetFile);
} else {
closeImpl();
}
} else if (this.output != null) {
try {
save(this.output);
} finally {
output.close();
}
}
// ensure all held resources are freed
revert();
// Clear
this.contentTypeManager.clearAll();
}
/**
* Close the package WITHOUT saving its content. Reinitialize this package
* and cancel all changes done to it.
*/
public void revert() {
revertImpl();
}
/**
* Add a thumbnail to the package. This method is provided to make easier
* the addition of a thumbnail in a package. You can do the same work by
* using the traditional relationship and part mechanism.
*
* @param path The full path to the image file.
*/
public void addThumbnail(String path) throws IOException {
// Check parameter
if (path == null || path.isEmpty()) {
throw new IllegalArgumentException("path");
}
String name = path.substring(path.lastIndexOf(File.separatorChar) + 1);
try (InputStream is = Files.newInputStream(Paths.get(path))) {
addThumbnail(name, is);
}
}
/**
* Add a thumbnail to the package. This method is provided to make easier
* the addition of a thumbnail in a package. You can do the same work by
* using the traditional relationship and part mechanism.
*
* @param filename The full path to the image file.
* @param data the image data
*/
public void addThumbnail(String filename, InputStream data) throws IOException {
// Check parameter
if (filename == null || filename.isEmpty()) {
throw new IllegalArgumentException("filename");
}
// Create the thumbnail part name
String contentType = ContentTypes
.getContentTypeFromFileExtension(filename);
PackagePartName thumbnailPartName;
try {
thumbnailPartName = PackagingURIHelper.createPartName("/docProps/"
+ filename);
} catch (InvalidFormatException e) {
String partName = "/docProps/thumbnail" +
filename.substring(filename.lastIndexOf('.') + 1);
try {
thumbnailPartName = PackagingURIHelper.createPartName(partName);
} catch (InvalidFormatException e2) {
throw new InvalidOperationException(
"Can't add a thumbnail file named '" + filename + "'", e2);
}
}
// Check if part already exist
if (this.getPart(thumbnailPartName) != null) {
throw new InvalidOperationException(
"You already add a thumbnail named '" + filename + "'");
}
// Add the thumbnail part to this package.
PackagePart thumbnailPart = this.createPart(thumbnailPartName,
contentType, false);
// Add the relationship between the package and the thumbnail part
this.addRelationship(thumbnailPartName, TargetMode.INTERNAL,
PackageRelationshipTypes.THUMBNAIL);
// Copy file data to the newly created part
StreamHelper.copyStream(data, thumbnailPart.getOutputStream());
}
/**
* Throws an exception if the package access mode is in read only mode
* (PackageAccess.Read).
*
* @throws InvalidOperationException
* Throws if a writing operation is done on a read only package.
* @see PackageAccess
*/
void throwExceptionIfReadOnly() throws InvalidOperationException {
if (packageAccess == PackageAccess.READ) {
throw new InvalidOperationException(
"Operation not allowed, document open in read only mode!");
}
}
/**
* Throws an exception if the package access mode is in write only mode
* (PackageAccess.Write). This method is call when other methods need write
* right.
*
* @throws InvalidOperationException if a read operation is done on a write only package.
* @see PackageAccess
*/
void throwExceptionIfWriteOnly() throws InvalidOperationException {
if (packageAccess == PackageAccess.WRITE) {
throw new InvalidOperationException(
"Operation not allowed, document open in write only mode!");
}
}
/**
* Retrieves or creates if none exists, core package property part.
*
* @return The PackageProperties part of this package.
*/
public PackageProperties getPackageProperties()
throws InvalidFormatException {
this.throwExceptionIfWriteOnly();
// If no properties part has been found then we create one
if (this.packageProperties == null) {
this.packageProperties = new PackagePropertiesPart(this,
PackagingURIHelper.CORE_PROPERTIES_PART_NAME);
}
return this.packageProperties;
}
/**
* Retrieve a part identified by its name.
*
* @param partName
* Part name of the part to retrieve.
* @return The part with the specified name, else {@code null}.
*/
public PackagePart getPart(PackagePartName partName) {
throwExceptionIfWriteOnly();
if (partName == null) {
throw new IllegalArgumentException("partName");
}
// If the partlist is null, then we parse the package.
if (partList == null) {
try {
getParts();
} catch (InvalidFormatException e) {
return null;
}
}
return partList.get(partName);
}
/**
* Retrieve parts by content type.
*
* @param contentType
* The content type criteria.
* @return All part associated to the specified content type.
*/
public ArrayList<PackagePart> getPartsByContentType(String contentType) {
ArrayList<PackagePart> retArr = new ArrayList<>();
for (PackagePart part : partList.sortedValues()) {
if (part.getContentType().equals(contentType)) {
retArr.add(part);
}
}
return retArr;
}
/**
* Retrieve parts by relationship type.
*
* @param relationshipType
* Relationship type. Must not be {@code null}.
* @return All parts which are the target of a relationship with the
* specified type. If no such parts are found, the list is empty.
* @throws InvalidOperationException If called on a write-only package.
* @throws IllegalArgumentException if relationshipType input param is null.
*/
public ArrayList<PackagePart> getPartsByRelationshipType(
String relationshipType) {
if (relationshipType == null) {
throw new IllegalArgumentException("relationshipType");
}
ArrayList<PackagePart> retArr = new ArrayList<>();
for (PackageRelationship rel : getRelationshipsByType(relationshipType)) {
PackagePart part = getPart(rel);
if (part != null) {
retArr.add(part);
}
}
Collections.sort(retArr);
return retArr;
}
/**
* Retrieve parts by name
*
* @param namePattern
* The pattern for matching the names
* @return All parts associated to the specified content type, sorted
* in alphanumerically by the part-name
*/
public List<PackagePart> getPartsByName(final Pattern namePattern) {
if (namePattern == null) {
throw new IllegalArgumentException("name pattern must not be null");
}
Matcher matcher = namePattern.matcher("");
ArrayList<PackagePart> result = new ArrayList<>();
for (PackagePart part : partList.sortedValues()) {
PackagePartName partName = part.getPartName();
if (matcher.reset(partName.getName()).matches()) {
result.add(part);
}
}
return result;
}
/**
* Get the target part from the specified relationship.
*
* @param partRel
* The part relationship uses to retrieve the part.
*/
public PackagePart getPart(PackageRelationship partRel) {
PackagePart retPart = null;
ensureRelationships();
for (PackageRelationship rel : relationships) {
if (rel.getRelationshipType().equals(partRel.getRelationshipType())) {
try {
retPart = getPart(PackagingURIHelper.createPartName(rel
.getTargetURI()));
} catch (InvalidFormatException e) {
continue;
}
break;
}
}
return retPart;
}
/**
* Load the parts of the archive if it has not been done yet. The
* relationships of each part are not loaded.
*
* Note - Rule M4.1 states that there may only ever be one Core
* Properties Part, but Office produced files will sometimes
* have multiple! As Office ignores all but the first, we relax
* Compliance with Rule M4.1, and ignore all others silently too.
*
* @return All this package's parts.
* @throws InvalidFormatException if the package is not valid.
*/
public ArrayList<PackagePart> getParts() throws InvalidFormatException {
throwExceptionIfWriteOnly();
// If the part list is null, we parse the package to retrieve all parts.
if (partList == null) {
/* Variables use to validate OPC Compliance */
// Check rule M4.1 -> A format consumer shall consider more than
// one core properties relationship for a package to be an error
// (We just log it and move on, as real files break this!)
boolean hasCorePropertiesPart = false;
boolean needCorePropertiesPart = true;
partList = getPartsImpl();
for (PackagePart part : new ArrayList<>(partList.sortedValues())) {
part.loadRelationships();
// Check OPC compliance rule M4.1
if (ContentTypes.CORE_PROPERTIES_PART.equals(part.getContentType())) {
if (!hasCorePropertiesPart) {
hasCorePropertiesPart = true;
} else {
LOG.atWarn().log("OPC Compliance error [M4.1]: " +
"there is more than one core properties relationship in the package! " +
"POI will use only the first, but other software may reject this file.");
}
}
PartUnmarshaller partUnmarshaller = partUnmarshallers.get(part._contentType);
if (partUnmarshaller != null) {
UnmarshallContext context = new UnmarshallContext(this, part._partName);
try (InputStream partStream = part.getInputStream()) {
PackagePart unmarshallPart = partUnmarshaller.unmarshall(context, partStream);
partList.remove(part.getPartName());
partList.put(unmarshallPart._partName, unmarshallPart);
// Core properties case-- use first CoreProperties part we come across
// and ignore any subsequent ones
if (unmarshallPart instanceof PackagePropertiesPart &&
hasCorePropertiesPart &&
needCorePropertiesPart) {
this.packageProperties = (PackagePropertiesPart) unmarshallPart;
needCorePropertiesPart = false;
}
} catch (IOException ioe) {
LOG.atWarn().log("Unmarshall operation : IOException for {}", part._partName);
} catch (InvalidOperationException invoe) {
throw new InvalidFormatException(invoe.getMessage(), invoe);
}
}
}
}
return new ArrayList<>(partList.sortedValues());
}
/**
* Create and add a part, with the specified name and content type, to the
* package.
*
* @param partName
* Part name.
* @param contentType
* Part content type.
* @return The newly created part.
* @throws PartAlreadyExistsException
* If rule M1.12 is not verified : Packages shall not contain
* equivalent part names and package implementers shall neither
* create nor recognize packages with equivalent part names.
* @see #createPartImpl(PackagePartName, String, boolean)
*/
public PackagePart createPart(PackagePartName partName, String contentType) {
return this.createPart(partName, contentType, true);
}
/**
* Create and add a part, with the specified name and content type, to the
* package. For general purpose, prefer the overload version of this method
* without the 'loadRelationships' parameter.
*
* @param partName
* Part name.
* @param contentType
* Part content type.
* @param loadRelationships
* Specify if the existing relationship part, if any, logically
* associated to the newly created part will be loaded.
* @return The newly created part.
* @throws PartAlreadyExistsException
* If rule M1.12 is not verified : Packages shall not contain
* equivalent part names and package implementers shall neither
* create nor recognize packages with equivalent part names.
* @see #createPartImpl(PackagePartName, String, boolean)
*/
PackagePart createPart(PackagePartName partName, String contentType,
boolean loadRelationships) {
throwExceptionIfReadOnly();
if (partName == null) {
throw new IllegalArgumentException("partName");
}
if (contentType == null || contentType.isEmpty()) {
throw new IllegalArgumentException("contentType");
}
// Check if the specified part name already exists
if (partList.containsKey(partName)
&& !partList.get(partName).isDeleted()) {
throw new PartAlreadyExistsException(
"A part with the name '" + partName.getName() + "'" +
" already exists : Packages shall not contain equivalent part names and package" +
" implementers shall neither create nor recognize packages with equivalent part names. [M1.12]");
}
/* Check OPC compliance */
// Rule [M4.1]: The format designer shall specify and the format producer
// shall create at most one core properties relationship for a package.
// A format consumer shall consider more than one core properties
// relationship for a package to be an error. If present, the
// relationship shall target the Core Properties part.
// Note - POI will read files with more than one Core Properties, which
// Office sometimes produces, but is strict on generation
if (contentType.equals(ContentTypes.CORE_PROPERTIES_PART)) {
if (this.packageProperties != null) {
throw new InvalidOperationException(
"OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !");
}
}
/* End check OPC compliance */
PackagePart part = this.createPartImpl(partName, contentType,
loadRelationships);
/* check/create default entries - for bug54803 */
try {
PackagePartName ppn = PackagingURIHelper.createPartName("/."+EXTENSION_XML);
contentTypeManager.addContentType(ppn, PLAIN_OLD_XML);
ppn = PackagingURIHelper.createPartName("/"+RELATIONSHIP_PART_EXTENSION_NAME);
contentTypeManager.addContentType(ppn, RELATIONSHIPS_PART);
} catch (InvalidFormatException e) {
throw new InvalidOperationException("unable to create default content-type entries.", e);
}
this.contentTypeManager.addContentType(partName, contentType);
this.partList.put(partName, part);
this.isDirty = true;
return part;
}
/**
* Add a part to the package.
*
* @param partName
* Part name of the part to create.
* @param contentType
* type associated with the file
* @param content
* the contents to add. In order to have faster operation in
* document merge, the data are stored in memory not on a hard
* disk
*
* @return The new part.
* @see #createPart(PackagePartName, String)
*/
public PackagePart createPart(PackagePartName partName, String contentType,
ByteArrayOutputStream content) {
PackagePart addedPart = this.createPart(partName, contentType);
if (addedPart == null) {
return null;
}
// Extract the zip entry content to put it in the part content
if (content != null) {
try (OutputStream partOutput = addedPart.getOutputStream()) {
if (partOutput == null) {
return null;
}
content.writeTo(partOutput);
} catch (IOException ignored) {
return null;
}
} else {
return null;
}
return addedPart;
}
/**
* Add the specified part to the package. If a part already exists in the
* package with the same name as the one specified, then we replace the old
* part by the specified part.
*
* @param part
* The part to add (or replace).
* @return The part added to the package, the same as the one specified.
* @throws InvalidOperationException
* If rule M1.12 is not verified : Packages shall not contain
* equivalent part names and package implementers shall neither
* create nor recognize packages with equivalent part names.
*/
protected PackagePart addPackagePart(PackagePart part) {
throwExceptionIfReadOnly();
if (part == null) {
throw new IllegalArgumentException("part");
}
if (hasPackagePart(part)) {
if (!partList.get(part._partName).isDeleted()) {
throw new InvalidOperationException(
"A part with the name '"
+ part._partName.getName()
+ "' already exists : Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]");
}
// If the specified partis flagged as deleted, we make it
// available
part.setDeleted(false);
// and delete the old part to replace it thereafter
this.partList.remove(part._partName);
}
this.partList.put(part._partName, part);
this.isDirty = true;
return part;
}
protected boolean hasPackagePart(PackagePart part) {
return partList.containsKey(part._partName);
}
/**
* Remove the specified part in this package. If this part is relationship
* part, then delete all relationships in the source part.
*
* @param part
* The part to remove. If {@code null}, skip the action.
* @see #removePart(PackagePartName)
*/
public void removePart(PackagePart part) {
if (part != null) {
removePart(part.getPartName());
}
}
/**
* Remove a part in this package. If this part is relationship part, then
* delete all relationships in the source part.
*
* @param partName
* The part name of the part to remove.
*/
public void removePart(PackagePartName partName) {
throwExceptionIfReadOnly();
if (partName == null || !this.containPart(partName)) {
throw new IllegalArgumentException("partName");
}
// Delete the specified part from the package.
if (this.partList.containsKey(partName)) {
this.partList.get(partName).setDeleted(true);
this.removePartImpl(partName);
} else {
this.removePartImpl(partName);
}
// Delete content type
this.contentTypeManager.removeContentType(partName);
// If this part is a relationship part, then delete all relationships of
// the source part.
if (partName.isRelationshipPartURI()) {
URI sourceURI = PackagingURIHelper
.getSourcePartUriFromRelationshipPartUri(partName.getURI());
PackagePartName sourcePartName;
try {
sourcePartName = PackagingURIHelper.createPartName(sourceURI);
} catch (InvalidFormatException e) {
LOG.atError().log("Part name URI '{}' is not valid! This message is not intended to be displayed!", sourceURI);
return;
}
if (sourcePartName.getURI().equals(
PackagingURIHelper.PACKAGE_ROOT_URI)) {
clearRelationships();
} else if (containPart(sourcePartName)) {
PackagePart part = getPart(sourcePartName);
if (part != null) {
part.clearRelationships();
}
}
}
this.isDirty = true;
}
/**
* Remove a part from this package as well as its relationship part, if one
* exists, and all parts listed in the relationship part. Be aware that this
* do not delete relationships which target the specified part.
*
* @param partName
* The name of the part to delete.
* @throws InvalidFormatException
* Throws if the associated relationship part of the specified
* part is not valid.
*/
public void removePartRecursive(PackagePartName partName)
throws InvalidFormatException {
// Retrieves relationship part, if one exists
PackagePart relPart = this.partList.get(PackagingURIHelper
.getRelationshipPartName(partName));
// Retrieves PackagePart object from the package
PackagePart partToRemove = this.partList.get(partName);
if (relPart != null) {
PackageRelationshipCollection partRels = new PackageRelationshipCollection(
partToRemove);
for (PackageRelationship rel : partRels) {
PackagePartName partNameToRemove = PackagingURIHelper
.createPartName(PackagingURIHelper.resolvePartUri(rel
.getSourceURI(), rel.getTargetURI()));
removePart(partNameToRemove);
}
// Finally delete its relationship part if one exists
this.removePart(relPart._partName);
}
// Delete the specified part
this.removePart(partToRemove._partName);
}
/**
* Delete the part with the specified name and its associated relationships
* part if one exists. Prefer the use of this method to delete a part in the
* package, compare to the remove() methods that don't remove associated
* relationships part.
*
* @param partName
* Name of the part to delete
*/
public void deletePart(PackagePartName partName) {
if (partName == null) {
throw new IllegalArgumentException("partName");
}
// Remove the part
this.removePart(partName);
// Remove the relationships part
this.removePart(PackagingURIHelper.getRelationshipPartName(partName));
}
/**
* Delete the part with the specified name and all part listed in its
* associated relationships part if one exists. This process is recursively
* apply to all parts in the relationships part of the specified part.
* Prefer the use of this method to delete a part in the package, compare to
* the remove() methods that don't remove associated relationships part.
*
* @param partName
* Name of the part to delete
*/
public void deletePartRecursive(PackagePartName partName) {
if (partName == null || !this.containPart(partName)) {
throw new IllegalArgumentException("partName");
}
PackagePart partToDelete = this.getPart(partName);
// Remove the part
this.removePart(partName);
// Remove all relationship parts associated
try {
for (PackageRelationship relationship : partToDelete
.getRelationships()) {
PackagePartName targetPartName = PackagingURIHelper
.createPartName(PackagingURIHelper.resolvePartUri(
partName.getURI(), relationship.getTargetURI()));
this.deletePartRecursive(targetPartName);
}
} catch (InvalidFormatException e) {
LOG.atWarn().withThrowable(e).log("An exception occurs while deleting part '{}'. Some parts may remain in the package.", partName.getName());
return;
}
// Remove the relationships part
PackagePartName relationshipPartName = PackagingURIHelper
.getRelationshipPartName(partName);
if (relationshipPartName != null && containPart(relationshipPartName)) {
this.removePart(relationshipPartName);
}
}
/**
* Check if a part already exists in this package from its name.
*
* @param partName
* Part name to check.
* @return <i>true</i> if the part is logically added to this package, else
* <i>false</i>.
*/
public boolean containPart(PackagePartName partName) {
return (this.getPart(partName) != null);
}
/**
* Add a relationship to the package (except relationships part).
*
* Check rule M4.1 : The format designer shall specify and the format
* producer shall create at most one core properties relationship for a
* package. A format consumer shall consider more than one core properties
* relationship for a package to be an error. If present, the relationship
* shall target the Core Properties part.
*
* Check rule M1.25: The Relationships part shall not have relationships to
* any other part. Package implementers shall enforce this requirement upon
* the attempt to create such a relationship and shall treat any such
* relationship as invalid.
*
* @param targetPartName
* Target part name.
* @param targetMode
* Target mode, either Internal or External.
* @param relationshipType
* Relationship type.
* @param relID
* ID of the relationship.
* @see PackageRelationshipTypes
*/
@Override
public PackageRelationship addRelationship(PackagePartName targetPartName,
TargetMode targetMode, String relationshipType, String relID) {
/* Check OPC compliance */
// Check rule M4.1 : The format designer shall specify and the format
// producer
// shall create at most one core properties relationship for a package.
// A format consumer shall consider more than one core properties
// relationship for a package to be an error. If present, the
// relationship shall target the Core Properties part.
if (relationshipType.equals(PackageRelationshipTypes.CORE_PROPERTIES)
&& this.packageProperties != null) {
throw new InvalidOperationException(
"OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead.");
}
/*
* Check rule M1.25: The Relationships part shall not have relationships
* to any other part. Package implementers shall enforce this
* requirement upon the attempt to create such a relationship and shall
* treat any such relationship as invalid.
*/
if (targetPartName.isRelationshipPartURI()) {
throw new InvalidOperationException(
"Rule M1.25: The Relationships part shall not have relationships to any other part.");
}
/* End OPC compliance */
ensureRelationships();
PackageRelationship retRel = relationships.addRelationship(
targetPartName.getURI(), targetMode, relationshipType, relID);
this.isDirty = true;
return retRel;
}
/**
* Add a package relationship.
*
* @param targetPartName
* Target part name.
* @param targetMode
* Target mode, either Internal or External.
* @param relationshipType
* Relationship type.
* @see PackageRelationshipTypes
*/
@Override
public PackageRelationship addRelationship(PackagePartName targetPartName,
TargetMode targetMode, String relationshipType) {
return this.addRelationship(targetPartName, targetMode,
relationshipType, null);
}
/**
* Adds an external relationship to a part (except relationships part).
*
* The targets of external relationships are not subject to the same
* validity checks that internal ones are, as the contents is potentially
* any file, URL or similar.
*
* @param target
* External target of the relationship
* @param relationshipType
* Type of relationship.
* @return The newly created and added relationship
*/
@Override
public PackageRelationship addExternalRelationship(String target,
String relationshipType) {
return addExternalRelationship(target, relationshipType, null);
}
/**
* Adds an external relationship to a part (except relationships part).
*
* The targets of external relationships are not subject to the same
* validity checks that internal ones are, as the contents is potentially
* any file, URL or similar.
*
* @param target
* External target of the relationship
* @param relationshipType
* Type of relationship.
* @param id
* Relationship unique id.
* @return The newly created and added relationship
* @see RelationshipSource#addExternalRelationship(String,
* String)
*/
@Override
public PackageRelationship addExternalRelationship(String target,
String relationshipType, String id) {
if (target == null) {
throw new IllegalArgumentException("target");
}
if (relationshipType == null) {
throw new IllegalArgumentException("relationshipType");
}
URI targetURI;
try {
targetURI = new URI(target);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid target - " + e);
}
ensureRelationships();
PackageRelationship retRel = relationships.addRelationship(targetURI,
TargetMode.EXTERNAL, relationshipType, id);
this.isDirty = true;
return retRel;
}
/**
* Delete a relationship from this package.
*
* @param id
* Id of the relationship to delete.
*/
@Override
public void removeRelationship(String id) {
if (relationships != null) {
relationships.removeRelationship(id);
this.isDirty = true;
}
}
/**
* Retrieves all package relationships.
*
* @return All package relationships of this package.
* @throws InvalidOperationException if a read operation is done on a write only package.
* @see #getRelationshipsHelper(String)
*/
@Override
public PackageRelationshipCollection getRelationships() {
return getRelationshipsHelper(null);
}
/**
* Retrieves all relationships with the specified type.
*
* @param relationshipType
* The filter specifying the relationship type.
* @return All relationships with the specified relationship type.
*/
@Override
public PackageRelationshipCollection getRelationshipsByType(
String relationshipType) {
throwExceptionIfWriteOnly();
if (relationshipType == null) {
throw new IllegalArgumentException("relationshipType");
}
return getRelationshipsHelper(relationshipType);
}
/**
* Retrieves all relationships with specified id (normally just ine because
* a relationship id is supposed to be unique).
*
* @param id
* Id of the wanted relationship.
*/
private PackageRelationshipCollection getRelationshipsHelper(String id) {
throwExceptionIfWriteOnly();
ensureRelationships();
return this.relationships.getRelationships(id);
}
/**
* Clear package relationships.
*/
@Override
public void clearRelationships() {
if (relationships != null) {
relationships.clear();
this.isDirty = true;
}
}
/**
* Ensure that the relationships collection is not null.
*/
public void ensureRelationships() {
if (this.relationships == null) {
try {
this.relationships = new PackageRelationshipCollection(this);
} catch (InvalidFormatException e) {
this.relationships = new PackageRelationshipCollection();
}
}
}
@Override
public PackageRelationship getRelationship(String id) {
return this.relationships.getRelationshipByID(id);
}
@Override
public boolean hasRelationships() {
return !relationships.isEmpty();
}
@Override
public boolean isRelationshipExists(PackageRelationship rel) {
for (PackageRelationship r : relationships) {
if (r == rel) {
return true;
}
}
return false;
}
/**
* Add a marshaller.
*
* @param contentType
* The content type to bind to the specified marshaller.
* @param marshaller
* The marshaller to register with the specified content type.
*/
public void addMarshaller(String contentType, PartMarshaller marshaller) {
try {
partMarshallers.put(new ContentType(contentType), marshaller);
} catch (InvalidFormatException e) {
LOG.atWarn().log("The specified content type is not valid: '{}'. The marshaller will not be added !", e.getMessage());
}
}
/**
* Add an unmarshaller.
*
* @param contentType
* The content type to bind to the specified unmarshaller.
* @param unmarshaller
* The unmarshaller to register with the specified content type.
*/
public void addUnmarshaller(String contentType,
PartUnmarshaller unmarshaller) {
try {
partUnmarshallers.put(new ContentType(contentType), unmarshaller);
} catch (InvalidFormatException e) {
LOG.atWarn().log("The specified content type is not valid: '{}'. The unmarshaller will not be added !", e.getMessage());
}
}
/**
* Remove a marshaller by its content type.
*
* @param contentType
* The content type associated with the marshaller to remove.
*/
public void removeMarshaller(String contentType) {
try {
partMarshallers.remove(new ContentType(contentType));
} catch (InvalidFormatException e) {
throw new IllegalStateException(e);
}
}
/**
* Remove an unmarshaller by its content type.
*
* @param contentType
* The content type associated with the unmarshaller to remove.
*/
public void removeUnmarshaller(String contentType) {
try {
partUnmarshallers.remove(new ContentType(contentType));
} catch (InvalidFormatException e) {
throw new IllegalStateException(e);
}
}
/* Accesseurs */
/**
* Get the package access mode.
*
* @return the packageAccess The current package access.
*/
public PackageAccess getPackageAccess() {
return packageAccess;
}
/**
* Validates the package compliance with the OPC specifications.
*
* @return <b>true</b> if the package is valid else <b>false</b>
*/
@NotImplemented
public boolean validatePackage(OPCPackage pkg) throws InvalidFormatException {
throw new InvalidOperationException("Not implemented yet !!!");
}
/**
* Save the document in the specified file.
*
* @param targetFile
* Destination file.
* @throws IOException
* Throws if an IO exception occur.
* @see #save(OutputStream)
*/
public void save(File targetFile) throws IOException {
if (targetFile == null) {
throw new IllegalArgumentException("targetFile");
}
this.throwExceptionIfReadOnly();
// You shouldn't save the same file, do a close instead
if(targetFile.exists() &&
targetFile.getAbsolutePath().equals(this.originalPackagePath)) {
throw new InvalidOperationException(
"You can't call save(File) to save to the currently open " +
"file. To save to the current file, please just call close()"
);
}
// Do the save
try (OutputStream fos = Files.newOutputStream(targetFile.toPath())) {
this.save(fos);
}
}
/**
* Save the document in the specified output stream.
*
* @param outputStream
* The stream to save the package.
* @see #saveImpl(OutputStream)
*/
public void save(OutputStream outputStream) throws IOException {
throwExceptionIfReadOnly();
this.saveImpl(outputStream);
}
/**
* Core method to create a package part. This method must be implemented by
* the subclass.
*
* @param partName
* URI of the part to create.
* @param contentType
* Content type of the part to create.
* @return The newly created package part.
*/
protected abstract PackagePart createPartImpl(PackagePartName partName,
String contentType, boolean loadRelationships);
/**
* Core method to delete a package part. This method must be implemented by
* the subclass.
*
* @param partName
* The URI of the part to delete.
* @throws IllegalArgumentException if the partName is null.
* @throws InvalidOperationException if the package is in read-only mode.
*/
protected void removePartImpl(PackagePartName partName) {
if (partName == null) {
throw new IllegalArgumentException("partName cannot be null");
}
throwExceptionIfReadOnly();
this.partList.remove(partName);
}
/**
* Flush the package but not save.
*/
protected abstract void flushImpl();
/**
* Close the package and cause a save of the package.
*
*/
protected abstract void closeImpl() throws IOException;
/**
* Close the package without saving the document. Discard all changes made
* to this package.
*/
protected abstract void revertImpl();
/**
* Save the package into the specified output stream.
*
* @param outputStream
* The output stream use to save this package.
*/
protected abstract void saveImpl(OutputStream outputStream)
throws IOException;
/**
* Get all parts link to the package.
*
* @return A list of the part owned by the package.
*/
protected abstract PackagePartCollection getPartsImpl()
throws InvalidFormatException;
/**
* Replace a content type in this package.<p>
* A typical scenario to call this method is to rename a template file to the main format, e.g.
* <ul>
* <li>".dotx" to ".docx"</li>
* <li>".dotm" to ".docm"</li>
* <li>".xltx" to ".xlsx"</li>
* <li>".xltm" to ".xlsm"</li>
* <li>".potx" to ".pptx"</li>
* <li>".potm" to ".pptm"</li>
* </ul>
* For example, a code converting a .xlsm macro workbook to .xlsx would look as follows:
* <pre>{@code
*
* OPCPackage pkg = OPCPackage.open(new FileInputStream("macro-workbook.xlsm"));
* pkg.replaceContentType(
* "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
* "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml");
*
* try (FileOutputStream out = new FileOutputStream("workbook.xlsx")) {
* pkg.save(out);
* }
*
* }</pre>
*
* @param oldContentType the content type to be replaced
* @param newContentType the replacement
* @return whether replacement was successful
* @since POI-3.8
*/
public boolean replaceContentType(String oldContentType, String newContentType){
boolean success = false;
ArrayList<PackagePart> list = getPartsByContentType(oldContentType);
for (PackagePart packagePart : list) {
if (packagePart.getContentType().equals(oldContentType)) {
PackagePartName partName = packagePart.getPartName();
contentTypeManager.addContentType(partName, newContentType);
try {
packagePart.setContentType(newContentType);
} catch (InvalidFormatException e) {
throw new OpenXML4JRuntimeException("invalid content type - "+newContentType, e);
}
success = true;
this.isDirty = true;
}
}
return success;
}
/**
* Add the specified part, and register its content type with the content
* type manager.
*
* @param part
* The part to add.
*/
public void registerPartAndContentType(PackagePart part) {
addPackagePart(part);
this.contentTypeManager.addContentType(part.getPartName(), part.getContentType());
this.isDirty = true;
}
/**
* Remove the specified part, and clear its content type from the content
* type manager.
*
* @param partName
* The part name of the part to remove.
*/
public void unregisterPartAndContentType(PackagePartName partName) {
removePart(partName);
this.contentTypeManager.removeContentType(partName);
this.isDirty = true;
}
/**
* Get an unused part index based on the namePattern, which doesn't exist yet
* and has the lowest positive index
*
* @param nameTemplate
* The template for new part names containing a {@code '#'} for the index,
* e.g. "/ppt/slides/slide#.xml"
* @return the next available part name index
* @throws InvalidFormatException if the nameTemplate is null or doesn't contain
* the index char (#) or results in an invalid part name
*/
public int getUnusedPartIndex(final String nameTemplate) throws InvalidFormatException {
return partList.getUnusedPartIndex(nameTemplate);
}
/**
* @return true if the package is in Strict OOXML format
* @since POI 5.1.0
*/
public boolean isStrictOoxmlFormat() {
PackageRelationshipCollection coreDocRelationships = getRelationshipsByType(
PackageRelationshipTypes.STRICT_CORE_DOCUMENT);
return !coreDocRelationships.isEmpty();
}
/**
* Has close been called already?
*/
public abstract boolean isClosed();
@Override
public String toString() {
return "OPCPackage{" +
"packageAccess=" + packageAccess +
", relationships=" + relationships +
", packageProperties=" + packageProperties +
", isDirty=" + isDirty +
//", originalPackagePath='" + originalPackagePath + '\'' +
'}';
}
}
|