// pack.originalPackagePath = file.getAbsolutePath();
return pack;
} catch (InvalidFormatException | RuntimeException e) {
- IOUtils.closeQuietly(pack);
+ // use revert() to free resources when the packgae is opened read-only
+ pack.revert();
+
throw e;
}
}
*/
public static OPCPackage open(File file, PackageAccess access)
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");
- }
-
- OPCPackage pack = new ZipPackage(file, access);
+ if (file == null) {
+ throw new IllegalArgumentException("'file' must be given");
+ }
+ if (file.exists() && file.isDirectory()) {
+ throw new IllegalArgumentException("file must not be a directory");
+ }
+
+ OPCPackage pack = new ZipPackage(file, access);
try {
if (pack.partList == null && access != PackageAccess.WRITE) {
pack.getParts();
pack.originalPackagePath = file.getAbsolutePath();
return pack;
} catch (InvalidFormatException | RuntimeException e) {
- IOUtils.closeQuietly(pack);
+ if (access == PackageAccess.READ) {
+ pack.revert();
+ } else {
+ IOUtils.closeQuietly(pack);
+ }
throw e;
}
}
import org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException;
import org.apache.poi.openxml4j.opc.ContentTypes;
import org.apache.poi.openxml4j.opc.OPCPackage;
+import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.opc.TargetMode;
+import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource;
import org.apache.poi.util.TempFile;
import org.junit.jupiter.api.Test;
);
}
+ @Test
+ void testInvalidformatExceptionZipSource() throws IOException {
+ try (AesZipFileZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(
+ POIDataSamples.getOpenXML4JInstance().openResourceAsStream("OPCCompliance_DerivedPartNameFAIL.docx"))) {
+ assertThrows(InvalidFormatException.class, () ->
+ OPCPackage.open(source),
+ "Should fail for invalid file"
+ );
+ }
+ }
+
+ @Test
+ void testInvalidformatExceptionFile() {
+ assertThrows(InvalidFormatException.class,
+ () -> OPCPackage.open(POIDataSamples.getOpenXML4JInstance().
+ getFile("OPCCompliance_DerivedPartNameFAIL.docx"), PackageAccess.READ),
+ "Should fail for invalid file"
+ );
+ }
+
/**
* Rule M1.12 : Packages shall not contain equivalent part names and package
* implementers shall neither create nor recognize packages with equivalent